{}DSA Atlas

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.

Advanced6 interview questions

Races are everywhere in web backends

Every request runs concurrently with others, across many servers. The classic bugs:

BugScenario
Check-then-act"if username not taken → insert" — two signups take the same name
Lost updatetwo admins edit the same product; the second save silently overwrites the first
Overselltwo buyers get the last item
Double spendtwo concurrent withdrawals both see enough balance
Double submita double click creates two orders
Duplicate processinga retried message charges a card twice
Stale cache writeslow 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.

SQL
-- 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

Alice API Bob GET → ETag "v7" GET → ETag "v7" PATCH If-Match: "v7" 200, ETag "v8" PATCH If-Match: "v7" 412 Precondition Failed → refetch, merge
No locks held between requests; conflicts are detected at write time.
Python
@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

SQL
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.

OptimisticPessimistic
Contentionlow–mediumhigh
Across user think-time / HTTP requests✓✗ (can't hold locks)
Failure moderetries / 412waiting, 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"):

Python
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
Client 1 Lock service Client 2 Storage lock granted, token 33 GC pause… lease expires lock granted, token 34 write (token 34) ✓ write (token 33) → rejected: 33 < 34 storage remembers the highest token it has accepted
Leases alone can't stop a paused client; fencing tokens checked by the storage can.
Lock backendSafetyNotes
Redis SET NX PX (single node)efficiency onlylost on failover; no fencing
Redlock (multiple Redis nodes)debatedrelies on timing assumptions (see Kleppmann vs antirez)
etcd / ZooKeeper / Consulstrong (consensus)leases + monotonic revision usable as fencing tokens
Database row lock / advisory lockstrong within that DBpg_advisory_lock, SELECT … FOR UPDATE

Tool 5: transactional outbox + idempotent consumers

Order serviceone transaction Orders DB orders (INSERT) outbox (INSERT event) relay / CDC(Debezium) Kafka consumersinbox: dedupe event_id
The event is written atomically with the data; delivery is at-least-once, so consumers dedupe.
SQL
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

  1. Can a unique constraint or atomic UPDATE enforce the rule? Do that first.
  2. Updates by humans → optimistic locking (ETag/If-Match).
  3. Short, hot critical sections → row locks with consistent ordering.
  4. Cross-service effects → outbox + idempotent consumers.
  5. Retries anywhere → idempotency keys.
  6. Distributed locks only with leases + fencing, preferably on a consensus store.

Interview questions

0 / 6 marked confident

Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.