Handling race conditions

A race condition occurs when the outcome depends on the order or timing of concurrent operations (e.g. two requests reading then updating the same counter). Handling them means making the “read–modify–write” or “check–then–act” sequence atomic (e.g. with locks, DB constraints, or atomic operations).

Classic race: two updates overwrite

sequenceDiagram participant A as Request A participant B as Request B participant DB as DB A->>DB: SELECT balance (100) B->>DB: SELECT balance (100) A->>DB: UPDATE balance = 100 - 50 B->>DB: UPDATE balance = 100 - 30 Note over DB: Balance = 70 (lost A's update)

Solutions

flowchart TB R[Race-prone: read then write] --> A[Atomic DB op] R --> L[Lock (pessimistic)] R --> O[Version check (optimistic)] R --> Q[Single writer queue]

Identify critical sections (shared state, counters, inventory). Prefer atomic DB operations; use locking or versioning when you must read then write in app.