Concurrency & Consistency in Backends
Race conditions in web systems (double submit, oversell, double spend, lost updates), fixing them with atomic SQL, constraints, optimistic locking via version columns and ETag/If-Match, pessimistic row locks, distributed locks with leases and fencing tokens, the transactional outbox and inbox patterns, and ordering guarantees.
Races are everywhere in web backends
Every request runs concurrently with others, across many servers. The classic bugs:
| Bug | Scenario |
|---|---|
| Check-then-act | "if username not taken → insert" — two signups take the same name |
| Lost update | two admins edit the same product; the second save silently overwrites the first |
| Oversell | two buyers get the last item |
| Double spend | two concurrent withdrawals both see enough balance |
| Double submit | a double click creates two orders |
| Duplicate processing | a retried message charges a card twice |
| Stale cache write | slow request writes an old value into the cache after a newer one |
Tool 1: atomic statements and constraints
Push the invariant into one atomic database operation or a constraint.
-- unique business rules: the database settles races
CREATE UNIQUE INDEX users_username ON users (lower(username));
CREATE UNIQUE INDEX one_active_sub ON subscription (user_id) WHERE status = 'active';
-- conditional, atomic decrement (no oversell)
UPDATE inventory SET available = available - $qty
WHERE sku = $sku AND available >= $qty; -- 0 rows → insufficient stock
-- atomic withdrawal (no double spend)
UPDATE account SET balance = balance - $amt
WHERE id = $id AND balance >= $amt
RETURNING balance;
-- invariants as constraints
ALTER TABLE account ADD CONSTRAINT non_negative CHECK (balance >= 0);
Tool 2: optimistic locking
@app.patch("/documents/{doc_id}")
def update_document(doc_id: int, body: DocPatch, if_match: str = Header(...)):
expected = int(if_match.strip('"').removeprefix("v"))
row = db.one(
"""UPDATE document SET title = COALESCE(%s, title), body = COALESCE(%s, body),
version = version + 1
WHERE id = %s AND version = %s
RETURNING id, title, body, version""",
(body.title, body.body, doc_id, expected))
if row is None:
raise HTTPException(412, "Document was modified by someone else")
return JSONResponse(row, headers={"ETag": f'"v{row["version"]}"'})
Tool 3: pessimistic locking
BEGIN;
SELECT * FROM seat WHERE show_id = 77 AND seat_no = 'C12' FOR UPDATE; -- others wait here
-- check it's free, then:
UPDATE seat SET status = 'held', held_by = 42, held_until = now() + interval '10 min'
WHERE show_id = 77 AND seat_no = 'C12';
COMMIT;
Keep lock scopes tiny, lock rows in a consistent order (sort ids) to avoid deadlocks, use NOWAIT/SKIP LOCKED where waiting is pointless, and never hold a DB lock across a network call to another service.
| Optimistic | Pessimistic | |
|---|---|---|
| Contention | low–medium | high |
| Across user think-time / HTTP requests | ✓ | ✗ (can't hold locks) |
| Failure mode | retries / 412 | waiting, deadlocks |
Tool 4: distributed locks (carefully)
When the protected resource isn't a single database row (e.g. "only one worker runs the nightly billing job", "only one process regenerates this cache entry"):
import uuid
RELEASE = """
if redis.call('GET', KEYS[1]) == ARGV[1] then
return redis.call('DEL', KEYS[1])
end
return 0
"""
def with_lock(r, name, ttl_ms, fn):
token = str(uuid.uuid4())
if not r.set(f"lock:{name}", token, nx=True, px=ttl_ms): # acquire with a lease
return None # someone else holds it
try:
return fn()
finally:
r.eval(RELEASE, 1, f"lock:{name}", token) # release only our own lock
| Lock backend | Safety | Notes |
|---|---|---|
Redis SET NX PX (single node) | efficiency only | lost on failover; no fencing |
| Redlock (multiple Redis nodes) | debated | relies on timing assumptions (see Kleppmann vs antirez) |
| etcd / ZooKeeper / Consul | strong (consensus) | leases + monotonic revision usable as fencing tokens |
| Database row lock / advisory lock | strong within that DB | pg_advisory_lock, SELECT … FOR UPDATE |
Tool 5: transactional outbox + idempotent consumers
BEGIN;
INSERT INTO orders (id, customer_id, total_cents, status) VALUES ('ord_9', 42, 99800, 'placed');
INSERT INTO outbox (id, aggregate_type, aggregate_id, type, payload)
VALUES (gen_random_uuid(), 'order', 'ord_9', 'OrderPlaced', '{"order_id":"ord_9","total_cents":99800}');
COMMIT;
-- consumer side (inbox): dedupe in the same transaction as the side effect
BEGIN;
INSERT INTO processed_event (event_id) VALUES ($1) ON CONFLICT DO NOTHING; -- 0 rows → duplicate, skip
-- ... apply side effect ...
COMMIT;
Ordering
- Partition by entity key (Kafka key =
order_id) → per-entity order. - Include a version in events; consumers ignore stale versions.
- Avoid relying on global order; design for commutative or version-guarded updates.
Caching races
- Cache-aside stale write: request A reads old value from DB, request B updates DB and deletes the cache, then A writes its old value into the cache. Mitigate with short TTLs, versioned cache values (only write if newer), or delete-after-write with a delay ("double delete").
- Thundering herd on expiry: request coalescing / single-flight, probabilistic early refresh. See Caching.
Checklist
- Can a unique constraint or atomic UPDATE enforce the rule? Do that first.
- Updates by humans → optimistic locking (ETag/If-Match).
- Short, hot critical sections → row locks with consistent ordering.
- Cross-service effects → outbox + idempotent consumers.
- Retries anywhere → idempotency keys.
- Distributed locks only with leases + fencing, preferably on a consensus store.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.