Learn

PATTERN · ORIGINAL

Reservations and contention: selling what you have, exactly once

How to sell finite inventory without overselling: conditional updates and row locks, holds that expire, pre-split tokens for burst giveaways, and waiting rooms that keep it fair.

Every reservation system protects one sentence: never sell more than you have. A hotel has 40 king rooms on the night of the 14th. A giveaway has 10,000 units. An account may stream on 4 screens. A driver can carry one rider. The design work is in two places: making that sentence true when many requests arrive at once, and keeping it true without turning one database row into a queue that everyone waits in.

This article walks through the tools in the order you should reach for them. Start with the database enforcing the rule. Add holds when a purchase takes minutes, not milliseconds. Pre-split the inventory only when a single row truly cannot keep up. Put a waiting room in front when demand dwarfs supply and fairness becomes part of the product.

First, name the unit of inventory

Before any locking discussion, write down what exactly is scarce. Getting this wrong is the most common reason a sketch oversells.

  • Hotel booking: a room type on a date (a room-night), not a room. A three-night stay consumes three units, and all three must succeed together. See hotel booking.
  • Limited giveaway: one unit of one item, plus a second limit you must also enforce: one per account. See limited giveaway.
  • Concurrent streams: a slot on an account, which is held for as long as playback continues and must be released when a device goes silent. See concurrent stream limits.
  • Dispatch: a driver's availability. The scarce thing is a person, and you must never offer one driver to two riders at once. See dispatch matching.

Once the unit is named, the invariant becomes checkable: for every unit, confirmed plus held is at most capacity. Every design below is a different place to enforce that inequality.

Database-enforced inventory

The conditional update

The simplest correct design keeps a counter per unit and lets the database refuse the write that would break the rule:

UPDATE inventory
   SET reserved = reserved + 1
 WHERE room_type = 'king' AND night = '2026-12-14'
   AND reserved < capacity;
-- 1 row affected: you got it. 0 rows: sold out.

The check and the increment happen in one statement on one row, so two requests cannot both see 39 and both write 40. You do not need a special isolation level for this. You do need to read the affected-row count and treat zero as sold out.

Row locks and lock ordering

When the decision needs more logic than a WHERE clause can express, lock first and decide second: SELECT ... FOR UPDATE on the inventory rows, run your checks, write, commit. A multi-night stay locks one row per night. Here is the trap: guest A locks the 14th then the 15th while guest B locks the 15th then the 14th. Each waits on the other, and the database kills one as a deadlock.

The fix is boring and reliable: always lock in a fixed order, for example by (room type, night) ascending. If every transaction acquires locks in the same order, no cycle can form. An alternative is a single statement that updates all three nights with the capacity condition and checks that exactly three rows changed; if not, roll back.

Unique constraints as inventory

Some limits are not counters at all. "One per account" is a unique index on (giveaway_id, user_id). Assigned seating is a unique index on (event_id, seat_id). A unique constraint is the cheapest lock you will ever take, and it doubles as idempotency: a retried request hits the constraint and you return the existing claim instead of a second one. Consistency and idempotency goes deeper on retry-safe writes.

When one row becomes the bottleneck

A row lock serializes writers. If a transaction holds the lock for about 2 ms (a network round trip plus the write), one row tops out near 500 updates per second, and less once commits wait on replication. That number drives the decision:

  • A popular hotel room-night might see a few booking attempts per minute. One row is plenty for decades.
  • A giveaway of 10,000 units where 1 million people click in the first 10 seconds sends 100,000 requests per second at one row. That is 200 times what it can absorb. Requests pile up, time out, retry and make it worse.

Database enforcement is the right default. It stops being enough only when the contention on a single unit is extreme, which is a burst-giveaway problem, not a hotel problem.

Holds with expiry

Many purchases are not one step. A guest picks a room, then spends two to eight minutes entering card details. If you only decrement at payment, two guests can both reach the payment page for the last room and one gets an apology after paying. If you decrement at selection and never give it back, abandoned carts quietly sell you out.

A hold splits the purchase in two:

  1. Reserve: conditionally increment held and insert a hold row with expires_at = now + 10 minutes. The capacity check counts holds and confirmed bookings together.
  2. Confirm: after payment succeeds, convert the hold to a booking in one conditional statement that also checks the hold is still active. If it expired and the unit was resold, you refund instead of overselling.
  3. Release: a sweeper deletes expired holds and decrements held. Reads can also ignore expired holds lazily, so a slow sweeper costs a little availability, never correctness.
FIG. 1ORIGINAL SKETCH
pick room1reserve hold2charge3confirm if held4release expired5GuestBooking APIInventory DBheld + sold ≤ capPayment providerHold sweeperTTL 10 min
A hold-based booking flow: the inventory store enforces capacity on reserve and on confirm, payment happens between them, and a sweeper returns expired holds.

Choosing the TTL is a real trade-off. If 30% of holds are abandoned and holds last 10 minutes, then during a busy hour a noticeable share of your inventory is invisible to shoppers. Shorten the TTL and some honest guests lose their room mid-payment. A practical pattern is a short TTL (5 to 10 minutes) with an extension when the guest reaches the payment form.

Make the confirm step idempotent with a key tied to the hold. The payment callback may arrive twice, or arrive after the guest's browser already retried. The same discipline shows up in the wire transfer API, where a hold on funds plays the role a hold on a room plays here.

Burst giveaways: split the counter

When one unit gets hundreds of thousands of attempts per second, stop asking one row to decide. Split the decision so each part is uncontended.

Pre-split tokens

Before the drop, mint 10,000 tokens and spread them across 100 shards of 100, each shard a key in an in-memory store. A request picks a random shard and atomically decrements it. If the result is zero or below, it tries one or two other shards, then reports sold out. Each shard now sees about 1% of the traffic. A winner gets a signed claim, and an asynchronous worker writes the order to the durable database, where a unique (giveaway_id, user_id) constraint enforces one per account.

The property you want: the tokens are the authority, and the total minted equals the stock. If a shard crashes and loses its remaining 37 tokens, you undersell by 37, which you can fix by re-minting after an audit. You never oversell, because no path creates a token. Shards drain unevenly near the end, so let a small rebalancer move leftovers, or accept a slightly ragged sell-out.

Token buckets for admission

The same idea, applied to rate rather than stock, is a token bucket in front of the purchase path: let in only as many requests per second as the backend can finish. That is admission control, and it pairs naturally with a waiting room.

Queueing users and fairness

With 1 million people and 10,000 units, 99% of visitors will lose no matter what you build. The design question becomes how they lose and whether it feels fair.

  • Waiting room: visitors get a position and a page that polls. A gate admits them at the rate the purchase path can serve, say 2,000 per second, and hands each a signed admission token that expires in a few minutes. The purchase API rejects requests without a valid token, so bots that skip the page gain nothing.
  • First come, first served rewards fast networks and scripts. It is simple to explain, and it turns your launch into a latency contest.
  • Lottery: collect entries for a window (say 5 minutes), dedupe by account and payment instrument, then draw winners. Arrival time stops mattering, the backend load becomes flat, and abuse moves to account creation, which you can attack with verification.

Whichever you choose, say it in the product. People accept losing a lottery more easily than losing a race they could not see. The broader patterns for shedding load sit in queues, retries and dead letters.

The same pattern in disguise

Concurrent stream limits

A stream slot is a hold that renews itself. Starting playback acquires a lease row with a conditional insert (active leases for the account under 4). The player heartbeats every 30 seconds and each heartbeat extends the lease to 90 seconds out. A crashed TV simply stops renewing, and its slot frees itself without anyone calling "stop". The interesting decisions are the lease length (how long a dead device blocks a live one) and what to do at the limit: refuse, or let the newest device evict the oldest. Presence-style counting with heartbeats is covered in counting at scale.

Dispatch matching

Here the inventory is a driver. The matcher picks a candidate and then claims them with a conditional update: set state from available to offered for this trip, only if the state is still available. If zero rows change, another matcher got there first; pick the next candidate. The offer carries an expiry (say 15 seconds) so a driver who ignores it returns to the pool. Finding candidates is a geospatial problem (see geospatial indexing); claiming them is a reservation problem.

OptionWins whenCosts
Conditional update or row lockEach unit sees modest contention (hundreds of writes per second or less) and the purchase is one quick step.One hot row caps throughput near a few hundred writes per second. Multi-row locks need a fixed order to avoid deadlocks.
Hold with expiry, then confirmPurchase spans minutes (payment, form filling) and you must not let two people pay for the last unit.Abandoned holds hide inventory for the TTL. Needs a sweeper, idempotent confirm and a refund path for late payments.
Pre-split tokens across shardsA single burst far beyond one row’s capacity, such as a timed giveaway.Uneven drain at the end, an extra in-memory tier, and asynchronous order writes you must reconcile.
Waiting room or lottery in frontDemand is 10x to 1000x supply and fairness or bot resistance matters.More product surface (positions, tokens, messaging) and a slower experience for everyone.

TAKE THIS TO YOUR NEXT SKETCH

  • Name the scarce unit first (room-night, item, slot, driver) and write the invariant as an inequality you can point to.
  • Default to the database enforcing it: a conditional update, a row lock taken in a fixed order, or a unique constraint.
  • Use holds with a TTL when buying takes minutes. Confirm with a conditional write that checks the hold is still valid, and keep a refund path.
  • Only split inventory into pre-minted tokens when one row cannot keep up; make tokens the authority so failures undersell rather than oversell.
  • When demand dwarfs supply, design the losing experience: a waiting room with signed admission tokens, or a lottery.

PRACTICE WITH THIS

Now sketch one.

OFF-SITE READING · NOT WRITTEN BY US

Further reading

  • Explicit Locking

    PostgreSQL documentation

    The reference for row-level lock modes, SELECT FOR UPDATE and how deadlocks are detected, which is exactly what a database-enforced booking path leans on.

  • Transaction Isolation

    PostgreSQL documentation

    Read the sections on Read Committed and Serializable to see which check-then-act races each level does and does not stop.

  • Working with items and attributes (conditional writes)

    Amazon DynamoDB documentation

    Shows the same compare-and-set idea in a key-value store: a write that only applies when a condition on the current item holds.

Next: Caching and hot keys