Concurrency & Failure Modes
The 12 classic concurrency and distributed-systems bugs unified under one root cause (TOCTOU): state changes in the gap between check and use.
One root cause: the TOCTOU gap
Every concurrency bug is the same race at a different boundary:
Actor A: [ check state ] ──── gap (reality changes!) ────▶ [ act on stale state ]Actor B: ▲ mutates state hereThree universal fixes:
- Collapse check + act atomically: atomic SQL, Lua scripts,
SELECT ... FOR UPDATE,SERIALIZABLE. - Version or fence every action: optimistic locking, fencing tokens, idempotency keys, entity sequences.
- Dampen synchronized herds: jitter, singleflight, circuit breakers, canonical lock ordering.
Family 1: Inside one database
Step through Lost Update vs Write Skew below — they look identical until you watch which rows get written.
interactive · switch anomaly, flip broken vs fixed, or step line by line
0 doctors on call — disjoint row writes broke the invariantwrote different rows
- 1. Lost update: two read-modify-write cycles overwrite each other (both
read
10, both write11). Fix with optimistic locking (WHERE version = :expected) or atomic SQL:
UPDATE counters SET value = value + 1 WHERE id = 1;- 2. Write skew: two transactions read the same premise then write
different rows, breaking a multi-row invariant (“at least one doctor on
call”). Row locks on written rows don’t help; use
SERIALIZABLEor lock the rows you read:
SELECT * FROM on_call WHERE shift = 1 FOR UPDATE;- 3. Phantom / non-repeatable reads: repeating a query in one transaction
returns changed values or newly inserted rows; fix with
REPEATABLE READ(snapshot isolation) orSERIALIZABLE. - 4. Deadlock: Tx A locks
Xwaiting forYwhile Tx B locksYwaiting forX; fix with canonical lock ordering (sort IDs ascending), short transactions, and lock timeouts.
Family 2: Across two systems
Crossing any store or network boundary drops single-database transactions:
- 5. Duplicate processing: at-least-once queues and client retries run the
same mutation twice (Idempotency, Retries & Outbox);
fix with an idempotency key +
UNIQUEconstraint:
INSERT INTO payments (idempotency_key, amount)VALUES (:key, :amount)ON CONFLICT (idempotency_key) DO NOTHING;- 6. Dual write problem: crashing between a DB commit and a Kafka publish causes permanent drift; fix with the outbox pattern (same DB transaction + async relay) or CDC.
- 7. Cache stampede / thundering herd: a hot key expires and concurrent misses flatten the DB (Caching & Failure Modes); fix with singleflight coalescing, jittered TTLs, or early background refresh.
- 8. Stale reads / replication lag: reading an async replica right after a primary write misses your own update (Replication & Quorums); fix by routing read-your-writes to the primary, pinning sessions, or passing an LSN token.
Family 3: Across time & networks
No shared clock, reordered packets, and sudden GC pauses break naive timing:
- 9. Out-of-order events: delayed updates overwrite newer state; attach a
monotonic per-entity version (reject
incoming_version <= current_version) and partition streams by entity key. - 10. Split brain / expired locks: a partition creates two leaders (split-brain) or a GC pause expires a lease mid-write (Distributed Locks & Fencing Tokens, Consensus & Raft); fix with Raft/etcd leadership and storage-verified fencing tokens.
- 11. Retry storms: synchronized retries amplify load on a struggling service (Load Balancing & Circuit Breakers); fix with exponential backoff with jitter, retry budgets, and a circuit breaker.
- 12. Clock skew: NTP drift or backward jumps break wall-clock ordering (Distributed Unique IDs); fix with logical clocks (Lamport / HLC) or monotonic DB sequences.
Quick reference: 12 bugs at a glance
| # | Failure mode | Boundary | Primary fix |
|---|---|---|---|
| 1 | Lost update | Same DB row | Atomic SQL or optimistic version check |
| 2 | Write skew | Different DB rows | SERIALIZABLE or SELECT ... FOR UPDATE |
| 3 | Phantoms | Repeated DB query | REPEATABLE READ / SERIALIZABLE |
| 4 | Deadlock | Multi-row locks | Canonical lock order + short tx + timeouts |
| 5 | Duplicates | Network / queue | Idempotency-Key + UNIQUE constraint |
| 6 | Dual write | DB ↔ Kafka | Transactional Outbox or CDC |
| 7 | Cache stampede | Cache ↔ DB | Singleflight + TTL jitter + early refresh |
| 8 | Stale reads | Primary ↔ Replica | Read-your-writes on primary / LSN token |
| 9 | Out-of-order | Async events | Per-entity version + partition by key |
| 10 | Split brain / lock | Nodes ↔ Storage | Raft consensus + leases + fencing tokens |
| 11 | Retry storms | Service ↔ Service | Exp backoff + jitter + circuit breaker |
| 12 | Clock skew | Cross-machine time | Logical clocks / DB sequence / monotonic |
lesson
When asked “what can go wrong here?”, walk the three boundaries: inside the DB (lost update / write skew), across stores (dual write / duplicates / stampede / lag), and across time (expired locks / out-of-order / retries / clocks).
Where this shows up in system design
- Design Ticketmaster / BookingLost updates, write skew (double-booking the last seat), and deadlocks when locking multiple seats in one cart.
- Design Stripe / PaymentsDuplicate processing (idempotency keys), dual writes (ledger DB + webhook outbox), and retry storms.
- Design Twitter / InstagramCache stampedes on celebrity profiles, replication lag after posting, and out-of-order feed updates.
- Design Distributed Cron / SchedulerExpired locks under GC pauses (fencing tokens), split-brain leaders (Raft/etcd), and clock skew.
Check yourself: spot the failure mode
interactive · diagnose which of the 12 failure modes is happening and pick the right fix
01 · Double-booked meeting room
same premise read · different rows inserted · invariant broken
Two users simultaneously check 'SELECT * FROM bookings WHERE room = 5 AND slot = 2pm' (returns 0 rows). Both insert their own new booking row for room 5 at 2pm. Neither row conflicts with the other's primary key.
Select an option to check the trade-off.
02 · Order saved, email never sent
DB + Kafka · crash between steps · permanent drift
Your checkout service commits an order to PostgreSQL, then calls kafka.publish('order.created'). The pod gets OOM-killed right after the DB commit, so the Kafka event is never published.
Select an option to check the trade-off.
03 · Outdated profile overwrites newer edit
async consumer · event reordering · stale overwrite
A user updates their bio twice in one second (v1 -> v2 -> v3). Due to network retries, the v2 event arrives at the search indexer AFTER v3 and overwrites the index with stale v2 text.
Select an option to check the trade-off.
idempotencyreliability
Property where repeating the exact same request multiple times produces the same final state as executing it once.
outbox patternmessaging
Writing a domain change and its outgoing event to the same DB transaction, then relaying the event asynchronously to avoid dual writes.
singleflightcaching
Coalescing concurrent identical cache misses inside a process so only one request queries the DB and shares the result.
monotonicordering
Always moving in one direction: every newly generated value is strictly greater than (or never less than) the previous one.
split-brainconsensus
A failure where a network partition tricks two nodes into believing they are both the active leader and accepting conflicting writes.
leasecoordination
Time-bounded exclusive ownership of a resource (like a machine ID or lock) that expires automatically if the holder crashes.
fencing tokencoordination
A strictly increasing number issued with every lock grant; storage rejects any write carrying an older token than the highest seen.
circuit breakerresilience
A state machine (closed, open, half-open) that trips to fail fast when a downstream dependency is failing, avoiding cascading stalls.