Skip to content

Pattern: Dealing with Contention

Advanced 67 min read Part 11 of 18

Stop many users claiming the same seat, item or bid: atomic writes, locks, optimistic checks, TTL holds, single-writer queues and waiting rooms.

Summary#

Contention happens when many requests try to change the same piece of state at the same moment. Examples are the last seat at a concert, the current high bid in an auction, or the final 40 units of a sale item. If each request reads the state, decides, and then writes, two requests can both read "one left" and both sell it. This is a race condition, and it causes double bookings, oversold stock and lost updates.

The pattern is a ladder of tools, from cheapest to most involved:

  • Atomic conditional writes. One statement checks and changes a single row, such as "decrement if above zero".
  • Database constraints. A unique index or check constraint refuses the bad state outright.
  • Pessimistic locks. A transaction locks rows before it reads them.
  • Optimistic concurrency. A write succeeds only if a version number has not changed since the read.
  • Reservations with a TTL. A user holds an item for a few minutes while they pay. The hold expires on its own.
  • Distributed locks. These coordinate work across services or stores.
  • Single-writer serialisation. All writes for one key go through one queue partition or actor.
  • Virtual waiting rooms. These control how many people reach the contended system at all.

The core skill is to name the invariant you must protect, such as "never sell more seats than exist". Then put the check where it is enforced atomically, ideally in one database row or one transaction. Pick the lightest tool that holds the invariant under the peak load you expect.

Why It Exists#

Most data in most systems is touched by one user at a time. Your profile, your draft email and your shopping cart rarely see two writers at once. Contention appears when demand for a scarce, shared thing spikes, and it is exactly where errors are most expensive:

  • Ticketing. A stadium has 50,000 seats and a million fans arrive at 10:00. The best seats see thousands of attempts per second.
  • Auctions. In the last ten seconds of an auction, dozens of bids race to update one "current high bid" value.
  • Flash sales and inventory. A sneaker drop or a console restock puts many orders onto one stock-keeping unit, or SKU, which is one row per product variant.
  • Ride-hailing and delivery. Several dispatchers may try to assign the same nearby driver to different riders.
  • Unique names. Two people sign up for the username "sam" in the same second.
  • Money. Two withdrawals can race against one account balance.
  • Calendars. Two people can book the same meeting room for overlapping times.

The naive flow is read, then check, then write. It works perfectly for one user and fails under concurrency, because time passes between the read and the write. Here is the race on the last seat, step by step:

Both apps behaved correctly by their own lights. The bug is in the gap between the read and the write. Here it is a lost update: Ben's write overwrote Asha's without knowing it existed. With available = available - 1, the count would go to minus one instead. Either way, two people now hold tickets for one seat, the venue must refund one, and a support queue fills with angry fans.

These bugs hide in testing. On a developer laptop, requests arrive one at a time and the gap is microseconds wide. In production at a sale's start, hundreds of requests land inside the same millisecond, so the rare case becomes the normal case. If one sale in 10,000 hits the race and you sell 2 million tickets, you oversell 200 seats.

There are two separate problems. It is worth keeping them apart from the start:

  1. Correctness. The invariant must hold, so nothing is oversold, no bid is lost and no driver is double-assigned. This is not negotiable.
  2. Throughput under contention. Once correctness is guaranteed, often with a lock, every request for the hot item queues behind one lock. One row can then only process a few hundred changes per second, and latency explodes. This is a performance problem, and it needs different tools: splitting the hot item, serialising in memory, batching, or limiting arrivals.

Many designs solve the first problem and then fall over on the second. A senior answer handles both.

How It Works#

Every contention design answers the same questions in order:

  1. What is the scarce thing? It may be a seat, a unit of stock, a driver, a name or a balance.
  2. What is the invariant? For example, at most one confirmed booking per seat, or stock never below zero.
  3. Where does the truth live? It may be one row, several rows in one database, rows on different shards, or a different system entirely.
  4. How long must a claim be held? It might be milliseconds, inside one statement, or minutes, while a person types a card number.
  5. How hot is the hottest key at peak? It might be ten attempts per second, or ten thousand.

The answers decide which layer of the ladder you need. Large systems stack several layers, each protecting the next:

The waiting room limits how many people compete at all. The hold gives a person time to pay without holding database locks. The confirm transaction is short and checks that the hold is still valid. The constraint guarantees the invariant even if every layer above has a bug. The rest of this section covers each tool, then how to choose.

Step zero: measure how hot the contention is#

Before picking a tool, estimate the contention rate on the hottest key. Contention is about the rate per key, not total traffic. A ticketing site doing 10,000 bookings per second, spread over 5,000 shows, sees 2 bookings per second per show. That is easy. One superstar show taking 10,000 attempts per second on its best 500 seats is a different problem, even at the same total load.

Two numbers matter:

  • λ (lambda), the arrival rate of conflicting writes on one key, in attempts per second.
  • t, the critical-section time. This is how long one writer must exclusively own the key. For a single-statement update it is the time a row lock is held. For a transaction it runs from the first lock to commit, including any network round trips made in between.

Their product, ρ = λ × t (rho), is the key's utilisation: the fraction of time the key is busy.

  • ρ well below 0.1. Conflicts are rare. Optimistic concurrency wins, because it almost never retries and never blocks.
  • ρ between 0.1 and about 0.7. Conflicts are common. Locks or atomic conditional updates keep wasted work low, and queues stay short.
  • ρ near or above 1. The key cannot keep up, whatever the locking scheme. Requests pile up without limit. You must shorten t, by serialising in memory or batching, split the key, or cut λ with admission control.

Contention maths, in depth#

The ceiling on one row. If a row lock is held for t seconds per write, that row can absorb at most 1/t writes per second, however many database cores you have. Here are typical values:

  • Single conditional UPDATE, with the lock held only inside the storage engine: roughly 0.1 to 0.5 ms on a local SSD-backed primary. If each commit must wait for a durable log flush, group commit helps, but a hot row still serialises. Expect a few thousand updates per second on one row, at best.
  • Interactive transaction. The app runs BEGIN, SELECT ... FOR UPDATE, app logic, UPDATE, then COMMIT. That is three or four network round trips at about 0.5 ms each inside a data centre, plus app time. The lock is held for perhaps 2 to 5 ms, giving a ceiling of 200 to 500 writes per second on that row.
  • Transaction that calls an external API while holding the lock. A payment call can take 300 ms to 2 s, giving a ceiling of 0.5 to 3 writes per second. This is why you never hold a database lock across a payment call.

Queueing makes it worse before you reach the ceiling. Waiting time on a lock behaves like a single-server queue. For an M/M/1 model, with random arrivals and random service time, the mean time in the system is t / (1 − ρ). At ρ = 0.5 a write takes about twice its bare cost. At ρ = 0.9 it takes ten times. At ρ = 0.99 it takes a hundred times. Real lock queues also suffer convoys: once a queue forms, each waiter's own work is delayed, which holds other locks longer, so delay spreads to unrelated rows.

Worked example. A flash sale expects 3,000 checkout attempts per second for one SKU at the opening second. The checkout transaction locks the stock row for 4 ms, so ρ = 3,000 × 0.004 = 12. The row can serve 250 per second. After one second, 2,750 requests are waiting. Connection pools fill, timeouts fire, clients retry, and the retries add load. No choice of lock type helps. The fixes change ρ:

  • Shorten t. A single conditional UPDATE without a round trip brings t to about 0.3 ms, so ρ = 0.9. That is borderline.
  • Split the row. Ten stock buckets give ρ = 1.2 per bucket with the long transaction, or 0.09 with the short update.
  • Serialise in memory. One single-threaded process decrementing a counter at 1 µs per operation has ρ = 0.003.
  • Limit arrivals. A waiting room admits 200 shoppers per second, so ρ = 0.8 with the long transaction.

Every layer in the rest of this page is one of these four levers. Each shortens t, spreads λ across keys, removes the lock, or caps λ.

Atomic single-row updates and constraints#

The cheapest fix moves the check and the write into one statement that the database runs atomically. Instead of reading the count and deciding in the app, you tell the database to change the row only if the condition still holds:

-- General admission: decrement only if a ticket is left
UPDATE shows
SET available = available - 1
WHERE show_id = 'arena-0612' AND available > 0;
-- rows affected: 1 means you got a ticket, 0 means sold out
 
-- Assigned seating: claim one specific seat
UPDATE seats
SET status = 'sold', booking_id = 'b-7731'
WHERE seat_id = 'arena-0612-R5-S12' AND status = 'available';

The app checks the affected row count. One means success. Zero means someone else won, so the app returns "sold out" or "seat taken". There is no gap, because the storage engine locks the row, evaluates the condition and applies the change as one step.

This is often called a conditional write, and every serious store has a form of it:

  • PostgreSQL and MySQL: UPDATE ... WHERE <condition>, plus RETURNING in PostgreSQL to read the new value in the same statement.
  • DynamoDB: a ConditionExpression on PutItem or UpdateItem, such as available > :zero or attribute_not_exists(pk). A failed condition returns ConditionalCheckFailedException.
  • Redis: single commands are atomic, because Redis runs commands one at a time on one thread. DECR returns the new value, SET key value NX sets only if absent, and a Lua script can run "check then change" atomically.
  • MongoDB: findOneAndUpdate with a filter that includes the condition.
  • Cassandra: lightweight transactions, written as INSERT ... IF NOT EXISTS or UPDATE ... IF col = value. These run a Paxos round among the replicas, so they cost several round trips. Use them sparingly, not on every write.
  • etcd and ZooKeeper: compare-and-swap on a key's revision or version.

Constraints are the safety net. A database constraint refuses an illegal state, whatever the app code does:

  • Unique index. Put UNIQUE (show_id, seat_id) on a bookings table. The insert is the claim: the second insert for the same seat fails with a unique-violation error. The same works for usernames, with UNIQUE (lower(username)), and for one-vote-per-user, with UNIQUE (poll_id, user_id).
  • Check constraint. CHECK (available >= 0) makes an overselling decrement fail instead of going negative.
  • Exclusion constraint (PostgreSQL). This prevents overlapping time ranges, which is what room and rental bookings need: EXCLUDE USING gist (room_id WITH =, during WITH &&), with the btree_gist extension enabled for the equality part. Two bookings for the same room whose periods overlap cannot both commit, even if both apps checked for free time first.
  • Foreign keys and NOT NULL. These stop partial claims, such as a booking pointing to a seat that does not exist.

Even when you use locks or reservations elsewhere, keep the constraint. It turns a silent oversell into a loud error that you can catch, log and compensate.

Atomic updates, in depth#

Why the conditional UPDATE is safe at default isolation. You might worry that two concurrent UPDATEs both see available = 1 in their snapshot. Databases handle this specially for writes:

  • PostgreSQL. In READ COMMITTED, the default, an UPDATE that finds its target row locked by another transaction waits. When the other commits, PostgreSQL re-reads the latest committed version of that row and re-checks the WHERE clause against it before applying the change. The internal mechanism is called EvalPlanQual. So the second decrement sees available = 0, fails the condition, and affects zero rows.
  • MySQL InnoDB. UPDATE and DELETE always do a current read, also called a locking read, of the latest committed row, not the transaction's snapshot. The effect is the same.

The danger is only the read-then-write in the app. A plain SELECT reads a snapshot without locking, and a later UPDATE writes a value computed from that stale read, such as SET available = 0 after reading 1.

Increment-style updates over set-style updates. SET available = available - 1 is safer than SET available = :newValue, because the database computes from the current value. Set-style writes need either the condition (AND available = :oldValue, which is optimistic concurrency) or a lock.

The limits of one statement. A conditional write covers the rows that one statement touches, so it cannot cover:

  • Several unrelated rows, such as a cart with five SKUs, each of which must be in stock. You need a transaction around all the updates, with each update still conditional.
  • External side effects. You cannot charge a card "inside" an UPDATE. Payment needs a reservation, followed by a confirm.
  • Invariants that span many rows. "No more than 8 tickets per customer per show" needs a count over a set. Use a transaction at SERIALIZABLE, a per-customer counter row updated conditionally, or a lock on the customer row.

Counter row or one row per unit? This is a key modelling choice:

  • Assigned seating naturally gives one row per seat. Contention spreads across seats, and only the most popular seats are hot.
  • General admission or fungible stock, meaning identical units, tempts you into a single counter row. That row becomes the hottest key in the system.

The alternative is one row per unit, or a pool of unit rows, claimed with SELECT ... FOR UPDATE SKIP LOCKED. Each buyer grabs some free row and skips rows that others have locked, so buyers no longer queue behind one row. Shopify described exactly this move in a 2026 engineering post, covered in Real-World Examples below.

-- Claim any one free unit of an item without waiting on other buyers
UPDATE stock_units
SET status = 'held', holder = :cart_id, hold_expires = now() + interval '10 minutes'
WHERE unit_id = (
  SELECT unit_id FROM stock_units
  WHERE item_id = :item AND status = 'free'
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
RETURNING unit_id;

Without SKIP LOCKED, concurrent buyers would pick the same "first free row" and block on each other. With it, they spread out across the pool.

Uniqueness without a lock: insert as the claim. For "first one wins" claims, inserting into a table with a unique key is often the simplest correct answer. Examples are usernames, seats, coupon codes and idempotency keys:

  • INSERT INTO seat_claims (show_id, seat_id, booking_id) VALUES (...) succeeds for exactly one booking. It works the same on PostgreSQL, MySQL, DynamoDB (with attribute_not_exists) and Cassandra (with IF NOT EXISTS).
  • PostgreSQL's INSERT ... ON CONFLICT DO NOTHING RETURNING tells you whether you won without raising an error.

Pessimistic locking#

Pessimistic locking assumes conflict is likely, so a transaction locks the rows it will change before reading them. Other writers wait until it commits or rolls back. In SQL this is SELECT ... FOR UPDATE:

BEGIN;
SELECT available FROM shows WHERE show_id = 'arena-0612' FOR UPDATE;  -- row now locked
-- app checks available > 0 and computes the booking
UPDATE shows SET available = available - 1 WHERE show_id = 'arena-0612';
INSERT INTO bookings (show_id, user_id, qty) VALUES ('arena-0612', 'u42', 1);
COMMIT;  -- lock released

Anyone else running SELECT ... FOR UPDATE on that row blocks until the first transaction finishes. Then they see the new value. Variants control what happens when a row is already locked:

  • FOR UPDATE NOWAIT fails immediately instead of waiting. This suits user-facing flows that would rather say "try again" than hang.
  • FOR UPDATE SKIP LOCKED ignores locked rows and returns the next free ones. It is ideal for claiming any unit from a pool, or any job from a queue table.
  • FOR SHARE takes a shared lock. Others can read-lock the row but cannot change it. This is useful when you depend on a row staying unchanged, such as a parent row while you insert children.
  • Lock timeouts cap the wait: lock_timeout in PostgreSQL, and innodb_lock_wait_timeout in MySQL, whose default is 50 seconds and which is usually far too long for web requests.
  • Advisory locks in PostgreSQL, such as pg_advisory_xact_lock(hashtext('show:arena-0612')), lock an application-defined number rather than a row. They suit "only one worker may rebuild this report" without inventing a dummy row.

When pessimistic locking fits:

  • Contention is high, so optimistic retries would waste a lot of work.
  • The transaction is short and stays inside the database, taking milliseconds, not seconds.
  • A retry would be expensive, for example because the transaction does heavy computation.
  • You need several rows to stay consistent together, such as moving money between two accounts.

Common failure modes of pessimistic locks#

Locks are simple to add and easy to misuse. The classic failures are these:

  • Holding a lock across slow work. A transaction that locks the seat, then calls the payment provider, then commits will hold the lock for one to several seconds. That caps the row at around one sale per second, and it ties up a database connection the whole time. Never hold a database lock across a network call to another service, and never across user think time. Keeping a transaction open for the 5 to 10 minutes a buyer spends at checkout is the classic bad answer. That calls for a reservation, covered below.
  • Deadlocks. Transaction 1 locks seat A and wants seat B. Transaction 2 locks seat B and wants seat A. Neither can proceed. The database detects the cycle and kills one, but users see errors, and code paths that do this often turn into deadlock storms under load.
  • Connection pool exhaustion. Each waiting transaction holds a database connection. If 500 requests wait on one row and the pool has 100 connections, the whole service stalls, including requests that have nothing to do with the hot row.
  • Abandoned transactions. A client crashes or hangs after BEGIN and never commits, leaving the lock held. Guard with statement and idle timeouts. PostgreSQL's idle_in_transaction_session_timeout ends sessions that sit idle inside a transaction.
  • Surprise lock scope. Locks can cover more than you expect:
    • MySQL's default REPEATABLE READ takes gap locks and next-key locks, which lock ranges of an index, not just matching rows. A locking query on an empty range can block inserts into that range.
    • SQL Server can escalate many row locks into a table lock.
    • A query without a usable index may lock far more rows than it returns.
  • Long transactions hurt everyone. In PostgreSQL, an old open transaction stops vacuum from removing dead row versions, so tables bloat. In MySQL, it grows the undo log.

Pessimistic locking, in depth#

Preventing deadlocks. A deadlock needs a cycle in the "who waits for whom" graph. You can avoid cycles by design:

  1. Lock in a global order. If every transaction locks seats in ascending seat ID, no cycle can form. One transaction may wait for another, but never in a circle. For a multi-seat booking, sort the IDs and run one SELECT ... WHERE seat_id IN (...) ORDER BY seat_id FOR UPDATE.
  2. Lock everything up front. Take all needed locks at the start of the transaction, in one statement where possible. Don't add locks halfway through.
  3. Keep transactions short. The shorter the lock, the smaller the window for a cycle.
  4. Use NOWAIT or a short lock timeout on user-facing paths. A failed attempt that retries after a jittered pause is better than a pile-up.
  5. Same order across code paths. Two different features that touch the same tables must lock them in the same sequence. Shopify found this exact bug: different paths touched its reservation tables in different orders.

How databases detect deadlocks. The database keeps a wait-for graph. Nodes are transactions, and an edge from T1 to T2 means T1 waits for a lock that T2 holds. A cycle means deadlock.

  • PostgreSQL waits deadlock_timeout, 1 second by default, before running the check. This makes the check rare and cheap when locks are quickly released. Then it aborts one transaction with a deadlock error.
  • InnoDB checks on each lock wait by default. Under extreme concurrency the check itself becomes expensive, so some high-throughput setups disable innodb_deadlock_detect and rely on the lock wait timeout instead.

The aborted transaction must be retried by the app, so wrap transactions in a retry helper that recognises deadlock and serialisation errors.

Lock granularity. Lock the smallest thing that protects the invariant: one seat, not the whole show, and one SKU, not the whole warehouse. Coarser locks are simpler but serialise unrelated work. Finer locks increase lock-manager overhead and deadlock risk. The Concurrency Control and Locking page covers lock modes, intention locks and escalation. See Concurrency Control and Locking.

Lock convoys and fairness. When a hot lock is released, which waiter gets it next? Most database lock managers grant in roughly FIFO order to prevent starvation. At high rates, though, a lock convoy forms. Every waiter wakes, runs, and goes back into line, and throughput drops below the single-thread ceiling because of context switching and wake-ups. This is one reason that serialising hot keys in a single in-memory worker can beat locking by one or two orders of magnitude.

Optimistic concurrency control#

Optimistic concurrency control (OCC) assumes conflicts are rare. You read without locking, do your work, and at write time check that nobody changed the data since you read it. If someone did, your write fails and you retry with fresh data. The usual check is a version number:

-- 1. Read, remembering the version
SELECT high_bid, high_bidder, version FROM auctions WHERE id = 'lot-88';
-- returns high_bid = 120, version = 41
 
-- 2. Write only if the version is unchanged; bump it in the same statement
UPDATE auctions
SET high_bid = 130, high_bidder = 'u42', version = version + 1
WHERE id = 'lot-88' AND version = 41 AND 130 > high_bid;
-- 1 row: bid accepted. 0 rows: someone else changed the lot, so re-read and retry or reject.

No lock is held while the user or the app thinks. The only lock is the brief row lock inside the UPDATE. OCC is everywhere, sometimes under other names:

  • HTTP: ETag plus If-Match. The server returns 412 Precondition Failed if the resource changed. This prevents two admins from overwriting each other's edits in a CMS.
  • Kubernetes: every object carries a resourceVersion. Updates with a stale version get 409 Conflict, and controllers re-read and retry. The entire control plane runs on this.
  • DynamoDB: a version attribute plus a condition expression. Some SDK mappers do this automatically with a version annotation.
  • Elasticsearch: if_seq_no and if_primary_term on index requests.
  • etcd: a transaction that compares mod_revision, then puts.
  • Wikis: MediaWiki shows an edit conflict screen when you save over a page that someone changed after you opened it.

When OCC fits:

  • Contention is low: most writes don't collide.
  • Reads far outnumber writes, and you don't want readers to block.
  • The "think time" between read and write is long, as when a user edits a form, and holding a lock that long is impossible.
  • The data store has no locks, which is true of many NoSQL stores, but does have conditional writes.

When OCC hurts. Under heavy contention, most attempts fail and retry. The work is wasted, latency grows, and clients that keep losing can starve. In the last seconds of a hot auction, OCC on the lot row produces a retry storm. A single-writer queue, covered below, is a better fit there.

Optimistic concurrency, in depth#

The cost of retries under contention. Suppose k clients all read version 41 at once and all try to write. Exactly one wins. The other k − 1 re-read and try again, and one of them wins, and so on. If they keep colliding, the total number of attempts to get all k through is k + (k − 1) + ... + 1 = k(k + 1) / 2. That is quadratic in k. With 100 simultaneous bidders, that is 5,050 attempts to commit 100 bids, against 100 lock acquisitions under pessimistic locking. In practice clients arrive spread out rather than all at once, so it is less bad. The shape is still right: OCC's cost explodes as contention grows, while lock-based cost grows linearly, though with queueing delay.

Retry discipline. Always retry with these rules:

  • Bounded retries, such as 3 to 5 attempts, then return a clear "conflict, please retry" to the caller.
  • Jittered backoff, so losers don't collide again in lockstep.
  • Re-read and re-validate the business rule, not just the version. A bid of 130 that was valid against 120 may be invalid against a new high of 135.
  • Idempotent side effects. If the retry path re-sends an email or re-charges a card, a retry storm becomes a billing incident. See Idempotency.

The ABA problem. A check that compares values rather than versions can be fooled. The value goes from A to B and back to A, and a stale writer sees "still A" and proceeds as if nothing happened, even though the world changed in between. Here are three examples:

  • A seat shows available. Your app reads it. Then Ben holds it, his hold expires, and it shows available again. A check on status = 'available' passes. That is harmless here, because the seat really is free. But suppose your write also carries a price you read earlier, and the price changed during Ben's hold. Then you sell at a stale price.
  • A document is in status draft. An editor starts changes. Meanwhile someone publishes it, edits it and reverts it to draft. The editor's save, which checks status = 'draft', silently overwrites the newer content.
  • An inventory count reads 5. One unit sells and one is returned, so it is 5 again. A compare on count = 5 passes, but the specific unit your logic assumed is gone.

The fix is to compare something that never repeats. Options are a version counter that only increases, a last-modified log sequence number, or a timestamp from a single clock source. The name ABA comes from lock-free programming. There, a compare-and-swap on a pointer can succeed after the pointer was freed and reused, and the classic fix is a tagged pointer that pairs the pointer with a counter. The database version column is the same idea.

Version columns versus comparing all fields. Some ORMs implement OCC by putting every original column value in the WHERE clause. That works, but it is exposed to ABA on each column, and it makes statements long. A single integer version column is clearer and cheaper.

OCC inside the database. OCC is also an internal technique for whole transactions. A transaction runs against a snapshot without locks, and at commit the database validates that nothing it read was changed by a transaction that committed in between. If validation fails, it aborts. The idea goes back to H. T. Kung and John T. Robinson, "On Optimistic Methods for Concurrency Control" (ACM Transactions on Database Systems, 1981). Many in-memory and distributed databases use variants of it.

Isolation levels as a contention tool#

The isolation level decides which anomalies a transaction can see. It is part of the contention toolbox, because a stronger level makes the database catch races for you. The full treatment is in ACID and Isolation Levels. For contention, the key facts are these:

  • READ COMMITTED, the default in PostgreSQL, Oracle and SQL Server, does not prevent lost updates from app-level read-then-write. You need conditional writes, FOR UPDATE, or a version column.
  • REPEATABLE READ behaves differently by product:
    • In PostgreSQL it is snapshot isolation. If two transactions update the same row, the second fails with a serialisation error ("could not serialize access due to concurrent update"), so lost updates are detected.
    • In MySQL InnoDB, the default level, plain SELECTs read a snapshot but UPDATEs read the latest row. A lost update is therefore still possible if you compute in the app from a snapshot read.
  • SERIALIZABLE guarantees the result is as if transactions ran one at a time. PostgreSQL implements it with Serializable Snapshot Isolation (SSI). SSI tracks read-write dependencies between concurrent transactions and aborts one when a dangerous cycle appears. The algorithm comes from Michael Cahill, Uwe Röhm and Alan Fekete, "Serializable Isolation for Snapshot Databases" (SIGMOD 2008). Dan Ports and Kevin Grittner described the PostgreSQL implementation in VLDB 2012.

Write skew is the anomaly that only SERIALIZABLE, or explicit locks, prevents. Two transactions each read an overlapping set of rows, each check a condition, and each write a different row, so no row-level conflict is detected:

  • Room booking. Two people each check that room 4 is free from 14:00 to 15:00 and each insert their own booking row. Both commit, giving overlapping bookings. Nothing was updated twice, so neither conditional updates nor version checks catch it.
  • Per-customer ticket limit. A customer with two browser tabs runs two transactions. Each counts the customer's existing tickets as 6 against a limit of 8, and each inserts 2 more, so the customer ends up with 10.

There are four fixes. Use SERIALIZABLE and retry on serialisation failure, error code 40001. Lock a common parent row, such as the room or customer, with FOR UPDATE. Use an exclusion or unique constraint. Or materialise the conflict, by creating a row that both transactions must update, such as a per-customer counter.

SERIALIZABLE in practice. Many teams are scared of SERIALIZABLE, but for short transactions on modest contention it works well. A whole multi-item order can be one transaction:

  1. Check stock for items A, B and C.
  2. Decrement all three.
  3. Insert the order and its lines.
  4. Commit, or retry on error 40001.

This is often the simplest correct design for a local-delivery or grocery service, where an order touches several SKUs in one regional warehouse. The cost is aborts under contention, so keep transactions small and the retry loop bounded.

Reservations with a TTL#

Atomic writes and short locks work when the claim and the commit happen within milliseconds. Many real flows have a long gap in the middle. A ticket buyer picks a seat, then spends several minutes entering card details. A shopper starts checkout, and the payment provider takes seconds to authorise. If you only check availability at the final step, buyers do all that work and then learn the seat went to someone faster. If you hold a database lock for the whole time, you hit the failure modes above.

A reservation, also called a hold, splits the flow into two short atomic steps with a time-limited claim in between:

  1. Hold. A short atomic write marks the item as held by this buyer until a deadline, typically now plus 5 to 15 minutes. Other buyers see it as unavailable.
  2. Pay. The buyer completes checkout. No database lock is held during this time.
  3. Confirm. A second short atomic write turns the hold into a sale, but only if the hold is still this buyer's and has not expired.
  4. Release or expire. If the buyer abandons the purchase, or payment fails, the hold is released explicitly or simply expires, and the item is available again.

This is the countdown timer you see on ticketing, airline and hotel sites. There are four common ways to implement the expiry.

Option 1: a status column, an expiry column and a sweeper job. The table has status with values available, held and sold, plus hold_expires_at. A cron job runs every minute, and sets status = 'available' wherever status = 'held' AND hold_expires_at < now(). It works, but:

  • Expired holds stay unavailable until the next sweep. For a popular show that is up to a minute of seats nobody can buy.
  • If the sweeper fails or falls behind, seats leak. Under a bad failure, the whole show looks sold out while seats sit unsold.

Option 2: implicit expiry in the claim condition. The best database-only design treats expiry as part of the definition of available. A seat is free if it is available, or if it is held and the hold has expired. The claim statement checks both:

UPDATE seats
SET status = 'held', holder = :booking, hold_expires_at = now() + interval '10 minutes'
WHERE seat_id = :seat
  AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()));

Now correctness does not depend on the sweeper at all. An expired hold is claimable the instant its deadline passes. A sweeper can still tidy rows for reporting and keep the table honest for other readers, but if it runs late, nothing breaks. The costs are:

  • Every read of availability must include the expiry test, such as status = 'available' OR hold_expires_at < now(). A compound index on (show_id, status, hold_expires_at) keeps this fast.
  • Other consumers of the table, such as analytics, must understand that "held" might mean "expired".

Option 3: a TTL lock in Redis. A hold is a key with a time to live:

SET hold:arena-0612:R5-S12 booking-b7731 NX EX 600

NX means "only if absent", so exactly one buyer gets it. EX 600 makes Redis delete the key after 600 seconds, so expiry is automatic and immediate. The database table then needs only two states, available and sold. At confirm, the app checks that the Redis key still holds its booking ID, then runs the database transaction. This approach has three subtleties:

  • The seat map needs to know about holds. It is tempting to keep a Redis set of held seat IDs per show, but set members don't expire when the lock keys do, so abandoned holds become ghosts. Use a sorted set scored by expiry time instead, such as ZADD show:arena-0612:held <expiresAt> R5-S12. The seat map counts only members whose score is in the future, and stale members are trimmed with ZREMRANGEBYSCORE whenever the set is touched. Alternatively, write a "held" status through to the database and treat Redis as the source of truth for expiry.
  • The database still enforces the invariant. Redis is the reservation layer, not the last line of defence. If Redis fails over and loses a recent key, two buyers might both believe they hold the seat. The confirm transaction must then use a conditional write or unique constraint, so that only one sale commits and the other buyer is refunded automatically.
  • Two systems cannot commit together. Clearing the Redis hold and marking the database row sold are separate writes. A crash between them leaves them disagreeing. With a TTL, the disagreement heals itself when the key expires, but counters in Redis do not heal so easily. Shopify's experience, below, is the cautionary tale.

Option 4: a holds table with a unique constraint. Insert a row into holds (show_id, seat_id, booking_id, expires_at). For the seat-level claim, the key is unique on (show_id, seat_id), and an expired hold is deleted or overwritten by the next claim in the same transaction. This keeps everything in one database, so the hold and the sale commit atomically with the rest of the order.

Reservations, in depth#

The payment-at-expiry race. The nastiest corner case looks like this:

  1. Asha holds a seat until 10:10:00.
  2. Her card authorisation is slow, and her confirm arrives at 10:10:04.
  3. At 10:10:01, Ben claimed the expired hold.

Now both have a reason to believe the seat is theirs. Three defences combine:

  1. Confirm is conditional on the hold still being mine. The confirm statement is UPDATE seats SET status = 'sold' WHERE seat_id = :seat AND holder = :asha_booking AND status = 'held'. If Ben's claim replaced the holder, Asha's confirm affects zero rows. Her payment is then voided or refunded automatically, and she sees a clear message.
  2. Extend the hold when payment starts. When the buyer submits payment, extend the hold by a few minutes with the same conditional pattern, so slow authorisations rarely cross the deadline.
  3. Authorise first, capture later. Most card networks separate authorisation (reserving funds on the card) from capture (taking them). Authorise during checkout, then capture only after the confirm statement succeeds. If confirm fails, void the authorisation instead of refunding a captured charge, which is cheaper and invisible to the buyer.

Use one clock. Expiry compares a deadline with "now". If app servers write hold_expires_at from their own clocks and the database compares with its clock, clock skew of even a second matters at the deadline. Generate and compare times in one place: either now() inside the database, for both writing and checking, or Redis's own TTL. A hold ID, or generation number, that changes on every new claim acts as a fencing token. Confirm checks the hold ID, not the time, so a late confirm with an old hold ID can never succeed. See Distributed Locking for fencing.

Choosing the hold duration. The duration is a business trade-off:

  • Too short, such as 2 minutes, and genuine buyers lose seats while typing a card number or completing a bank's 3-D Secure check. Conversion drops.
  • Too long, such as 30 minutes, and abandoned holds lock up inventory during the busiest window. Bots can hoard: a script that holds seats without paying can make a show look sold out, then release the seats to resellers.
  • Typical values are 5 to 15 minutes for tickets and retail checkout, and longer for hotel or airline holds where the buyer might need to confirm travel plans.

Pair the duration with hold limits: one active hold per account per event, a cap on items per hold, and rate limits on hold attempts per account, device and IP. These limits matter as much as the TTL for keeping inventory available to real buyers.

Accounting for holds in fungible stock. For a counter-style item, there are three quantities:

  • on_hand, the physical stock the merchant has.
  • reserved, the sum of active holds.
  • sold, confirmed but not yet shipped or deducted, depending on the model.

Availability is on_hand − sold − reserved. The invariant is that reserved + sold never exceeds on_hand. If holds live in a separate store from on_hand, a crash between "deduct on_hand" and "release hold" breaks the arithmetic, which is exactly what Shopify hit. Keep the hold and the ledger in the same transactional store when they must change together.

Why Redis expiry alone cannot run side effects. A TTL simply deletes a key. If your design keeps one counter per item, such as reserved:hoodie = 37, an individual hold's expiry must decrement that counter. Redis deleting a per-hold key does not do that. Keyspace notifications can publish an "expired" event, but they are fire-and-forget pub/sub. If the listening worker is down, the event is lost and the counter is wrong for ever. A sturdier Redis design keeps holds in a sorted set scored by deadline. Each reserve call first reclaims a bounded number of overdue holds in the same Lua script, then takes the new hold, and a background sweeper handles items that stop getting traffic. The bound matters, because a Lua script blocks every other Redis command while it runs.

Overbooking on purpose. Airlines and hotels deliberately sell more than capacity, because some customers don't show up, and they manage the risk with compensation policies. That is a business decision, not a race condition. If you overbook, do it with an explicit, configured allowance, such as capacity × 1.05, enforced by the same atomic check. Never do it by accident.

Distributed locks#

A distributed lock gives one process exclusive rights to a resource across many machines, using a shared coordination service. Reach for one when the contended thing is not a row in one database you can lock or update conditionally:

  • Coordinating work that spans services or stores. Examples: "only one dispatcher may offer this driver a ride at a time", or "only one worker may run this nightly report".
  • Guarding an external resource with no concurrency control of its own, such as a third-party API account that allows only one session.
  • A fast front filter in front of the database. It turns away doomed attempts quickly, so the database sees fewer conflicts. The database still enforces the invariant.

The common implementations are covered in depth in Distributed Locking. In brief:

  • Redis SET key token NX PX ttl. Fast, at sub-millisecond speed, and simple. Release with a Lua script that deletes the key only if it still holds your token, so you never release someone else's lock. It is not safe on its own for strict correctness, because of failover and TTL expiry. The multi-node Redlock algorithm is debated for the same reason.
  • ZooKeeper ephemeral sequential nodes, and etcd leases with revisions. These are built on consensus, so they survive node failures. They are slower, at a few milliseconds, and better for coarse locks such as leader election than for per-request locks.
  • Database advisory locks, or a lock table. These are fine when everything already uses one database.

The golden rule: a lock with a TTL can expire while the holder still thinks it owns the lock. A garbage-collection pause, a slow disk or a network partition can stall a process past its TTL. Another process takes the lock, and now two processes act. Unless the protected resource checks a fencing token (a number that increases with each grant and is rejected if it is older than the last one seen), a distributed lock is an efficiency tool, not a correctness tool. In practice, this means three things:

  • Use the distributed lock to avoid duplicate work.
  • Rely on a conditional write, version check or unique constraint in the database to prevent duplicate effects.
  • If the lock service is down, the system should degrade, with more conflicts and errors, but never double-sell.

Distributed locks, in depth#

Locking several resources. To hold several seats at once, take locks in sorted key order and release everything if any acquisition fails. This gives all-or-nothing behaviour without deadlock. In Redis Cluster, a Lua script that sets several keys atomically works only if all keys are in the same hash slot. Use a hash tag, such as hold:{arena-0612}:R5-S12, so that all keys for one show land together. That co-location is also a sharding decision. It puts all of one show's locks on one node, which is exactly the hot spot for a superstar show.

Lock service failure modes:

  • Redis primary failover with async replication. The new primary may not have the most recent locks, so two clients can hold "the same" lock briefly. The defence is fencing, plus database enforcement.
  • Clock jumps. Redis TTLs depend on the server's clock behaviour. Leases in etcd are tracked by the leader and refreshed by keep-alives, so they are more robust, but they still depend on timeouts.
  • Thundering herd on release. If 5,000 clients poll for a hot lock, each release triggers 5,000 retries. Prefer a queue of waiters, as ZooKeeper's sequential nodes provide, where each waiter watches only its predecessor. Better still, don't use a lock for something that hot.

When the lock is the wrong tool. If a key is so hot that thousands of clients are contending for its lock, the lock just turns contention into queueing with network round trips. At that point, serialise the work in one place, which is the next tool.

Serialising through a queue or partition#

Instead of letting many writers fight over a key, route every change for that key to one place and apply the changes one at a time. If only one thread ever writes auction lot-88, there is no race to guard against: no locks, no version checks and no retries. This is the single-writer principle.

There are three ways to build it:

  1. A partitioned log. Write bid commands to a Kafka topic partitioned by auction_id. All bids for one lot land in one partition, in order. One consumer owns that partition and applies bids sequentially, usually against in-memory state backed by a database.
  2. Actors or virtual actors. Frameworks such as Akka Cluster Sharding and Microsoft Orleans keep one actor per entity, such as one actor per auction. The framework routes all messages for that entity to it and processes them one at a time. The Orleans "virtual actor" model was described by Philip Bernstein and colleagues at Microsoft Research in a 2014 technical report.
  3. Consistent-hash routing to a stateful service. A load balancer or service mesh hashes the key, so the same lot always reaches the same server, which holds the lot in memory with a single-threaded loop per lot. See Consistent Hashing.

Why this scales better than locks for one hot key. A lock-based design pays network round trips and a lock hand-off per write, so it manages hundreds to low thousands of writes per second per key. A single thread updating in-memory state pays microseconds per write, so it can manage hundreds of thousands to millions of writes per second per key. Martin Fowler's 2011 write-up of the LMAX retail exchange architecture described a single-threaded business logic processor handling about 6 million orders per second, by keeping all state in memory and journalling inputs. Stock exchange matching engines commonly work this way: one sequenced, single-threaded engine per instrument or group of instruments.

The costs:

  • The API becomes asynchronous. The bid is "accepted for processing", not yet applied. The client learns the outcome through a reply channel. This can be a response correlated by request ID, delivered over a push connection (see Pattern: Pushing Realtime Updates), or a short synchronous wait in the API for the worker's reply.
  • One partition has a ceiling. If one key needs more than a single thread can give, you must split the key's meaning, or batch.
  • Failover needs replay. When the worker dies, a new owner must rebuild in-memory state from a snapshot plus the log since then. Commands must be processed idempotently, so that replays don't double-apply. See Delivery Semantics.
  • Head-of-line blocking. A slow command for one lot delays everything behind it in the same partition. Partition finely enough, and keep per-command work tiny.

Serialising and batching, in depth#

Batching turns contention into throughput. A single writer can apply many requests in one database write. A flash-sale worker pulls 500 queued orders for SKU 991, checks them against in-memory stock in arrival order, accepts the first 340 that fit, and commits one transaction. That transaction decrements stock by 340, inserts 340 order rows, and marks 160 as sold out. The hot row is locked once per batch instead of 500 times. This is the same idea as a database's group commit, where many transactions share one log flush.

Hot-key splitting, or sharded counters. When one counter is too hot, split it into N sub-counters, each holding a share of the stock:

  • 10,000 units become 10 buckets of 1,000.
  • A buyer picks a random bucket and decrements it conditionally. If that bucket is empty, they try another.
  • Total available is the sum of the buckets.

Google App Engine documented this as sharding counters for high write rates. It spreads λ across N keys, so ρ per key falls by N. The cost is a long tail at sell-out. When only a few buckets have stock left, buyers hit empty buckets and must probe several. You can rebalance stock between buckets, or collapse them into one when stock gets low.

Pre-generated tokens. For a fixed stock of identical units, load one token per unit into a Redis list. Each buyer pops a token with LPOP, which is atomic and O(1). An empty list means sold out. At around 100,000 simple operations per second on one Redis shard, this absorbs the opening spike. Order creation then flows asynchronously through a queue to the database, which can take its time. The database still checks the token's uniqueness with a unique constraint on token_id, so a replayed message cannot create a second order.

Escrow and commutative updates. Some updates commute: two decrements of 1 give the same result in either order. A database can let commuting updates proceed concurrently if it can prove the invariant holds whatever the order. For example, it may allow a decrement if available − (pending decrements) ≥ 1. Patrick O'Neil described this in "The Escrow Transactional Method" (ACM Transactions on Database Systems, 1986). The idea reappears in modern systems as quota allocation. Each region or shard gets a slice of the inventory that it can sell locally without coordination, and slices are rebalanced in the background.

Counters that don't need exact answers. Likes, views and "people looking at this right now" are high-contention, but the invariant is weak. Approximate or eventually consistent counts are fine. Buffer increments in memory and flush them periodically, use per-shard counters summed on read, or use a counter CRDT. That is a write-scaling problem rather than a correctness problem. See Pattern: Scaling Writes.

Keeping the read side honest: live availability#

Contention is not only a write problem. During a big on-sale, thousands of buyers stare at the same seat map. A map loaded 20 seconds ago is already stale. Buyers keep clicking seats that are gone, each click is a failed hold attempt, and each failure adds load and frustration.

  • Cache the static parts aggressively. The venue layout, prices and event details change rarely, so serve them from a CDN and an in-memory cache. The same applies to inventory in commerce. A local-delivery app might do 20,000 availability lookups per second against far fewer orders. It serves availability from a cache with a short TTL, such as 1 minute, and the order service invalidates the affected entries when it writes stock. See Pattern: Scaling Reads.
  • Push changes to open maps. Use Server-Sent Events (SSE), a one-way stream from server to browser, to send "seat R5-S12 held" and "seat R5-S12 released" as they happen. At high rates, coalesce changes into a diff every second or so, rather than one message per seat change. See Pattern: Pushing Realtime Updates.
  • Show availability as approximate under extreme load. Labels such as "Few left" or "Selling fast" in a section are cheaper and less misleading than a per-seat map that changes faster than people can click.

Live updates are a good answer for moderately popular events. For the most extreme events, the seat map empties in seconds, and live updates just show buyers seats disappearing faster than they can react. That calls for controlling arrivals.

Virtual waiting rooms#

A virtual waiting room is admission control in front of the contended system. Instead of letting a million people hit the booking flow at 10:00:00, you queue them and admit them at a rate the system, and the inventory, can absorb. Admitted users get a time-limited pass to the booking pages. Everyone else sees their position and an estimated wait.

The parts are these:

  1. Join. When the buyer requests the event, they get a queue ticket and a position. A Redis sorted set works well, scored by arrival time or a random number. ZADD adds the buyer, and ZRANK gives their position. At large scale, vendors serve the waiting page itself as a static page from the CDN, so the waiting room absorbs load without touching your origin.
  2. Wait. The client learns its position and estimated wait through SSE, WebSocket or polling every few seconds. The estimate is position ÷ admission rate. For example, position 120,000 at 2,000 admissions per minute is a wait of about 60 minutes.
  3. Admit. A scheduler moves the front N users to "admitted" at a controlled rate. It marks each in an admitted:{eventId} set with a TTL and issues each a signed pass, such as a short-lived JWT holding the user ID, event ID and expiry.
  4. Enforce. The booking service, or better the edge, rejects any booking request without a valid pass. Without enforcement, a waiting room is a polite suggestion that bots ignore.
  5. Adapt. The admission rate follows feedback from the booking system: active sessions, hold success rate, error rate and database latency. When inventory runs out, close the queue and tell everyone still waiting, rather than letting them wait for nothing.

How fast to admit? Admit by target concurrency, not just a rate. If the booking flow is healthy at 20,000 concurrent shoppers, and an average session lasts 4 minutes, admit about 20,000 ÷ 4 = 5,000 users per minute. Also consider inventory. If 50,000 seats remain and buyers take 3 on average, only about 17,000 more buyers can succeed. Admitting 500,000 is pointless, so tell the rest early.

Fairness choices:

  • First come, first served by arrival time. This rewards whoever clicked first, which mostly means those with the fastest connections and bots.
  • Randomised early arrivals. Everyone who joins before the on-sale time gets a random position at the opening moment, and later arrivals join in order behind them. This removes the incentive to hammer the page at 09:59:59. Commercial waiting rooms such as Queue-it offer this mode.
  • Pre-registration and lotteries. Fans register days ahead, and accounts are screened for bots. Selected fans get access codes, and only code holders can enter the queue. Ticketmaster's Verified Fan programme works in broadly this way.

Implementation options. Several vendors sell waiting rooms: Queue-it, Cloudflare Waiting Room, Akamai, and an AWS reference solution called Virtual Waiting Room on AWS. SeatGeek has written about building its own. A home-grown version needs a CDN-served waiting page, a queue store, an admission scheduler, pass signing at the edge, and solid bot defences such as CAPTCHAs, device fingerprinting and per-account limits.

The cost. People wait, sometimes for a long time. Clear position updates, honest estimates and an early "sold out" message keep the experience tolerable. A waiting room that says "you are 400,000th" is better than a site that returns errors for an hour.

Cross-shard contention#

Everything so far assumed the contended data lives in one database, where one row or one transaction can guard the invariant. At scale, data is sharded: split across many database nodes by a key. Contention becomes harder when an invariant spans shards. Examples:

  • A cart contains SKUs stored on different inventory shards.
  • A money transfer moves funds between two accounts on different shards.
  • A trip booking needs a flight seat and a hotel room, owned by different services.
  • Usernames must be globally unique, but users are sharded by user ID.

There are five ways to handle it, from best to most involved:

  1. Co-locate what contends. Choose the shard key so that everything that must change atomically lives together. Shard ticketing data by event_id, so every seat, hold and booking for a show sits on one shard and one local transaction covers them. Shard grocery inventory by region or warehouse, since one order is filled from one warehouse. This is by far the most effective tool. Most "cross-shard" problems disappear with a better key. See Partitioning and Sharding.
  2. Route unique claims to the shard of the unique value. For global usernames, keep a separate usernames table sharded by the username itself, and claim with a conditional insert there. The user record can live elsewhere. The claim and the user record are now two writes, so either create the user only after the claim succeeds, or treat the claim as a reservation that a background job cleans up if user creation never completes.
  3. Use a distributed transaction. Two-phase commit (2PC) across shards locks rows on each participant until the coordinator decides. Distributed SQL databases such as Google Spanner, CockroachDB and YugabyteDB do this internally, and give you serialisable multi-shard transactions. They cost cross-shard round trips while locks are held, often 10 to 100 ms across zones or regions, so hot multi-shard transactions are slow. Fine for rare cross-shard writes, painful for the hottest path. See Distributed Transactions.
  4. Reserve on each shard, then confirm or compensate. This is a saga made of holds. Place a TTL hold on each shard independently. If all succeed, confirm each. If any fails, release the ones you got. Holds expire on their own if the coordinator crashes, so nothing is stuck for ever. See Pattern: Multi-Step Processes.
  5. Remove the global invariant with quotas. Give each shard or region a slice of the inventory, such as 2,500 of 10,000 units each, which it sells without coordination. A background rebalancer moves unsold quota to where demand is. This is the escrow idea applied across machines.

Deadlock across shards. If two orders lock items on two shards in opposite orders, you get a distributed deadlock. No single database can see it, because each shard sees only half the cycle. There are three defences. Lock in a global order, such as sorted by item ID across all shards. Use timeouts, and abort on expiry. Or use a priority scheme such as wound-wait, where older transactions may abort younger ones that block them, or wait-die, where a younger transaction that would wait on an older one aborts itself. Both schemes come from Daniel Rosenkrantz, Richard Stearns and Philip Lewis, "System Level Concurrency Control for Distributed Database Systems" (ACM Transactions on Database Systems, 1978). The Spanner paper (Corbett et al., OSDI 2012) describes using wound-wait for its read-write transactions.

Multi-region contention. If buyers in Europe and the US can both buy the last unit, you must pick between two approaches:

  • A single home region per item, where all claims for an event go to its home region. This is simple and correct, at the cost of extra latency for remote buyers. Ticketing usually takes this route, since an event has a natural home.
  • Quotas per region. Each region sells its slice locally, giving low latency, and the risk is only that a region sells out early while another still has stock.

Multi-leader databases that merge conflicting writes later cannot safely protect a "never oversell" invariant, because they detect the conflict after both sales are confirmed. See Multi-Region Data.

Choosing the right approach#

Start at the top of this flow and stop at the first answer that holds your invariant at your peak load:

Here is the same advice as a table, with the problem signal that points to each tool:

Signal in the problemToolWhy
"Decrement if in stock", "claim if free" on one recordConditional UPDATE or conditional putOne atomic statement, no app-level gap
"Each seat or username at most once"Unique constraint, insert as the claimThe database refuses duplicates, whatever the code does
"No overlapping bookings"Exclusion constraint, or lock the parent rowWrite skew is otherwise invisible to row checks
Several rows change together in one databaseTransaction with FOR UPDATE in sorted order, or SERIALIZABLEAtomic across rows, deadlock-free if ordered
Low contention, long edit time (forms, documents, configs)Optimistic concurrency with a version column or ETagNo locks held during think time
Buyer needs minutes to payReservation with TTL, then a conditional confirmShort atomic steps, automatic release
Resource outside any one databaseDistributed lock plus fencing, with DB enforcementCoordinates work; the DB still prevents bad effects
One key gets thousands of writes per secondSingle writer (partition or actor), batchingRemoves locks; in-memory speed
Fungible stock with a hot counterUnit rows with SKIP LOCKED, sharded counters, Redis tokensSpreads one hot row across many
Millions arrive at once for limited stockVirtual waiting roomCaps arrivals; fairer and protects every layer
Invariant spans shardsBetter shard key first; then holds plus saga; then 2PCLocal transactions are cheap; cross-shard ones aren't

Worked example: a stadium on-sale#

Here is a concrete design for a popular stadium concert, to show how the layers fit together and where the numbers actually bite.

Inputs:

  • Supply: 50,000 assigned seats, with orders averaging 2.5 seats, so about 20,000 successful orders.
  • Demand: 1.5 million people arrive in the first 10 minutes, and most arrive within the first 30 seconds.
  • Hold: a hold lasts 8 minutes, and payment takes about 3 minutes on average.

Step 1: without admission control. If even 10% of arrivals click a seat in the first minute, that is 150,000 hold attempts per minute, or 2,500 per second, aimed mostly at the best 5,000 seats. Every seat sees dozens of attempts, so most fail. Failed buyers retry immediately, which doubles the load. Seat maps go stale in a second. The database could commit a few thousand short conditional writes per second in total, but the connection pools, API servers and payment calls in front of it would melt first. The experience is chaos even if nothing is oversold.

Step 2: add a waiting room. Target 15,000 concurrent shoppers in the booking flow. A typical session runs 5 minutes from admission to finished payment or abandonment, so admit 15,000 ÷ 5 = 3,000 per minute. About 60% of admitted users complete an order, so 3,000 admissions per minute produce about 1,800 orders per minute. The 20,000 orders sell out in about 11 minutes. That means only about 33,000 people get admitted in total. Tell the other 1.4 million as soon as remaining inventory falls below what the queue ahead of them could buy, rather than leaving them waiting.

Step 3: the write load is now tiny. About 3,000 holds per minute at 2.5 seats each, plus some failed attempts, is roughly 150 seat claims per second. Confirms run at about 30 orders per second. One PostgreSQL primary, sharded by event_id if the platform runs many events, does this easily. Each seat claim is a single conditional UPDATE with implicit expiry. Each confirm is one transaction that checks the hold ID and marks seats sold. A unique constraint on (event_id, seat_id) in tickets_sold backs it up.

Step 4: the read load is the real scale problem. 1.5 million people with open pages, each polling or holding a stream, is the largest load in the system:

  • The waiting page is static on the CDN. Position updates arrive by short polling every 10 to 20 seconds against an edge-cached counter, or over SSE from a fleet of connection servers. At 1.5 million users polling every 15 seconds, that is 100,000 requests per second. A CDN handles this easily, but an origin would struggle.
  • Seat maps for the 15,000 admitted users get an SSE diff about once a second.

Step 5: failure handling.

  • Payment provider slow: extend holds when payment begins, and pause admissions if the hold-to-confirm rate drops.
  • Redis down, if it holds the queue: stop admitting rather than letting everyone in. A burst of the whole crowd hitting the booking flow is worse than a paused queue.
  • Buyer pays after hold expiry: the confirm check on the hold ID fails, so void the authorisation and show a clear message.
  • Bots: require a logged-in account with a verified phone, apply one hold per account and a cap on seats per order, and run CAPTCHAs or device checks at queue entry.

The lesson: the hard part of a famous on-sale is not the database lock. It is admission control, fairness, bot defence and the read side. The lock or conditional write that prevents double booking is ten lines of SQL. The surrounding layers keep enough calm around those ten lines that they can do their job.

When to Use It#

Apply this pattern whenever the problem statement contains scarce shared resources and concurrent demand:

  • Booking anything finite: tickets, seats, hotel rooms, appointments, restaurant tables, rental cars or meeting rooms.
  • Inventory: e-commerce checkout, flash sales, limited drops, grocery and delivery orders from one warehouse.
  • Auctions and bidding: current high bid, auction close, reserve prices.
  • Assignment and matching: assigning a driver, courier, support agent or job worker to exactly one request.
  • Money and quotas: balances, credit limits, API quotas and coupon redemption limits.
  • Uniqueness claims: usernames, short URLs with custom aliases, domain names and idempotency keys.
  • Shared configuration: concurrent edits to the same document, config object or Kubernetes resource, where optimistic concurrency fits.

The phrases that should trigger it in an interview include "the last one", "no double booking", "exactly one winner", "never oversell", "first come first served", "millions at the same time", and "everyone wants the same thing".

When NOT to Use It#

  • No real sharing. Per-user data such as carts, drafts, settings and personal feeds rarely sees two writers at once. A simple last-write-wins update, or a version check for safety, is enough. Don't put distributed locks on a user's profile.
  • The invariant is weak. For like counts, view counts and "trending" scores, approximate is fine. Use buffered or sharded counters for throughput, and skip locks entirely.
  • The conflict can be merged. Collaborative editing, shopping-cart merges across devices, and set-like data can use CRDTs (data types whose concurrent changes always merge) or operational transforms instead of blocking. See Collaborative Editing and CRDTs.
  • Low scale. A small internal tool with a handful of users does not need a waiting room, sharded counters or Kafka-serialised writers. A unique constraint and a conditional update cover it.
  • Don't stack every tool. Adding Redis locks and SERIALIZABLE and version columns and a queue to one flow multiplies failure modes. Pick the lightest layer that holds the invariant, then add others only for a measured reason, such as a hot key or an arrival spike.

How to Implement It#

  1. Write down the invariant in one sentence, such as "a seat has at most one confirmed booking" or "stock_sold ≤ stock_total".
  2. Put the truth in one place. Keep everything that must change atomically in one database, and ideally in one row or one shard. Choose the shard key to make that true.
  3. Add the constraint first. Use a unique index, check constraint or exclusion constraint that makes the bad state impossible to store.
  4. Make the claim atomic. Use a conditional UPDATE, conditional put or insert-as-claim, and check the affected row count.
  5. Split long flows into hold and confirm. Use a TTL reservation with implicit expiry, a hold ID for fencing, and a conditional confirm. Separate payment authorisation from capture.
  6. Measure contention. Estimate the peak attempts per second on the hottest key, and the critical-section time. If ρ approaches 1, shorten the critical section, split the key, serialise in memory, or batch.
  7. Control arrivals for spikes. Add a waiting room with signed passes for known extreme events, and rate limits per account and device for everyday abuse.
  8. Make every retry safe. Use idempotency keys on claims, payments and confirms, and bounded retries with jitter on conflicts.
  9. Observe it. Track the hold success rate, conflicts per second, lock wait time, deadlocks, hold expiry rate, oversell alarms (which should always read zero), and the time to sell out.

Here is a reservation flow in SQL. It uses implicit expiry, a hold ID as a fencing token, and a constraint as a backstop:

CREATE TABLE seats (
  event_id  bigint, seat_id text,
  status    text NOT NULL DEFAULT 'available',   -- available | held | sold
  hold_id   uuid, hold_expires_at timestamptz, booking_id uuid,
  PRIMARY KEY (event_id, seat_id),
  CHECK (status IN ('available', 'held', 'sold'))
);
 
-- Hold: claim if free or if a previous hold has expired (one short statement)
UPDATE seats
SET status = 'held', hold_id = :new_hold, hold_expires_at = now() + interval '8 minutes'
WHERE event_id = :e AND seat_id = :s
  AND (status = 'available' OR (status = 'held' AND hold_expires_at < now()))
RETURNING hold_id;                                -- no row: seat taken
 
-- Extend when payment starts (only if still mine and unexpired)
UPDATE seats SET hold_expires_at = now() + interval '5 minutes'
WHERE event_id = :e AND seat_id = :s AND hold_id = :my_hold AND hold_expires_at > now();
 
-- Confirm after payment authorisation: the hold id acts as the fencing token
UPDATE seats
SET status = 'sold', booking_id = :booking, hold_id = NULL, hold_expires_at = NULL
WHERE event_id = :e AND seat_id = :s AND status = 'held' AND hold_id = :my_hold
RETURNING seat_id;                                -- no row: hold lost, void the authorisation
 
-- Optional sweeper for tidiness only; correctness never depends on it
UPDATE seats SET status = 'available', hold_id = NULL, hold_expires_at = NULL
WHERE status = 'held' AND hold_expires_at < now() - interval '1 minute';

For a multi-seat hold, run the hold UPDATE for all seats in one transaction, with seat_id = ANY(:seats), sorted, and check that the affected count equals the number requested. If it does not, roll back.

TechnologyFits when
PostgreSQL / MySQL conditional UPDATE, constraints, FOR UPDATE, SKIP LOCKEDThe contended data fits in one relational database or shard; holds and ledger must commit together
PostgreSQL SERIALIZABLE (SSI)Multi-row invariants and write skew, with short transactions and a retry loop
PostgreSQL exclusion constraintsTime-range bookings: rooms, rentals, appointments
DynamoDB conditional writes and transactionsKey-value data at large scale; per-item conditions, or TransactWriteItems for up to 100 items
Redis SET NX EX, DECR, Lua, sorted setsFast TTL holds, stock tokens, waiting-room queues; the DB still enforces the final invariant
Kafka partitioned by key, or actor frameworks (Akka, Orleans)One very hot key needs a single writer with in-memory state, as for auctions or matching engines
ZooKeeper / etcdCoarse-grained coordination and leases that must survive node failures; not per-request locks
Spanner / CockroachDB / YugabyteDBInvariants that truly span shards or regions and need serialisable distributed transactions
Queue-it, Cloudflare Waiting Room, Akamai, AWS Virtual Waiting RoomKnown spikes far above capacity, such as ticket on-sales, product drops and government sign-ups

Trade-offs#

OptionProsConsPick when
Conditional single-row writeSimplest; no app-level gap; very fastOnly covers one row; cannot include side effectsClaim or decrement on one record
Unique, check or exclusion constraintBulletproof backstop; enforced whatever the code doesErrors must be handled; limited to expressible rulesAlways, as the last line of defence
Pessimistic lock (FOR UPDATE)Predictable under high contention; no wasted workBlocking, deadlocks, pool exhaustion; terrible across slow callsShort multi-row transactions with real contention
Optimistic concurrency (version)No blocking; great for long think timeRetry storms and starvation under high contention; ABA if comparing valuesLow contention, read-heavy, user edits
SERIALIZABLE isolationCatches write skew and complex anomalies for youAborts under contention; needs retry logic; some overheadMulti-row invariants in short transactions
Reservation with TTLGood user experience; no long locks; automatic releaseHoarding, expiry races, extra states to reason aboutUser needs minutes between claim and commit
Distributed lock (Redis or etcd)Coordinates across services and storesNot safe alone; TTL expiry and failover issues; extra systemResource outside one database; dedupe work
Single writer (partition or actor)Highest per-key throughput; ordering for free; no locksAsync API; replay and failover complexity; per-key ceilingOne extremely hot key, such as an auction or order book
Sharded counters or stock tokensSpreads one hot counter across many keysSell-out tail; harder exact counts; rebalancingFungible stock under flash-sale load
Virtual waiting roomCaps load; fairer; protects every layerUsers wait; extra infrastructure; bot arms raceKnown spikes far above capacity
Distributed transaction (2PC)Real atomicity across shardsSlow; locks held across round trips; coordinator failureRare cross-shard invariants that can't be redesigned away

Common Pitfalls#

  • Read, then check, then write in the app, with no lock, condition or version. This is the original bug, and it hides until launch day.
  • Ignoring the affected-row count. A conditional UPDATE that matched zero rows is a failed claim. Code that doesn't check it sells the ticket anyway.
  • Holding database locks across payment calls or user think time. This caps a row at about one sale per second and exhausts connection pools.
  • Trusting a Redis lock as the only guard. Without fencing or database enforcement, a failover or GC pause can double-sell.
  • Counters split across two stores. Holds in Redis and stock in the database, updated in two separate writes, drift apart after any crash between the writes.
  • Unbounded OCC retries. A retry loop without a cap or jitter becomes a self-inflicted denial of service at the hottest moment.
  • Inconsistent lock order across code paths, causing deadlocks that appear only under load.
  • Forgetting write skew. Two transactions each insert a valid-looking row whose combination breaks a rule, such as overlapping bookings or a per-customer limit. Row-level checks never see it.
  • Sweeper-dependent correctness. If seats come back only when a cron job runs, a stuck cron job looks like a sell-out.
  • Using app server clocks for expiry. Clock skew moves deadlines. Use the database's or Redis's clock, and fence with a hold ID.
  • A waiting room without enforcement. If the booking API accepts requests without a valid admission pass, bots skip the queue.
  • Solving correctness, forgetting throughput. A perfectly safe single counter row that serves 250 writes per second will still fall over at 3,000.

Real-World Examples#

  • Shopify (inventory reservations). In a May 2026 engineering post, Shopify described moving checkout reservations out of Redis and into MySQL, next to the inventory ledger.
    • The old split. Reservations lived as Redis counters while stock lived in MySQL. A crash between the two writes could hide sellable stock, or allow an oversell. Changing the order of the writes only changed which failure was possible.
    • The first fix failed. A single quantity row per item in MySQL became one hot lock during flash sales.
    • The design that worked. It is a bounded pool of unit rows, capped at 1,000 per item and refilled by a replenishment process. Buyers claim rows with SELECT ... FOR UPDATE SKIP LOCKED, so they lock different rows in parallel.
    • Three lock fixes. The team put the query columns into the primary key, halving lock work. It ran these transactions at READ COMMITTED to avoid gap locks on empty pools, its first use of a non-default isolation level. And it made every code path take locks in the same order.
    • The result. Shopify reported that the system held up through Black Friday 2025, when merchant sales peaked at a record of about $5.1 million per minute.
  • Ticketmaster. Ticketmaster uses timed seat holds with a visible countdown, a queue for popular on-sales, and the Verified Fan pre-registration programme to screen buyers before high-demand sales. Its 2022 Taylor Swift Eras Tour presale, where demand far exceeded both inventory and system capacity, became a widely reported example of why admission control and bot defence matter as much as the booking database.
  • SeatGeek has published a description of its virtual waiting room architecture for high-demand ticket sales.
  • LMAX. The LMAX retail exchange processed orders in a single-threaded, in-memory business logic processor fed by a ring buffer, the Disruptor. Martin Fowler's 2011 article described it handling around 6 million orders per second. It is a landmark example of the single-writer approach.
  • Kubernetes relies on optimistic concurrency throughout. Every object has a resourceVersion, and controllers that write stale versions receive 409 Conflict and retry.
  • Amazon DynamoDB exposes conditional writes and TransactWriteItems. These are the standard tools for "claim if free" and "decrement if in stock" on DynamoDB.
  • Google App Engine documentation long recommended sharded counters for counters with high write rates. It is the classic description of splitting a hot key.
  • Wikipedia (MediaWiki) detects edit conflicts when two people save changes to the same page version. This is optimistic concurrency at human time scales.

Case studies that use this pattern#

In the Interview#

Deep Dive: Locks versus optimistic retries on one hot keyShow

How much load can one hot key take under each scheme? A simple model gives a clean answer, and it explains why OCC fails suddenly rather than gradually.

Locking. Writers queue for the lock, and each holds it for t seconds. The key is stable while ρ = λt < 1, so the maximum throughput is 1/t. Latency grows like t / (1 − ρ) as the key approaches saturation, but every attempt eventually succeeds, and no work is wasted.

Optimistic concurrency. Each attempt reads, works for T seconds, then tries to commit. Assume it fails if any other attempt commits during its window. With attempts arriving at random (a Poisson process) at total rate Λ, the chance that a given attempt survives its window is about e^(−ΛT). Failed attempts retry, so the total attempt rate Λ is the fresh rate λ plus the retries. In steady state, each fresh request needs on average 1/q attempts, where q is the success probability, so Λ = λ / q. Putting these together gives q = e^(−λT / q).

Write x = λT for the offered load in units of one transaction window. The equation q = e^(−x/q) is equivalent to x = −q ln q. The right-hand side peaks at q = 1/e, where it equals 1/e ≈ 0.37. So:

  • If x is below about 0.37, a steady state exists. At x = 0.2, q ≈ 0.77, so each request needs about 1.3 attempts.
  • At x = 1/e, q = 1/e, so each success costs e ≈ 2.7 attempts.
  • Above 1/e, there is no steady state. Retries feed more conflicts, which feed more retries, and the success rate collapses towards zero unless clients back off or give up.

This is the same 1/e ceiling that limits slotted ALOHA, the classic random-access radio protocol where colliding senders retransmit. That is no coincidence: OCC on one key is a collision channel. The practical conclusion is that, for one hot key, OCC sustains at most about 0.37/T successful writes per second, and it falls off a cliff above that. Locking sustains up to 1/t, and t, the time the lock is held, is usually shorter than T, the whole read-compute-write window. So locks typically carry several times more load on a hot key, and they degrade gracefully, with growing latency rather than collapse.

Worked numbers. A bid transaction takes T = 20 ms from read to commit, and the row lock inside a conditional UPDATE lasts t = 0.5 ms.

  • OCC: collapse begins near λ = 0.37 / 0.02 ≈ 18 bids per second on one lot.
  • Conditional UPDATE: the ceiling is 1 / 0.0005 = 2,000 bids per second. At 1,000 bids per second, ρ = 0.5, so a bid takes about 1 ms.
  • A single in-memory writer at 5 µs per bid has a ceiling of 200,000 bids per second.

This is why designs for hot auctions skip OCC on the lot row and use either a conditional UPDATE, whose check is the business rule new_bid > high_bid, or a single writer.

Backoff changes the picture but not the ceiling. Exponential backoff with jitter stops the collapse by thinning the retry stream, as Ethernet's binary exponential backoff does. But it cannot raise successful throughput beyond the ceiling. It only trades collapse for latency and rejected requests. If the offered load stays above the ceiling, you must change the design: shorten the window, split the key or serialise.

When OCC is the right answer. For low-contention data, OCC wins on every count. There is no lock manager traffic, readers never block, and the expected attempts per write are 1 + (a little). Most rows in most systems are like this. The hot key is the exception, so treat it with a different tool rather than changing the whole system.

Deep Dive: Proving the hold protocol never oversellsShow

It is worth reasoning carefully about why the hold-then-confirm protocol is safe, because the same argument tells you which infrastructure choices quietly break it.

The model. Each seat is one row with state (status, hold_id). Every change is a single conditional write on that row in one database primary. A primary orders all writes to one row: each write sees the result of the one before. In consistency terms, single-row operations on one primary are linearizable. That means they behave as if they happened one at a time, in an order consistent with real time.

The transitions:

  • Claim: (available, −) or (held with expiry passed, old) becomes (held, h), where h is a fresh UUID.
  • Confirm: (held, h) becomes (sold, −), but only if hold_id = h.
  • Release: (held, h) becomes (available, −), but only if hold_id = h.
  • Refund: (sold, −) becomes (available, −), an explicit operator or business action.

Safety claim. Between refunds, at most one booking reaches sold for a seat. Here is the proof sketch:

  1. A confirm succeeds only from (held, h) and only for the booking that owns h.
  2. Hold IDs are unique, so only one booking can own h.
  3. Once the seat is sold, no claim or confirm predicate matches until a refund, because both require status available or held.
  4. So in the total order of writes on the row, after the first successful confirm, no second confirm can succeed.

The unique constraint on sold tickets is a second, independent guard.

Safety never depends on clocks. Expiry uses now() in the database, so ask what a clock fault does:

  • The clock jumps backwards: holds last longer than intended. That hurts availability, but it is safe.
  • The clock jumps forwards: holds expire early. A second buyer may claim the seat, and the first buyer's confirm then fails on the hold ID, so they are not charged. That hurts the user experience, but it is still safe.

Clocks affect only liveness (whether seats come back promptly) and user experience, never safety (whether a seat is sold twice). Good concurrency designs aim for exactly that split. The same reasoning is behind fencing tokens in distributed locks.

Where the proof breaks: four infrastructure traps.

  1. Claims read from replicas. If the app checks availability on a read replica and then writes based on that read, the gap returns. Use replicas only for display. Every claim must be a conditional write on the primary.
  2. Asynchronous replication and failover. If the primary commits a sale and crashes before the replica receives it, the promoted replica has never heard of the sale. The seat is available again and can be sold twice. For booking ledgers, use synchronous replication to at least one standby (PostgreSQL synchronous_commit with synchronous standbys, or MySQL semi-synchronous replication), or a storage layer with quorum writes. Otherwise, accept a small recovery point objective (RPO) and reconcile against payment records after a failover.
  3. Multi-leader or eventually consistent stores. If two regions can each accept a claim for the same seat and merge later, both claims succeed locally. Conflict resolution such as last-write-wins then silently drops one sale after both buyers were told yes. Strong single-key consistency needs a single leader per key, or consensus per write. Examples are DynamoDB conditional writes on the item's partition, Cassandra lightweight transactions (Paxos), and Spanner or CockroachDB (Raft or Paxos per range).
  4. Holds and sales in different stores. If the hold is in Redis and the sale is in the database, the "single row, single order" argument covers neither system alone. The database confirm must still re-check something it owns, such as status <> 'sold' or a unique constraint, so that a lost Redis key cannot cause a double sale.

Side effects need the same care. Charging a card and emailing a ticket happen outside the database. Use an idempotency key per booking for payment calls, so retries cannot double-charge. Use a transactional outbox, where the confirm transaction also inserts a "send ticket" event that a relay publishes, so that a crash after commit cannot lose the ticket email. See Change Data Capture for outbox relays.

Deep Dive: Flash sales at extreme scaleShow

A flash sale is the hardest contention case, because every buyer wants the same SKU in the same second. A typical case is 10,000 discounted units, 1 million buyers and a start time announced weeks ahead. Large e-commerce platforms have converged on a layered design whose goal is to let only about as many requests through each layer as the next layer can usefully handle.

Layer 1: the edge.

  • Product and countdown pages are static and served from the CDN.
  • The "buy" button is enabled at the start time by a server-signed timestamp, not the client clock.
  • Bot defences include CAPTCHAs, device checks and per-account rules such as a minimum account age or a verified phone number.
  • Once stock runs out, a sold-out flag goes to the CDN and to every API server's local memory. After that, most requests never reach any backend, and the long tail of late clicks costs almost nothing.

Layer 2: admission. A per-SKU token bucket at the API gateway passes only a multiple of the remaining stock, such as 3 × 10,000 attempts in the first seconds. It answers the rest immediately with "sold out or try again" responses. There is no point sending 1 million requests to compete for 10,000 units. A queue or waiting room can replace this when fairness matters more than raw speed.

Layer 3: atomic stock in memory. A Redis Lua script performs the check-and-decrement, enforces one unit per user, and records the order intent, all in one atomic step:

-- KEYS[1] = stock:sku991   KEYS[2] = buyers:sku991   KEYS[3] = orders:sku991 (stream)
-- ARGV[1] = user id        ARGV[2] = request id
if redis.call('SISMEMBER', KEYS[2], ARGV[1]) == 1 then
  return -2                        -- this user already bought
end
local left = tonumber(redis.call('GET', KEYS[1]) or '0')
if left <= 0 then
  return -1                        -- sold out
end
redis.call('DECR', KEYS[1])
redis.call('SADD', KEYS[2], ARGV[1])
redis.call('XADD', KEYS[3], '*', 'user', ARGV[1], 'req', ARGV[2])
return left - 1                    -- units remaining after this purchase

Because the decrement, the buyer record and the order intent (an entry in a Redis Stream) all change inside one script, they cannot disagree with each other. That avoids the two-store gap at this layer. All three keys must hash to the same Redis Cluster slot, so name them with a hash tag such as {sku991}. One Redis node runs simple scripts like this at tens of thousands per second, and the whole stock of 10,000 is gone in well under a second.

Layer 4: durable orders. Consumers read the stream, which can be bridged to Kafka partitioned by SKU. They create orders in the database idempotently, with UNIQUE (sale_id, user_id) and UNIQUE (request_id). Payment follows with a deadline, such as 15 minutes. An unpaid order is cancelled, and its unit returns to Redis through a script that checks the order's state first, so the same unit cannot be returned twice.

Reconciliation, because memory is not a ledger. Redis with AOF appendfsync everysec can lose up to about a second of writes in a crash, and a failover to an async replica can lose more. After the sale, or continuously, compare three numbers: the stock decremented in Redis, the orders created in the database, and the units paid. Alert on any mismatch. The database's unique constraints guarantee that no user gets two orders and no request creates two. The paid count, checked against the true stock in the ledger, is the final guard against overselling. If Redis lost writes, the worst case is a few undersold units. These are re-released in a second wave, which is a far better failure than overselling.

The hot shard problem. One SKU's keys live on one Redis node, so one node takes the whole spike. If that is too much, split the stock across N keys in different slots, such as {sku991:0} to {sku991:7}, with 1,250 units each. Route each buyer to a bucket by hashing their user ID. The per-user limit then needs a separate check keyed by user, and the sell-out tail needs care: buckets run dry at different moments, so a buyer whose bucket is empty probes the others, or the API layer redirects late buyers.

Where the numbers land. 1 million clicks in the first 5 seconds is 200,000 requests per second at the edge. The sold-out flag removes most of them after the first second. The token bucket passes about 30,000 attempts. Redis runs about 30,000 scripts and accepts 10,000. The database inserts 10,000 orders over the next minute, about 170 per second, which is trivial. Every layer did its share of filtering, and the relational database, which is the slowest and most precious component, saw a calm, steady stream.

Key Takeaways#

  • Contention is many writers on one scarce thing. The bug is the gap between read and write, and it only appears under real concurrency.
  • Start with the invariant, and keep the data that must change together in one place: one row, one transaction, one shard. A better shard key removes most cross-shard contention.
  • Conditional writes plus constraints solve most cases. Always check the affected row count, and keep the constraint as the last line of defence.
  • Pessimistic locks suit short, contended, multi-row transactions. Lock in a consistent order, and never hold a lock across payment calls or user think time.
  • Optimistic concurrency suits low contention and long edits. Compare a monotonically increasing version to avoid ABA, and bound retries. On a hot key, it collapses above about λT ≈ 0.37.
  • Reservations with TTL split long flows into hold and confirm. Put the expiry in the claim condition, fence with a hold ID, and separate payment authorisation from capture.
  • Distributed locks coordinate work but do not guarantee correctness on their own. The database confirm must still enforce the invariant.
  • For extreme hot keys, shorten the critical section, spread the load (unit rows with SKIP LOCKED, sharded counters, stock tokens), serialise in a single writer, and batch.
  • Waiting rooms turn an unmanageable spike into a controlled flow. Admit by target concurrency, enforce signed passes, and tell people early when stock runs out.
  • Safety must never depend on clocks, sweepers or caches. Those only affect how quickly inventory returns and how fresh the display is.