ApexAdvancedtransactionsconcurrencysoql
Use FOR UPDATE SOQL to prevent lost updates in concurrent Apex
Real World Scenario
Two batch jobs allocate inventory from same Product stock field causing oversell when both read quantity 10 and each decrements by 8.
Expected Answer
• FOR UPDATE in SOQL locks rows until transaction end
• Re-read quantity inside lock before decrement validation
• Minimize lock duration—no callouts inside locked transaction
• Row lock exception catch with retry in batch execute
• Alternative: optimistic locking with version field compare
• Avoid locking hot parent rows—partition inventory by warehouse
• Test concurrent futures simulating parallel batch execute
Follow-Up Questions & Answers
Click to expand — each follow-up includes a direct, interview-ready answer
Never fail silently. FOR UPDATE in SOQL locks rows until transaction end. Implement retry with exponential backoff and a dead-letter queue for permanent failures. Inventory and financial allocation need explicit concurrency strategy—not hope batch schedules dont overlap. Optimize for scale and operational observability.
Architect Perspective
Inventory and financial allocation need explicit concurrency strategy—not hope batch schedules dont overlap.