skip to content
jaeaeichsysdes

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 here

Three 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

t1Tx ASELECT count(*) FROM on_call WHERE shift = 1sees 2 doctors
t2Tx BSELECT count(*) FROM on_call WHERE shift = 1sees 2 doctors
t3Tx AUPDATE on_call SET active = false WHERE doc = 'Alice'commits (row A)
t4Tx BUPDATE on_call SET active = false WHERE doc = 'Bob'commits (row B) → 0 on call!

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 write 11). 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 SERIALIZABLE or 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) or SERIALIZABLE.
  • 4. Deadlock: Tx A locks X waiting for Y while Tx B locks Y waiting for X; 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:

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:

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.

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.

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.

esc
⌘B sidebar[ ] prev/next1–5 flowsc copyt theme