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.
| Technique | How | Good for |
|---|---|---|
| Atomic conditional update | UPDATE seats SET holder=? WHERE id=? AND holder IS NULL (check rowcount) | single-row races; simplest correct answer |
| Pessimistic lock | SELECT … FOR UPDATE inside a transaction | short critical sections on one DB |
| Optimistic concurrency | version column; UPDATE … WHERE version = v; retry on conflict | low contention, many readers |
| Distributed lock / lease | Redis SET key val NX PX ttl, ZooKeeper/etcd with fencing tokens | coordinating across services; holds with expiry |
| Serialize through a queue | partition by resource id, one consumer per partition applies requests in order | extreme contention (auctions, order books) |
| Reservation / hold | temporary hold with expiry, confirm on payment | multi-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.