skip to content

In a flash sale of 20,000 arena tickets to two million buyers arriving at 10:00, how does an end-to-end stock gate prevent overselling and keep orders matching stock?

level: seniorimportance: must knowfreq 58%

answer

  1. keep the spike off the order database
  2. preload a fast counter
  3. one successful decrement, one purchase token
  4. orders created from tokens, checked again
  5. reconcile counter against orders

basics

~20 s

Preload stock into a fast atomic counter, issue one purchase token per successful check-and-decrement, create orders from tokens asynchronously against a durable stock check, and reconcile the counter with the orders to correct lost or leaked units.

solid answer

~50 s

Before 10:00, copy the 20,000 into a fast in-memory counter so the spike never reaches the order database. Each request runs an atomic check-and-decrement; success issues a purchase token, a unique, expiring right to buy, so outstanding tokens cannot outnumber stock while the counter is right, and once the counter reaches zero a cached sold-out flag turns the rest away cheaply. Workers then create one order per token, unique on the token, and re-check against the durable stock record, which stays the source of truth. Unpaid tokens expire and give their unit back. Because counter and orders are written separately, they drift: a crash between the decrement and recording its token leaks a unit, and a counter failover that loses recent decrements can issue too many tokens. A reconciliation pass compares the counter with stock minus orders minus live tokens, lowers the counter at once when it is ahead, and re-releases leaked units only while token issuance is paused.

code

pseudocode · 15 lines
pseudocode
// Illustrative reconciliation for one sale; names are invented.
// Durable truth: the stock record, the order table and the token records.
function reconcile(saleId, issuancePaused):
    stock    = readStockRecord(saleId).total
    ordered  = count(orders where sale == saleId and status != Cancelled)
    live     = count(tokens where sale == saleId and redeemed == false
                     and expiresAt > now())
    expected = stock - ordered - live
    actual   = counterRead(saleId)
    if actual > expected:
        counterAdd(saleId, -(actual - expected))   // lost decrements: close the gap now
        alert(counterAhead, saleId, actual - expected)
    else if actual < expected and issuancePaused:
        counterAdd(saleId, expected - actual)      // leaked units: re-release only when quiet
    // actual < expected while issuing may be an in-flight token: leave it

go deeper

for a junior

Recall the shape: a fast counter turns most buyers away, a successful decrement gives a right to buy, and the real order is written afterwards in the database.

for a middle

Explain the atomic check-and-decrement, why tokens can never outnumber stock, the order insert unique on the token, and the expiry path that returns unpaid units.

for a senior

Show the drift analysis: failover losing decrements versus crashes leaking units, the durable check as backstop, and an asymmetric reconciliation that never raises the counter mid-issuance.

for a principal

Weigh the cost of a separate fast path against the sale's value: what disagreement the business tolerates, who is told what when a token cannot be honoured, and when the database alone is enough.

## Why the database cannot be the gate The scenario: **20,000 tickets**, **two million buyers**, all arriving at 10:00, so about one hundred buyers per ticket. If every request ran a guarded decrement on one stock row in the order database, every writer would queue on that row, the database would spend its capacity refusing people, and normal traffic would suffer with it. How a single database counter can be tuned or split is its own concurrency topic; a flash sale's answer is to move the **decision** off the database and keep the database as the **record**. ## The gate, stage by stage 1. **Preload.** Shortly before opening, read the sellable quantity from the durable stock record and write it into a fast in-memory counter. The counter must support one atomic operation: decrement by `n` only if at least `n` remain. Turning buyers away is now a memory operation. 2. **Decrement and issue a purchase token.** A request that wins the check-and-decrement receives a **purchase token**: a unique id, the quantity, the buyer's session and an expiry, for example the length of a checkout hold. A variant pre-generates exactly 20,000 tokens and hands each out once; either way, outstanding tokens are bounded by stock. Once the counter reaches zero, every application server caches a **sold-out flag** so later requests are answered without touching the counter. 3. **Create orders asynchronously.** The token is recorded, and order workers turn tokens into orders at a pace the database can sustain. Each order insert is **unique on the token id**, so a retried message cannot create a second order, and it re-checks the **durable stock record** (sold plus pending below total) before committing. That check sees roughly 20,000 writes over minutes rather than two million in seconds. 4. **Pay or expire.** The buyer pays within the token's time limit. An unpaid token expires; its order is cancelled and the unit is returned to the counter exactly once. | Stage | Guarantees | How it fails | |---|---|---| | Preload | the fast path starts from the true stock | loaded late or from a stale read | | Decrement and token | outstanding tokens ≤ stock, while the counter is right | counter loses decrements on failover | | Order creation | orders ≤ durable stock, one per token | worker crash after the decrement leaves a token with no order | | Expiry | unpaid units come back | a unit returned twice, or never | ## Where counter and orders drift apart The counter and the order table are two stores written at different moments, so no transaction keeps them equal. Each direction of drift has its own cause: - **Counter ahead of truth (too many units left).** The in-memory counter fails over to a replica that had not received the last few hundred decrements, or an expiry returns a unit twice. More tokens than stock can now be issued. The durable check at order creation stops more orders than stock from existing, but the extra token holders were told they had a ticket, which is the worse experience. - **Counter behind truth (units leaked).** A decrement succeeds and the process dies before the token is recorded, or a token lapses and its return is lost. Those units are sold to nobody, and the sale ends with unsold seats while buyers were told it sold out. ## Reconciliation A reconciliation pass computes what the counter *should* read from durable facts and corrects the difference: - **Expected remaining** = durable stock − orders not cancelled − purchase tokens that are unredeemed and unexpired. - If the counter is **above** expected, lower it immediately and alert; this direction oversells. - If the counter is **below** expected, do not raise it while tokens are being issued. A decrement whose token has not been recorded yet looks exactly like a leak, so raising mid-flight could oversell. Re-release leaked units in a pass taken while issuance is briefly paused, or after the sale closes. The rule is asymmetric on purpose: during the sale, every correction errs toward **underselling**, which a later pass can fix, never toward overselling, which cannot be undone without disappointing a buyer. ## What to watch during the sale - Tokens issued against orders created, and the lag between them. - The reconciliation gap in each direction, with an alert on any counter-ahead gap. - Orders rejected by the durable check, each of which is a token that should never have been issued. - How quickly the sold-out flag reached every server, since slow propagation means wasted counter traffic, not oversell. Admission in front of this gate, such as a waiting room, decides who may even attempt a decrement; per-account limits and bot defence are separate controls.

  • If the order database re-checks stock anyway, why bother correcting a counter that is ahead?
    Because the durable check only limits orders, not promises. A counter that is ahead keeps issuing purchase tokens, and every buyer holding one was told they had a ticket. When their order is rejected at the durable check, the oversell has become a broken promise to a real person. Lowering the counter quickly stops issuing tokens that cannot be honoured.
  • How should an expired purchase token return its unit without returning it twice?
    Make the return a conditional change on the token itself: mark it returned only if it is unredeemed and not already returned, and add the unit back to the counter only when that change applied. A retried expiry then finds the token already returned and does nothing. Reconciliation catches any return that was lost between the two steps.
  • Why preload the counter shortly before opening instead of keeping it in step with the database all the time?
    Outside a sale the database alone handles the traffic, and a permanently mirrored counter is a second copy that can drift for no benefit. Loading it just before opening, from the durable stock record, gives the fast path a known-good starting value, and the sale's own reconciliation keeps the two aligned only for the window that needs it.

  • The order database can absorb the spike with a guarded decrement on one row.
  • A fast in-memory counter is the source of truth for stock.
  • Once the counter is atomic, counter and orders can never disagree.
  • If the counter is below expected, raise it immediately during the sale.
  • Issuing a purchase token means the order is already safely created.