Domain-Driven Design (50 Qs)•Part 3: Advanced Architecture & Production Patterns (Senior / Lead)
How do you handle Concurrency and Race Conditions on Aggregate Roots?
senior LevelSystem Design
In Simple Words: Use Optimistic Concurrency Control (OCC):
- Store a
versioninteger on the Aggregate Root. - When committing updates via the repository:
UPDATE orders SET status = 'CANCELLED', version = 4 WHERE id = 'ORD-101' AND version = 3; - If another concurrent request already updated the aggregate (version is already 4), the update affects 0 rows.
- The repository throws a
ConcurrencyException, and the application service reloads the latest state and retries the business operation.