SDE & MLE Prep

Dealing with Contention

When: many users compete for the same thing — the last concert seat, an item in a flash sale, a username, a bid, a bank balance.

TechniqueHowGood for
Atomic conditional updateUPDATE seats SET holder=? WHERE id=? AND holder IS NULL (check rowcount)single-row races; simplest correct answer
Pessimistic lockSELECT … FOR UPDATE inside a transactionshort critical sections on one DB
Optimistic concurrencyversion column; UPDATE … WHERE version = v; retry on conflictlow contention, many readers
Distributed lock / leaseRedis SET key val NX PX ttl, ZooKeeper/etcd with fencing tokenscoordinating across services; holds with expiry
Serialize through a queuepartition by resource id, one consumer per partition applies requests in orderextreme contention (auctions, order books)
Reservation / holdtemporary hold with expiry, confirm on paymentmulti-step checkout (tickets, hotels)

Discuss: what happens when the lock holder crashes (TTL/lease), double-submits (idempotency key), and whether a virtual waiting room should limit how many users even reach the contended step.