System designPatterns8 min read

Dealing with Contention: When Everyone Wants the Last Seat

This lesson is for software engineers preparing for system design interviews where many users compete for the same thing: the last concert seat, a limited product drop, a shared counter, a meeting room. These problems look simple until two requests arrive in the same millisecond. By the end you will be able to pick the right concurrency control for the load, explain what each one costs, and survive the follow-up questions interviewers use to separate memorized answers from understanding.

Why contention is its own problem

Most scaling advice spreads load across many machines. Contention is the opposite: the load lands on one row, one key or one object, and adding machines does not help because they all wait for the same thing.

Put numbers on it. A sneaker drop has 1,000 pairs, and 200,000 people press "Buy" in the first minute. That averages about 3,300 requests per second, and the first few seconds are far busier. Every one of those requests wants to decrement the same stock count. If each purchase holds a lock on that row for 5 milliseconds, the row can serve at most 1,000 / 5 = 200 purchases per second, no matter how big the database is. Everything above that queues, times out or fails.

The interviewer is checking two things here: correctness (never sell seat 14C twice, never sell pair 1,001) and throughput under contention (not collapsing when the crowd arrives). Name both before you pick a technique.

The options, from simplest to most involved

1. Pessimistic locking

Lock the row before you read it, so nobody else can change it until you commit:

BEGIN;
SELECT remaining FROM inventory WHERE sku = 'SNKR-42' FOR UPDATE;
-- application checks remaining > 0
UPDATE inventory SET remaining = remaining - 1 WHERE sku = 'SNKR-42';
INSERT INTO orders (user_id, sku) VALUES (123, 'SNKR-42');
COMMIT;

It is correct and easy to reason about. The cost is that the lock is held for the whole transaction, including any slow application logic or network round trip in the middle. That is what caps you at a few hundred operations per second on a hot row. Use it when contention is moderate and correctness matters more than speed, such as transferring money between two accounts. Lock rows in a consistent order (for example, by account id) or two transactions can deadlock waiting on each other.

2. Optimistic concurrency control

Do not lock. Read the row with a version number, do your work, then write only if nobody changed it in the meantime:

-- read: remaining = 7, version = 41
UPDATE inventory
SET remaining = 6, version = 42
WHERE sku = 'SNKR-42' AND version = 41;
-- 1 row updated: success. 0 rows: someone else won; re-read and retry.

This is compare-and-set. It shines when conflicts are rare, such as two people editing the same profile, because nobody waits. It degrades badly when conflicts are common: with thousands of buyers on one row, almost every attempt fails and retries, and the retries add more load. Say this out loud when you propose it; it is the follow-up the interviewer is waiting for.

3. Atomic conditional updates

Often you need neither a read nor a lock. Push the check into a single statement the database executes atomically:

UPDATE inventory
SET remaining = remaining - 1
WHERE sku = 'SNKR-42' AND remaining > 0;
-- 1 row: you got one. 0 rows: sold out.

The row is still locked, and in PostgreSQL or MySQL that lock lasts until the transaction commits, not until the statement ends. Run on its own (autocommit), the hold is one statement plus the commit's log flush, with no application round trip in the middle: roughly a millisecond instead of the 5 in the example above, so the same row serves several times as many purchases. Wrap the update in a longer transaction and the lock lasts for all of it, so if the order insert must commit with the decrement, do it immediately after and call nothing slow before the commit. The same idea works in an in-memory store with an atomic decrement (a Redis script that checks and decrements), which skips the disk flush entirely. This is the right default for counters and stock levels.

4. Reservations with expiry

Some flows need time between choosing and paying. A ticket buyer picks seat 14C, then spends three minutes entering card details. You cannot hold a database lock for three minutes, so you hold the seat itself:

  • Set the seat's status to held, with held_by and hold_expires_at (say, 10 minutes out), using an atomic conditional update that only succeeds if the seat is available or its hold has expired.

  • On payment success, move it to sold.

  • If the hold expires, the seat becomes available again. Either a sweeper job releases expired holds or every read treats an expired hold as available.

This turns a long transaction into two short ones and makes the waiting visible to users ("your seats are held for 10 minutes"). The trade-off is that some held seats go unsold until they expire, which you can tune with the hold length.

5. Distributed locks

When the contended thing is not a database row (a file, a job that must run once, a call to an external system), teams reach for a lock in a coordination service or an in-memory store, acquired with a time limit called a lease.

The trap is the lease. If the lock holder pauses (a long garbage-collection pause, a slow network) past the lease, the lock expires, a second process acquires it, and now two processes both believe they hold it. The fix is a fencing token: every time the lock is granted, the lock service hands out a number that only ever increases. The protected resource remembers the highest token it has seen and rejects any write carrying a lower one. The paused process wakes up with token 33, the resource has already seen 34, and the stale write is refused.

If you mention distributed locks without leases and fencing, expect the interviewer to ask "what happens if the holder pauses?" Have the answer ready.

6. Queue the contended work

When demand vastly exceeds supply, stop letting everyone fight over the row. Put purchase requests into a queue and let a single consumer, or one consumer per item, process them in order. The database sees a steady, serialized stream it can handle, and users see "you are in line" instead of errors. The cost is latency and a more complex user experience (a waiting room, then a result). Large ticket on-sales commonly use a virtual waiting room for exactly this reason: it admits buyers at a rate the inventory system can absorb.

Contention across shards

Everything above assumes the contended data lives on one database. Two cases break that:

  • One hot item on one shard. Split the item. Store the 1,000 pairs as 10 buckets of 100 on different rows or shards; each purchase picks a bucket at random and atomically decrements it, falling back to another bucket when one empties. Ten rows absorb ten times the load. The cost is a slightly more complex "sold out" check.

  • One operation touching two shards. Moving money from an account on shard A to one on shard B cannot use a single local transaction. Either design the partition key so related data lands together, or run the operation as a multi-step process with compensation (see Multi-Step Processes). Partitioning itself is covered in Scaling Data.

Worked example: the sneaker drop

Prompt: "Design checkout for a limited drop: 1,000 pairs, 200,000 buyers at 10."

A weak answer: "I'll use a transaction with SELECT FOR UPDATE so we never oversell." Correct, but it ignores the numbers. At 5 ms per locked transaction the row serves 200 purchases per second while 3,300 arrive, so most buyers get timeouts and the database spends its time managing lock waits.

A strong answer walks the load first and then layers techniques:

  1. Gate the crowd. A waiting room admits buyers at, say, 500 per second. The checkout path now sees a rate it can serve.

  2. Claim stock atomically. An atomic conditional decrement on the stock count, split across 10 buckets of 100, so no single row is a bottleneck.

  3. Hold, then pay. A successful decrement creates a reservation that expires in 10 minutes. Payment converts it to an order; expiry returns the unit to its bucket.

  4. Make payment idempotent. The client sends an idempotency key so a retried "Pay" never charges twice.

  5. Detect failure. Alert if orders exceed 1,000 (oversell) or if expired holds are not being released (stock stuck).

What earns the points is the reasoning: the candidate computed the per-row ceiling (deep dive and scalability), chose the cheapest correct technique for each step and said why the others lose here (trade-offs), and named how the system could still fail.

Follow-ups to expect

  • "Why not optimistic locking here?" Because conflicts are the normal case, not the exception; retries would multiply the load.

  • "What if the process crashes after the decrement but before the reservation is written?" Do both in one local transaction, or make the reservation the thing you decrement against so there is only one write.

  • "How do you avoid deadlocks?" Acquire locks in a fixed order and keep transactions short; most databases detect deadlocks and abort one side, so the caller must retry.

  • "How do you know you never oversold?" A database constraint (remaining >= 0) as a last line of defense, plus a reconciliation job comparing orders to supply.

What changes with seniority

A mid-level candidate is expected to spot the race condition and fix it with locking or an atomic update. A senior candidate quantifies the per-row ceiling, picks different techniques for different steps, and handles crashes between steps. A staff-level candidate also talks about the product and operational side: waiting rooms, hold lengths as a business lever, and how to detect and repair oversells in production.

Mistakes that cost points

  • Check-then-act in application code. Reading remaining, checking it in the app, then writing it back without a lock or condition is the race condition itself.

  • Long transactions. Calling a payment provider while holding a row lock turns a 5 ms lock into a 2 second one.

  • Distributed locks without fencing. A lease alone does not guarantee mutual exclusion.

  • Ignoring the arithmetic. Without the per-row throughput number you cannot justify any choice.

Practice it

Take ten minutes and redo the worked example for a concert with assigned seats instead of identical sneakers: what changes when every unit is distinct? Compare your answer with the ticket booking breakdown. Then practice the pattern where it appears in a full design: the short-code counter in Design a URL Shortener, and per-conversation message ordering in Design a Real-Time Chat System.

Practise this in a mock interview

Try what this lesson covers out loud: the AI interviewer asks one of these questions, follows up, and scores your answer.

Read next

  • Multi-Step Processes and Long-Running Jobs

    Design flows that span services so they finish or cleanly undo themselves, with sagas, compensations, idempotent retries, the outbox pattern and durable workflows, and run long jobs with status, heartbeats and dead-letter queues.

    8 min read

  • Handling Large Files: Uploads, Processing and Delivery

    Keep large files off your API servers with presigned and resumable multipart uploads, keep metadata and stored bytes consistent, process files after upload, and deliver them through a CDN with range requests.

    7 min read

  • Scaling Reads

    Apply the read-scaling moves in order (fix queries, denormalize, add replicas, cache, precompute), check each against a read-rate estimate, and handle replication lag and hot keys.

    8 min read

  • Scaling Writes

    Raise write capacity by writing less, splitting latest state from history, batching behind a durable log, sharding by the write key and splitting hot counters, and size bursts and backpressure with real arithmetic.

    8 min read