Skip to content
CodeBrewerz logoCodeBrewerz
System Design

Selling the Last Ticket: Reservations, Oversell, and the Queue at the Door

A stock count is not inventory. Between the click and the payment there is a state your database does not have a word for, and every ticketing failure you have read about lives in that gap.

Published 7 min readBy Piyush Jain
  • System Design
  • Concurrency
  • Databases
  • E-commerce

An inventory system has one job — never sell the same seat twice — and it has to do it while ten thousand people press the same button in the same second.

The naive model is a number. remaining: 100, decrement on purchase. It is wrong in a way that only shows up under load, and it is wrong for a reason worth stating before any code: between the moment a customer chooses a seat and the moment their payment settles, there is a state that is neither available nor sold. Payment takes seconds and can fail. If the seat is available during that window, two people buy it. If it is sold, a failed payment permanently destroys inventory.

That third state — reserved — is the whole system.

The oversell is a race you have seen before

Figure 1

One hundred seats, and everyone clicks at once

Stock 100 · one bar per 50 ms of the sale—
Confirmed—
Oversold—
Cost—

—

Implementation
Buyers arriving at once
The naive implementation reads the remaining count, decides, then decrements. Every buyer whose read lands before anyone's write sees stock available, so the overshoot is roughly the number of concurrent requests in flight — it grows with popularity, which means the busier the sale, the more seats you sell that do not exist. A single conditional decrement cannot overshoot at all, at any concurrency.

Read the remaining count, check it is above zero, write the decrement. Set the buyers to 500 and watch the overshoot.

This is the same check-then-act race as the rate limiter and the same one that appears in driver dispatch, and here it has a number a finance team can read. Everyone whose read lands before the first write sees stock available, so the overshoot scales with concurrency — smallest in testing, largest during the sale you built the system for. And it does not fail; it confirms. The customer gets a confirmation email. Somebody finds out at the door.

The fix is not a lock and not a transaction wrapper. It is to make the decision and the write one statement, and let the database refuse:

-- The check is the WHERE clause. Zero rows updated means sold out.
UPDATE inventory
   SET remaining = remaining - 1
 WHERE item_id = $1 AND remaining > 0;

If that returns zero affected rows, the item is gone — no read, no gap, nothing to interleave. Switch the figure to the conditional version and raise the concurrency: the overshoot stays at zero, because there is no window for it to live in. Add a CHECK (remaining >= 0) constraint as well, so that even a future bug in application code cannot drive it negative. The database is where this invariant belongs.

For assigned seating the same principle applies per seat: rows in a seats table with a status column, and claiming one is UPDATE ... WHERE seat_id = $1 AND status = 'available'. One statement, zero or one rows affected, no ambiguity.

How long is a hold?

Once reservations exist, someone has to choose how long they last, and it is usually set to ten minutes by whoever wrote the ticket.

Figure 2

Two hundred holds, and how many became sales

Outcome of 200 holds on 200 units—
Completed—
Lost to expiry mid-checkout—
Unit-minutes held by abandoned carts—

—

Hold duration
Checkout times are a long tail: most people take two minutes and some take fifteen. A short hold expires under the slow ones and loses completed sales. A long hold parks stock behind buyers who abandoned, so the item shows sold out while units remain — the most expensive failure of the two, because nobody ever reports it. The idle-stock number is what a five-minute hold is buying you.

Both directions are real failures. A two-minute hold expires under the buyers whose card needed a verification step, and they discover it at the moment of payment — the worst possible time to tell someone the thing they were buying is gone. A thirty-minute hold loses nobody to expiry and parks a large amount of stock behind carts that will never complete.

The second failure is the more expensive one and the one nobody reports, because during that window the item reads as sold out while units still exist. The customers who wanted it simply left, and there is no ticket in your queue about it.

Five to ten minutes is the usual answer, and two refinements are worth more than tuning the number. Release the hold explicitly when the customer abandons the flow or the payment provider returns a definitive failure, rather than waiting for the timer — most abandoned carts announce themselves. And do not implement expiry as a sweeper job if you can avoid it: a background process that deletes expired holds every minute is a window in which stock is neither held nor available. Store an expires_at and treat the row as available when reading if the timestamp has passed, so expiry is a property of the data rather than an event that has to happen on time.

The queue at the door

For a normal shop, that is the system. For a sale where a hundred thousand people arrive in the same second, there is one more piece, and it is the difference between a launch and an outage.

You cannot serve a hundred thousand simultaneous checkout flows. What you can do is admit people at the rate the checkout can actually handle: a virtual waiting room that assigns each arrival a position and a token, and releases tokens at a measured rate. Everything behind the door then runs at a load you have tested.

This is worth building for three reasons that are not obvious. It converts an unpredictable failure — everything timing out, nobody able to buy — into a predictable wait, and a wait with a visible position is tolerable in a way a spinner is not. It makes the sale fair in a defensible sense, because admission is by arrival order rather than by who has the fastest connection and the most aggressive retry loop. And it turns a load-shedding problem into a scheduling one, which is the kind you can reason about.

The queue itself must be trivially cheap: a position and a token, served from a cache or the edge, with no database work per waiting user. If your waiting room needs the database, it will fall over alongside everything else.

The parts nobody mentions

Reservation must be idempotent. A user’s browser retries the reserve call and now holds two seats, one of which nobody will ever pay for. Every reservation carries a client-generated key, and a repeat of a known key returns the existing hold — the same idempotency contract as any payment.

The hot row is the bottleneck. Every buyer for one popular item contends on one row, and row locks serialise them. Splitting the count into N sub-counters — 10 rows of 10 units, buyers hashed across them — removes the contention and introduces a new failure: a buyer can be told “sold out” while another bucket still has stock. Rebalancing or a fallback scan fixes it, and both add complexity you should only take on when you have measured the contention.

Cancellation is not the inverse of purchase. Returning a unit to stock has to be idempotent too, has to interact with whatever partial refund happened, and must not resurrect inventory for an event that has already started. Model it as a new event, not as an undo.

The count you show is not the count you enforce. Displaying live remaining stock on a hot item means a read per page view against your most contended row. Serve a cached, slightly stale number for display, and let the conditional update be the only thing that decides — the customer seeing “3 left” when there are 2 is fine; the customer buying a fourth is not.

Reconciliation is a permanent job, not a launch task. Payments settle asynchronously and sometimes disagree with your inventory. A daily job comparing confirmed payments against issued units is the only way you will discover a slow leak before your customers do.

The short version

Inventory has three states, not two, because payment takes time and can fail. Model reserved explicitly or you will either oversell or destroy stock on every failed card.

Never read a count and then write it. UPDATE ... WHERE remaining > 0, check the affected row count, and add a CHECK constraint underneath — the overshoot in the naive version scales with concurrency, so it is smallest in your tests and largest on the day it matters, and it confirms rather than failing.

Pick a hold duration knowing both errors are real: too short loses buyers at the payment step, too long shows sold out while units sit behind carts nobody will complete — and only the first one generates support tickets. Release holds on explicit abandonment, and make expiry a property of the row rather than a sweeper job that leaves a gap.

Then, if the sale is genuinely popular, put a cheap queue in front of the door and admit people at the rate your checkout can serve. Turning “everything times out” into “you are number 4,120” is not a user experience compromise. It is the only version where anyone buys anything at all.

Next step

Want This Built, Not Just Explained?

CodeBrewerz builds the systems these posts take apart: web, mobile, cloud and the infrastructure underneath. Tell us what you are building.

Start a conversation