Skip to content

Design a Flash Sale and E-commerce Checkout

Advanced 75 min read Part 17 of 18

Design a flash sale: 10,000 units, 10M buyers in a minute. Holds with expiry, no overselling, hot-SKU contention, waiting rooms, fair access and checkout.

The Problem#

A flash sale sells a small, fixed amount of stock to a very large crowd, in a very short time. A sports brand releases 10,000 pairs of a limited-edition shoe at exactly 12:00. Ten million people have the page open, and most of them press "Buy" in the first few seconds. A console launch, a concert-merch drop, a limited sneaker run and a "doorbuster" deal on Black Friday all have the same shape.

Most e-commerce design problems are about breadth: catalogues, search, recommendations and reviews. This one zooms in on the hardest few minutes of e-commerce, when:

  • demand outnumbers supply by 1,000 to 1, so almost everyone must be told "no", quickly and politely;
  • every request targets the same few rows, the inventory of one product (one SKU, a stock-keeping unit: one size and colour of one product);
  • overselling is unacceptable. Selling unit 10,001 means cancelling a customer's order, and that costs money and trust;
  • underselling is also a failure. Units stuck in abandoned checkouts show as "sold out" while stock sits in the warehouse;
  • payment is slow and external. A card authorisation takes a second or more, and a buyer may take minutes to type their card details.

Analogy. Picture a bakery that bakes exactly 100 rare cakes and opens its doors at 9:00, with 10,000 people outside.

  • A doorman lets people in a few at a time, so the shop isn't crushed. That is the waiting room, or queue-based admission.
  • At the counter, the baker hands you a numbered ticket for one cake, and says: "Pay at the till within 10 minutes, or I give it to someone else." That ticket is the reservation, a hold with an expiry.
  • The cakes sit in a row of separate boxes. Several clerks can each take a different box at the same time, instead of fighting over a single tray. That is how we avoid hot-row contention.
  • The baker counts tickets, not hopes. When the last ticket is handed out, a sign goes up: "Sold out". It is visible from the back of the crowd, so people stop pushing. That is preventing oversell and broadcasting "sold out" early.
  • If you walk away without paying, your ticket expires and the cake goes back into the stock for the next person.

The trickiest requirement, and the one people often skip, is the reservation step. Buyers don't go straight from "view" to "paid". Payment runs through a third party and takes seconds to minutes, and we cannot hold a database transaction open that long. So the system first takes a unit off the table for that buyer, for a limited time, and settles the money afterwards.

Clarifying Questions#

QuestionAssumed answer
What is in scope?One flash sale for a limited item: view it, reserve a unit, pay. The general catalogue, search, returns and admin tools for configuring sales are out of scope.
How much stock and demand?~10,000 units across a few SKUs (sizes). ~10 million interested users, most arriving within the first minute.
Can one person buy several?A limit of 1 or 2 per account, enforced by the system
How long is a reservation held?~10 minutes to complete payment. Then the unit returns to stock.
Is overselling ever acceptable?No. Zero oversell is a hard requirement. Brief underselling (a unit invisible for seconds) is tolerated, but a long one is a bug.
Fairness?First-come-first-served at the moment of reservation, or a randomised queue to blunt bots. Bots and scalpers must be limited.
Payment?An external payment provider (cards and wallets). Authorise at checkout and capture at shipment, or capture immediately for digital goods.
Regions?Global audience. Inventory is one global pool, unless the business splits stock by region.
Does the catalogue need a best-sellers ranking?Yes. The shop shows "best sellers this week by category", updated hourly. We design that as a supporting feature.

Requirements#

Functional#

  1. View the sale item: product details, price, sale start time, and a live status (upcoming, available, low stock, sold out).
  2. Reserve a unit: while the sale is active, a user can secure one available unit (per allowed quantity) for a limited time. They either get a reservation or a clear "sold out" or "waiting" response.
  3. Pay to complete the purchase: a user holding a valid reservation can pay. On success, an order is created and the unit is permanently sold. On failure or expiry, the unit returns to stock.
  4. Cart and checkout in the normal shop: add items to a cart, check out with address, shipping and payment. The flash sale uses the same checkout pipeline, with a reservation attached.
  5. Best sellers by category: show the week's most popular products in each category, refreshed at least hourly.

Below the line: catalogue browsing and search, shipping and returns, refunds, order history, and admin tools for creating sales.

Non-Functional#

  • Strong consistency for inventory. Never sell more units than exist. Each unit is sold to at most one buyer.
  • High availability for viewing. The product page must stay up under 10M visitors, even if purchasing is saturated.
  • Throughput. Absorb a peak of hundreds of thousands to ~1 million purchase attempts per second at the edge, and admit to the inventory system only what it can handle (thousands per second).
  • Low latency for decisions. A reserve attempt answers (reserved, sold out or queued) in under ~500 ms at p99 once admitted.
  • Fairness. Requests are treated in a defensible order, and bots and multi-account abuse are limited.
  • Durability. A reservation or order acknowledged to a user is never lost.
  • Prompt release. Expired or abandoned reservations return to stock within seconds, so the sale doesn't falsely read "sold out".

Capacity Estimation#

Demand at the moment of the sale.

  • 10 million interested users. Suppose 60 percent are active at 12:00:00, and each client sends a reserve attempt within the first 10 seconds, plus a few retries. That is ~6 million users × ~3 attempts ≈ 18 million requests in 10 seconds, or ~1.8 million requests per second at the edge in the first seconds. Bots multiply this, often by several times.
  • Page views in the minutes before the sale: 10M users refreshing every ~10 seconds is ~1 million requests per second. Nearly all of them must be served by a CDN.

Supply.

  • 10,000 units, perhaps across 10 sizes, so roughly 1,000 per SKU. Some sizes, such as the popular middle sizes, are much hotter than others.
  • At most 10,000 successful reservations ever matter, plus re-reservations of released units. The vast majority of the 18 million attempts must receive "sold out" or "wait" responses without touching the inventory database.

What the inventory tier must handle.

  • If admission lets in, say, 5,000 reserve attempts per second, the sale's 10,000 units are allocated in ~2 to 5 seconds, assuming most admitted users succeed. Released units (abandoned or failed payments, often 10 to 30 percent in flash sales) trickle back over the next 10 to 15 minutes.
  • A single inventory row with a lock held for ~2 ms per transaction caps at ~500 reservations per second per SKU. That is the hot-SKU contention problem (Deep Dive 1).

Payments. 10,000 reservations, with perhaps 85 percent paid, is ~8,500 payments over ~10 minutes. That is ~15 per second: trivial for the payment provider. The bottleneck is entirely in admission and inventory, not in payment.

Storage. Reservations and orders: tens of thousands of rows per sale. Even a large shop's whole-year order volume is modest in bytes. The problem is concurrency, not size.

Best-sellers feature (normal shop traffic, separate from the sale):

  • assume 10 million products, 1,000 categories and 1 billion purchases per month. That is ~400 purchases per second on average;
  • a purchase record is ~40 bytes (timestamp, product, category, seller, buyer, quantity and price), so ~40 GB per month and ~1.5 TB over three years;
  • reads of best-seller lists at ~100 times the write rate: ~40,000 per second on average, with peaks well above that.

Useful conversion: a month has ~2.5 million seconds, so 1 request per second ≈ 2.5 million per month, and 400 per second ≈ 1 billion per month.

Core Entities#

  • Product / SKU: the item and its variants (size, colour). Each SKU has its own inventory.
  • Sale: a flash-sale event: which SKUs, price, start time, end time, per-user limit, reservation TTL.
  • Inventory: for each SKU, total units, units sold and units currently held. In some designs this is one row per reservable unit (Deep Dive 1).
  • Reservation (hold): a user's temporary claim on N units of a SKU, with expires_at and a status (ACTIVE, CLAIMED, RELEASED, EXPIRED).
  • Admission token: proof that a user passed the waiting room and may attempt to reserve, with an expiry.
  • Cart: in the normal shop, a user's list of items before checkout. It does not hold inventory.
  • Order: the confirmed purchase: items, price, address and payment reference, with a lifecycle (PENDING_PAYMENT, PAID, FULFILLED, CANCELLED).
  • Payment: the provider's authorisation or capture result, linked to the order by an idempotency key.

API Design#

GET  /sales/{saleId}
     -> { product, skus: [{ skuId, size, status: "AVAILABLE|LOW|SOLD_OUT" }], startsAt, serverTime }

POST /sales/{saleId}/queue                          # join the waiting room
     -> { position, ticket }                         # or a redirect to the waiting-room page

GET  /sales/{saleId}/queue/{ticket}                 # poll, or receive an SSE push
     -> { status: "WAITING|ADMITTED", admissionToken?, estimatedWait }

POST /sales/{saleId}/reservations                   # needs admissionToken and an Idempotency-Key
     { skuId, quantity }
     -> 201 { reservationId, expiresAt }
     -> 409 { error: "SOLD_OUT" }   |  429 { error: "LIMIT_REACHED" }

POST /checkout
     { reservationId | cartId, shippingAddress, paymentMethodToken }
     -> 202 { orderId, status: "PENDING_PAYMENT" }   # final status via polling or webhook to client

DELETE /reservations/{reservationId}                # the user abandons, so release now

GET  /categories/{categoryId}/best-sellers?limit=50
     -> [{ productId, rank, unitsSold }]

Notes:

  • The reserve endpoint is the hot one. It must be cheap to reject. It checks the admission token (a signed token verified without a database call), the per-user limit, and a cached sold-out flag, before doing any inventory work.
  • Idempotency keys make retries safe. A client that times out and retries gets the same reservation back, not a second one (see Idempotency and Safe Retries).
  • Server time in responses lets the page count down to the start time accurately, without trusting the device clock.
  • Checkout is asynchronous, because payment can take seconds. The client learns the result by polling the order or through a push channel.

High-Level Design#

We build the design one requirement at a time, then combine the pieces.

1) Users can view the flash sale item#

The product page is read-heavy and identical for everyone: the same photos, description and price for 10 million people. That is the perfect workload for a CDN (see Content Delivery Networks (CDN)).

  • The static page (HTML, JavaScript, images) is published to the CDN before the sale, with long cache lifetimes. Origin servers see almost none of the ~1 million requests per second.
  • Dynamic status (available, low, sold out) is a tiny JSON document, GET /sales/{id}. It is cached at the CDN for 1 to 2 seconds, with request collapsing, so each edge sends at most one request per second to the origin. The origin reads it from a cache (Redis) that the inventory service updates.
  • Countdown: the page shows a timer to startsAt, computed from serverTime rather than the device clock. At 12:00 the "Buy" button activates. It is gated by the server too: a reserve attempt before the start is rejected.

2) Users can reserve an available unit for a limited time#

Never hold a database transaction open while the user pays. Instead, a short transaction creates a reservation: it takes a unit out of the available pool and writes a hold with an expires_at 10 minutes ahead. Then it commits, in a few milliseconds. The unit is now invisible to others, but no lock is held.

The core check must be atomic, so two buyers cannot both get the last unit:

-- the simplest correct version: a conditional decrement on one counter row
UPDATE inventory
SET    available = available - 1
WHERE  sku_id = 42 AND available >= 1;          -- 1 row: reserved; 0 rows: sold out
INSERT INTO reservations (id, sku_id, user_id, qty, expires_at, status)
VALUES ($id, 42, $user, 1, now() + interval '10 minutes', 'ACTIVE');

Both statements run in one transaction. This is correct, but every buyer of SKU 42 updates the same row, and the database serialises them on that row's lock. Deep Dive 1 removes that bottleneck.

In front of the inventory service sit three cheap filters, so that most of the 1.8 million attempts per second never reach it:

  1. Waiting room admission: only users with a valid admission token may call reserve (requirement 3 below explains how tokens are issued).
  2. Sold-out short-circuit: if the status cache says SOLD_OUT for that SKU, reject immediately. The edge can even serve this rejection itself.
  3. Per-user limit: one active reservation per user per sale, checked in Redis and enforced again in the database with a unique constraint.

3) Users who hold a unit can pay to complete the purchase#

  1. The client calls checkout with the reservation id, address and a payment token (the card is tokenised by the provider's client library, so card numbers never touch our servers).
  2. The Checkout Service checks that the reservation is ACTIVE, belongs to the user and has not expired. It creates an order in PENDING_PAYMENT, and calls the payment provider with an idempotency key equal to the order id.
  3. On success (synchronous response or webhook), one transaction marks the reservation CLAIMED, permanently decrements sold inventory, and marks the order PAID. An outbox event triggers fulfilment and the confirmation email.
  4. On failure, the reservation is released: its unit returns to the pool, and the user may retry with another card while the hold is still valid.
  5. If nothing happens before expires_at, the hold expires and the unit returns to the pool automatically (Deep Dive 2).

Timing rule: the reservation's TTL must comfortably exceed the payment flow. If a payment can take up to 60 seconds with 3-D Secure (the card issuer's extra authentication step), a hold must not expire mid-payment. The Checkout Service extends the hold briefly when payment starts, or checks the hold again at claim time and refunds or voids an authorisation that arrives too late.

4) Users arrive in their millions at once: queue-based admission#

Even with filters, letting 1.8 million requests per second hit the reservation path would overwhelm the gateway tier and fill the database with contention. A virtual waiting room turns the spike into a steady, controlled flow:

  • At 11:55, users visiting the sale page are placed in a waiting room, served from the CDN or a dedicated, horizontally scaled queue service.
  • At 12:00, each waiting user gets a random position. Randomising at the start means that arriving early (or using a bot that refreshes fastest) gives no advantage. Users arriving after 12:00 join the end of the queue, in arrival order.
  • An admission controller lets users through at a fixed rate, matched to what the reservation service can handle (say 5,000 per second). Each admitted user receives a signed admission token, valid for a few minutes.
  • When the sale sells out, the queue is told immediately. Waiting users see "sold out" rather than waiting for nothing. If units come back (expired holds), admission resumes.

The waiting room is the single most effective protection for the inventory tier. Deep Dive 3 covers its internals.

The full high-level design#

Components:

  • CDN and edge: serves the product page and images, caches the per-SKU status for a second or two, filters obvious bots, and can serve "sold out" without calling the origin.
  • Waiting room service: holds users in a queue before and during the sale, assigns random positions at the start, and shows each user their position and estimated wait.
  • Admission controller: issues signed admission tokens at a rate the purchase path can absorb, and stops when stock is gone.
  • API gateway: verifies tokens (a signature check, no database call), applies rate limits per user, device and IP, and routes requests (see API Gateway and Backend-for-Frontend).
  • Reservation Service: enforces per-user limits and runs the short atomic reserve transaction. It returns RESERVED, SOLD_OUT or LIMIT_REACHED.
  • Checkout Service: validates the hold, creates the order, talks to the payment provider, and claims or releases the hold.
  • Inventory database: holds the ledger (units the merchant really has, and units sold), the pool of reservable units, and the holds. It is the single source of truth, so reserve and claim commit in one transaction with the ledger.
  • Redis: status cache (AVAILABLE, LOW or SOLD_OUT), per-user limit counters, rate-limit counters. It is never the source of truth for inventory in this design (Deep Dive 5 explains why).
  • Event log (Kafka): reservation, release and order events, delivered via an outbox. Consumers update status caches, refill the pool, send emails, start fulfilment and feed analytics.
  • Expiry sweeper and pool refill: background workers that garbage-collect expired holds and keep the reservable pool topped up.
  • Best-sellers pipeline: aggregates purchases per category into hourly rankings for the shop (Deep Dive 11).

Key Flows#

Flow 1: from waiting room to reservation#

  1. The user joins the waiting room before the sale. At 12:00 they receive a random position, and wait.
  2. The admission controller releases them, and they receive a signed token with the sale id, user id and expiry.
  3. Their client calls reserve. The gateway verifies the token locally, and enforces per-user and per-IP rate limits.
  4. The Reservation Service checks the cached sold-out flag and the per-user limit, then runs the reserve transaction: claim a free unit row, write the hold, and write an outbox event, all in one commit.
  5. The response says "reserved until 12:10". The UI starts a 10-minute checkout timer.

If no unit is free, the transaction finds nothing to claim. The service returns SOLD_OUT and sets the status cache, so later requests are rejected at the edge.

Flow 2: checkout and payment#

  • If the provider declines, the Checkout Service marks the order FAILED. It keeps the hold ACTIVE until it expires, so the user can try another card, or releases it immediately if the user abandons.
  • If the provider times out, the Checkout Service does not guess. It queries the provider with the same idempotency key, or waits for the webhook. Meanwhile the hold stays ACTIVE (it can be extended once by a minute or two), so the unit isn't resold while the outcome is unknown.
  • If the provider reports success after the hold expired (rare, if TTLs are set sensibly), the claim transaction finds the hold EXPIRED. If the unit has been re-reserved, the authorisation is voided and the user is told the unit is gone. If stock remains, the order can still be honoured by claiming a fresh unit.

Data Model#

CREATE TABLE inventory_ledger (            -- what the merchant really has
  sku_id   BIGINT PRIMARY KEY,
  on_hand  INT NOT NULL CHECK (on_hand >= 0),   -- physical units not yet sold
  sold     INT NOT NULL DEFAULT 0
);
 
CREATE TABLE reservation_units (           -- bounded pool of reservable units
  sku_id   BIGINT NOT NULL,
  id       BIGINT NOT NULL,
  PRIMARY KEY (sku_id, id)                 -- lookup and lock by sku without a secondary index
);
 
CREATE TABLE holds (
  id          BIGINT PRIMARY KEY,
  sku_id      BIGINT NOT NULL,
  user_id     BIGINT NOT NULL,
  sale_id     BIGINT NOT NULL,
  qty         INT NOT NULL,
  price_cents INT,                         -- sale price locked at reservation time
  expires_at  TIMESTAMPTZ NOT NULL,
  status      TEXT NOT NULL,               -- ACTIVE | CLAIMED | RELEASED | EXPIRED
  idem_key    TEXT NOT NULL,
  UNIQUE (user_id, idem_key)
);
CREATE INDEX holds_active ON holds (sku_id, expires_at) WHERE status = 'ACTIVE';
CREATE UNIQUE INDEX one_active_hold_per_user
  ON holds (sale_id, user_id) WHERE status IN ('ACTIVE', 'CLAIMED');   -- per-user limit of 1

Design notes.

  • The ledger and the holds live in the same database. Reserve, claim and release each commit in one transaction with the ledger. That one property removes a whole family of failure modes (Deep Dive 5).
  • The pool table is a set of claimable tickets, not a copy of the ledger. Its size is capped (for example 1,000 rows per SKU) and refilled from the ledger, so it stays small even for products with huge stock (Deep Dive 1).
  • The primary key starts with sku_id. A query that locks "any free unit of SKU 42" walks the clustered index directly. In InnoDB that means one lock per row instead of two (secondary index entry plus clustered row).
  • Available units at any moment are on_hand − (sum of qty in ACTIVE holds whose expires_at is in the future). Expired holds stop counting the instant their deadline passes, with no job needed for correctness (Deep Dive 2).
  • The per-user limit is a partial unique index, so the database itself refuses a second active hold for the same user in the same sale, even if the Redis pre-check is bypassed or stale.

Database choice. A relational database (PostgreSQL or MySQL 8+) gives us transactions spanning ledger, pool, holds and orders; row locks with SKIP LOCKED; constraints; and decades of operational experience (see PostgreSQL in Practice and Concurrency Control and Database Locking). The flash-sale inventory is tiny (thousands of rows), so a single well-provisioned primary, with a synchronous standby, can host it. Sharding is unnecessary for size. Contention is the enemy, and the schema design solves it. For the general trade-offs, see Choosing a Database: A Decision Guide.

DataStoreWhy
Ledger, pool, holds, ordersPostgreSQL or MySQL 8 (primary plus sync standby)Atomic transactions across all of them, SKIP LOCKED, constraints
Status flags, per-user limit pre-checks, rate limitsRedisMicrosecond reads, cheap rejections, TTLs
Waiting room positionsRedis sorted sets or a dedicated queue serviceRank lookups, high write rate at the start
Product pages and imagesObject storage plus CDNStatic, read by millions
EventsKafka (via an outbox)Fan-out to status, refill, fulfilment, analytics
Purchase history for best sellersObject storage logs plus a warehouse, or a stream processorHourly aggregation over billions of rows
Best-seller listsSQL table plus cacheSmall, read-heavy, precomputed

Deep Dives#

1. How do we keep inventory consistent under extreme contention?#

The goal is zero oversell: across all concurrent requests, the number of units handed out never exceeds the stock. The difficulty is that every request targets the same SKU, and therefore the same data.

Bad: check, then decrement, in application code

available = SELECT available FROM inventory WHERE sku_id = 42
if available > 0:
    UPDATE inventory SET available = available - 1 WHERE sku_id = 42

Two requests read available = 1 at the same instant. Both see stock, both decrement, and the counter reaches −1: one unit sold twice. The read and the write must be one atomic step, and under contention this race is certain, not merely possible.

Bad: a distributed lock around the SKU

Take a Redis lock on sku:42, then read and decrement. It is correct if the lock is correct, but it:

  • serialises all buyers of the SKU through a network round trip to the lock service plus the database work, which gives an even lower ceiling than a row lock;
  • adds the failure modes of distributed locks: expiry while the holder is paused, and the need for fencing (see Distributed Locks).

The database already has a better lock: its own row lock.

Good: a conditional decrement on one counter row

UPDATE inventory SET available = available - 1
WHERE sku_id = 42 AND available >= 1;      -- the WHERE clause is the guard

The row lock serialises the updates, and the guard makes the last unit go to exactly one transaction. Others update zero rows and get SOLD_OUT. Simple and correct.

The limit is the single hot row. Every reservation for SKU 42 queues on that row's lock. If each transaction holds it for ~2 ms (decrement, insert hold, commit with a synchronous replica), the SKU tops out at ~500 reservations per second. Thousands of admitted requests then pile up as lock waiters, connections are exhausted, and latency explodes. Shopify reported exactly this failure in an early MySQL attempt: thousands of checkouts for one item collapsed onto one row lock, and processing slowed to a crawl.

For 10,000 units sold over ~20 seconds at a controlled admission rate, ~500 per second may be enough. That is why the waiting room plus a single counter row is a legitimate design. It fails when admission is high, or when TTL churn creates a steady stream of re-reservations.

Good: an atomic counter in Redis

-- KEYS[1] = stock:42, KEYS[2] = holds:42 ; ARGV = holdId, expiresAt
if tonumber(redis.call('GET', KEYS[1])) >= 1 then
  redis.call('DECR', KEYS[1])
  redis.call('ZADD', KEYS[2], ARGV[2], ARGV[1])   -- remember the hold and its deadline
  return 1
end
return 0

Redis runs scripts one at a time, so this check-and-decrement is atomic, and a single Redis shard does ~100,000 such operations per second. That is 200 times the hot-row ceiling. Many flash-sale designs stop here.

The catch is that Redis is not the ledger. When payment succeeds, the permanent sold count must change in the order database, and the Redis hold must be cleared. That is two writes in two systems, with no shared transaction. A crash between them leaves the two disagreeing, which means either hidden stock or an oversell. Deep Dive 5 walks through it. The Redis counter is a fine choice if you accept reconciliation, or treat Redis as the authoritative inventory and make the order database follow it.

Great: one row per reservable unit, claimed with SKIP LOCKED

Replace the single counter with many rows, one per unit that can currently be reserved. A buyer claims any free row:

BEGIN;
SELECT id FROM reservation_units
WHERE  sku_id = 42
LIMIT  1
FOR UPDATE SKIP LOCKED;           -- skip rows other transactions have locked
DELETE FROM reservation_units WHERE sku_id = 42 AND id = $picked;
INSERT INTO holds (...) VALUES (..., now() + interval '10 minutes', 'ACTIVE');
COMMIT;

An ordinary FOR UPDATE waits when it reaches a row another transaction has locked. SKIP LOCKED skips it and takes the next one. Two hundred concurrent buyers therefore lock two hundred different rows and commit in parallel. There is no single hot row. Throughput scales with the database's general write capacity (thousands of transactions per second) rather than one row's lock rate. If the query returns no rows, the pool is empty: either sold out, or the pool needs refilling (Deep Dive 5).

This is the "one row per seat" idea from the ticket-booking problem, applied to identical items. PostgreSQL has supported SKIP LOCKED since 9.5, and MySQL since 8.0. It is also the standard way to build job queues on a relational database.

Great: split the counter into buckets

Keep counters, but split each SKU's stock across N rows (buckets). For example, 1,000 units become 20 buckets of 50. A reservation picks a random bucket and does the conditional decrement there. If that bucket is empty, it tries others.

  • Contention per bucket falls by roughly N, so throughput rises by roughly N.
  • The tail problem: as stock runs out, most buckets are empty, and requests probe several before finding stock, or fail falsely while units remain in another bucket. Fix it by scanning buckets in order when a random pick fails, by periodically rebalancing buckets, or by merging them when the total runs low.
  • This is the classic sharded counter technique, used for hot counters well beyond inventory.

Great: pre-issued tokens

Before the sale, put 10,000 unit tokens into a queue, such as a Redis list or a database table of tokens. Reserving means popping one token (LPOP, or DELETE ... RETURNING with SKIP LOCKED). Each pop is atomic and unique. An empty queue means sold out. Releasing pushes a token back. It is conceptually the same as the unit pool, and works well when units are few and known in advance.

Comparison

ApproachOversell-safeThroughput per SKUAtomic with ledgerComplexity
Check then writeNoHigh (but wrong)NoTrivial
Distributed lockYes, with fencingLowNoMedium
Conditional decrement, one rowYes~hundreds per secondYesLow
Redis atomic scriptYes, within Redis~100k per secondNo (separate store)Medium
Unit pool with SKIP LOCKEDYes~thousands per secondYesMedium
Bucketed countersYes~N times one rowYesMedium
Pre-issued tokensYesHighDepends on storeLow to medium

Our choice: the unit pool in the ledger database, behind a waiting room. It is correct by construction, it has no cross-store window, and it is fast enough with an order of magnitude to spare.

2. How do we release expired reservations efficiently?#

A reservation ends in one of three ways:

  • Paid: the hold is claimed and the ledger is permanently decremented.
  • Explicit failure or abandonment: payment declined, or the user clicks "cancel". The release is triggered by that event.
  • Silent expiry: the user closes the laptop, loses signal or simply walks away. No signal arrives at all. The hold must die on its own when its deadline passes.

The third case is the interesting one. Whatever releases the unit cannot be the user's browser, or the server that handled the original request, because both may be gone. The deadline must live in the data, and something still running must act on it, or better, nothing needs to act at all.

Bad: rely on the client to release

A "release on page unload" call is a nice optimisation, but it is never reliable. Browsers kill pages, networks drop, and phones sleep. On its own, it leaves units stranded.

Good: a periodic sweeper

A job runs every N seconds:

UPDATE holds SET status = 'EXPIRED'
WHERE  status = 'ACTIVE' AND expires_at <= now()
RETURNING sku_id, qty;          -- then return each unit to the pool
  • It works, and it is simple. The partial index on (sku_id, expires_at) WHERE status = 'ACTIVE' keeps it cheap.
  • Latency equals the sweep interval. With a 30-second sweep, a hot item can read "sold out" for up to 30 seconds while abandoned units wait to return. In a flash sale, that is exactly when buyers who would have paid give up.
  • The sweeper is now on the correctness path for availability. If it stalls, the sale looks sold out.

Good: TTL keys in Redis, and why they are subtle

Redis can delete a key automatically after a TTL, which sounds like a perfect expiring hold. It is perfect when the key is the resource: a lock on seat 37A is SET seat:37A user NX EX 600. When the key disappears, the seat is free, and nothing else needs updating. That is why the ticket-booking problem uses it.

Flash-sale inventory is different. Nobody reserves "hoodie number 37". They reserve one of 500 identical hoodies. Availability is a count across all live holds:

  • Per-hold keys with TTLs make counting expensive. Redis has no index over hold:* keys, and scanning the keyspace on every reservation is far too slow.
  • One counter per SKU makes counting cheap, but a TTL on the counter would delete the whole counter, not one buyer's hold. A hold's expiry must instead trigger a write somewhere else: increment the counter. Redis expiry runs no side effects. It just deletes the key, and with it, the only record that the hold existed.
  • Keyspace notifications publish an "expired" event that a worker can turn into an increment. But they are fire-and-forget pub/sub. If the worker is disconnected when the event fires, or crashes after reading it, the event is lost, and the unit is stranded for good.

Great: a sorted set of deadlines, reclaimed atomically

Keep each hold in a sorted set scored by its deadline (ZADD holds:42 <expiresAt> <holdId>). "What has expired?" becomes ZRANGEBYSCORE holds:42 -inf <now>. Workers pop due holds and, in one atomic script, remove each one and increment the counter. No hold can be reclaimed twice, and nothing is lost if a worker dies: the hold stays in the set until it is handled.

Better still, make every reserve reclaim first. The reserve script peeks at the head of the set, reclaims a few past-due holds, and only then decides whether a unit is free:

-- run atomically on every reserve for SKU 42
due = ZRANGEBYSCORE holds:42 -inf now LIMIT 0 10    -- at most 10 past-due holds
for each h in due: ZREM holds:42 h ; INCRBY stock:42 qty(h)
if GET stock:42 < 1 then return SOLD_OUT
DECR stock:42
ZADD holds:42 now+600 newHold
  • Demand itself drives the cleanup: the hotter the item, the faster expired units return.
  • Cap the batch (10 here). Redis blocks every other command while a script runs, so reclaiming an unbounded backlog inline would stall all buyers.
  • Items whose traffic dies down never get another reserve to clean them, so keep background sweepers for the long tail.

Great: implicit expiry, where nothing has to fire

In the relational design, define availability with the deadline in the query:

-- units currently held, as seen by anyone computing availability
SELECT coalesce(sum(qty), 0) FROM holds
WHERE  sku_id = 42 AND status = 'ACTIVE' AND expires_at > now();

A hold stops counting the instant its deadline passes. No job, timer or event is needed for correctness. In the unit-pool design, the refill process computes how many units the pool should contain: on_hand − units in unexpired holds − units already in the pool. When a hold expires, the next refill (background or inline) automatically restores its capacity.

  • What required a keyspace scan in Redis is an indexed range query here.
  • A cleanup job is still useful, as garbage collection: it marks expired holds EXPIRED, so tables don't bloat and other queries that forget the expires_at filter don't see stale "reserved" rows. If it runs late, nothing breaks and no sale is lost.
  • To be clear, no lock is held for the 10-minute window. The hold is just a row with a deadline. Locks exist only inside the millisecond-long transactions that create, claim or release it.

The same principle appears in the ticket-booking and auction problems: put the deadline in the data and check it at the decision point, so that background jobs only tidy up.

3. How do we handle millions of users arriving at once?#

Assume 6 million active users at 12:00:00, each pressing "Buy". The danger is not the inventory database alone. Every layer in front of it (load balancers, gateways, app servers, connection pools) can collapse under a sudden 100-fold spike. The strategy has four layers: absorb at the edge, queue, admit at a controlled rate, and shed what is left.

1. Absorb at the edge.

  • Serve the product page, images and JavaScript from the CDN, pushed in advance. Serve per-SKU status as a 1-second cacheable JSON document.
  • When the sale sells out, flip a flag that the edge itself evaluates (edge configuration or an edge function), so "sold out" is answered by the CDN without touching origin.
  • Filter obvious bots at the edge: missing or invalid challenge tokens, abusive IPs, known automation signatures.

2. Queue in a virtual waiting room.

  • From a few minutes before the start, all sale traffic is redirected to a waiting room: a lightweight page that holds a queue ticket (a signed cookie or token with the user's position).
  • The waiting room is itself built for scale. Positions live in a horizontally sharded store, and clients learn their status via cheap polling (every 5 to 15 seconds, with jitter) or SSE.
  • Products exist for this: CDN vendors and specialist providers offer hosted waiting rooms (for example Cloudflare Waiting Room and Queue-it). Building one is also feasible, because the core is simple.

3. Admit at a controlled rate. The admission controller releases users from the head of the queue at a rate R, set to what the purchase path can absorb with headroom.

  • Each admitted user receives a short-lived signed admission token (for example a JWT with saleId, userId and an expiry 5 minutes ahead). The gateway checks the token's signature locally, so it costs no database call.
  • Choosing R with Little's law: the number of users concurrently inside the purchase flow is L = R × W, where W is the time a user spends in it. With R = 2,000 users per second, and W = 3 seconds to reserve plus ~120 seconds to pay, about 250,000 users are mid-checkout at peak. The inventory tier only sees the reserve step: 2,000 per second, well within the unit-pool design's capacity.
  • Adaptive admission: R can be driven by feedback from the purchase path: p99 latency, error rate and database CPU. Admission slows when the path is stressed, and speeds up when it is healthy. That is backpressure, not just a static limit.
  • Stop when it is pointless: when stock is fully reserved, admission pauses, and waiting users see "all units are currently reserved; some may come back". As holds expire and units return, admission resumes, in queue order.

4. Shed load gracefully.

  • Per-user, per-device and per-IP rate limits at the gateway (see Rate Limiting and Throttling). A user gets one reserve attempt per second, say.
  • Requests without a valid admission token are rejected at the gateway with a redirect back to the waiting room.
  • Load shedding by priority: under overload, serve reserve attempts from admitted users first, and status polls last. Viewing degrades to stale cached pages, never to errors.

Design the client too. The browser or app is part of the load profile, and it is the one part you fully control:

  • Disable the Buy button after one press, until the response arrives. Show progress, so users don't mash it.
  • Retries with exponential backoff and jitter. A client that retries every 100 ms forever turns one user into ten requests per second. Cap the retries, and honour Retry-After.
  • Stay in the page. Make the waiting room an in-page state, with polling or SSE, not a page users feel they must refresh. "Do not refresh; you will keep your place" is both true (the ticket is in a cookie) and load-reducing.
  • Pre-fetch everything the purchase needs (scripts, payment widget) before 12:00, so the critical moment costs only the API calls.

Pre-scaling. Auto-scaling reacts in minutes. A flash sale's spike arrives in seconds. Scale up before the sale: app servers, gateways, Redis and connection poolers sized for the peak, and the database's buffer pool warmed. Load-test at the expected peak beforehand (see Capacity Planning and Load Testing).

4. How do we make access to limited inventory fair?#

"Fair" is a product decision, and the system has to implement whichever definition the business chooses.

First come, first served (FCFS) at the moment of reservation sounds fair, but in practice it rewards network latency and automation. Someone near the data centre, or a bot sending 100 requests per second, beats a person on a phone. Strict FCFS over the open internet mostly measures who has the best bot.

Randomised queue at the start. Everyone who arrives before 12:00 enters the waiting room with no position. At 12:00 the system shuffles them and assigns random positions. Arriving at 11:55 or at 11:59:59 makes no difference. Users who arrive later join the end in arrival order. This removes the incentive to hammer the site early, and blunts fast bots. It is a common design for high-demand ticket and product drops.

Lottery or draw. For extreme demand, skip the race entirely. Users enter a draw during a window (say 30 minutes). At the end, the system randomly selects winners, each of whom gets an exclusive reservation and a payment window. Sneaker releases often use draws, for example via brand apps. Technically this is the gentlest design: entries are simple idempotent inserts spread over the window, and the selection is a batch job. The cost is the "excitement" of a live race, and a delay before buyers know the result.

Limits per buyer. One or two units per account, enforced in the database (the partial unique index on active holds). Since one person can create many accounts, also tie limits to payment instruments, shipping addresses and devices, and check them at checkout as well as at reservation.

Bot and scalper defences (see Security Fundamentals for System Design):

  • Challenges (CAPTCHA, or invisible proof-of-work challenges) at queue entry rather than at checkout, so that the cost lands on mass automation before scarce inventory is involved.
  • Account requirements: a verified phone number, account age, or prior purchase history to enter high-demand sales.
  • Device and behaviour signals: fingerprints, request timing and headless-browser markers, used to score requests. Suspicious ones get extra challenges rather than outright blocks, to limit false positives.
  • Post-sale review: cancel orders that share addresses or cards across many accounts, and release the units in a second-chance sale.

Transparency is part of fairness. Show users their queue position, an honest estimated wait, and a clear message when stock is gone. A queue that says "sold out" quickly is fairer than one that keeps people waiting for nothing.

5. What can we learn from Shopify's inventory reservations?#

Shopify processes a large share of US e-commerce. Every checkout for inventory-tracked items is protected by a reservation: when a buyer starts paying, the items are held for a few minutes. On successful payment, they are permanently deducted from the merchant's inventory. In a 2026 engineering post, Shopify described moving those reservations from Redis into MySQL. The reasoning maps directly onto this problem.

The original design: counters in Redis, ledger in MySQL.

  • Reservations were a Redis counter per item. Redis executes commands one at a time, so two buyers could never both reserve the last unit. As a concurrency mechanism, it worked.
  • The merchant's inventory ledger lived in MySQL. On successful payment, two things had to happen: deduct units in MySQL, and clear the reservation in Redis. These were two writes in two databases, with no transaction spanning them.
  • Crash between them, MySQL first: the sale is recorded, but Redis still counts the units as reserved. Inventory that is really available is hidden, and the merchant loses sales.
  • Crash between them, Redis first: the reservation is cleared, but MySQL never deducted the units. They look available although they are sold. That is an oversell.
  • Reordering the writes only chooses which failure you get. It does not close the window.

Why the usual fixes didn't help.

  • Two-phase commit needs both stores to take part in one coordination protocol (for example XA). Redis doesn't support it (see Distributed Transactions: 2PC, Sagas and Outbox).
  • An outbox or reconciliation job eventually detects and repairs mismatches, but inventory is wrong until then. In the middle of a flash sale, even briefly wrong can mean selling a unit twice.
  • The real requirement was that reserve and claim commit atomically with the ledger. Only rows in the same database as the ledger can deliver that.

First MySQL attempt: one row per item with a quantity. UPDATE ... SET available = available - 1 WHERE available >= 1 is correct, but every checkout for a hot item takes the same row lock in InnoDB. Under a flash sale, thousands of checkouts lined up behind one lock, and throughput collapsed. This is the hot-row problem from Deep Dive 1.

The design that worked: a bounded pool of unit rows, claimed with SKIP LOCKED.

  • A reservation_units table holds one row per currently reservable unit. Reserving three items selects and locks three rows with FOR UPDATE SKIP LOCKED, removes them from the pool, and inserts one hold row, in one transaction.
  • SKIP LOCKED (available in MySQL since 8.0) lets concurrent buyers lock different rows and commit in parallel, instead of queueing on one.
  • Bounded: one row per unit of a merchant's entire stock would mean hundreds of thousands of mostly idle rows per item, across millions of items, with slower scans as tables grow. So the pool is capped (Shopify cited 1,000 rows per item), and a replenishment process tops it up from the ledger when it runs low.
  • Inline refill: a rush can drain the pool faster than background replenishment refills it. The reservation request then refills the pool itself and retries. A lock ensures only one transaction refills at a time, so capacity isn't added twice. That request is slower, but a buyer is never rejected while the ledger still has stock merely because the pool lagged. The post did not give the latency of this fallback, or explain how orders larger than the pool are handled. Those are open questions to think through in your own design.

Making InnoDB's locks behave. Three details mattered in production:

  1. Clustered primary key. InnoDB stores rows in primary-key order. A locking query through a secondary index locks both the index entry and the clustered row. Making the query's columns the leading part of the primary key, PRIMARY KEY (shop_id, inventory_item_id, inventory_group_id, id), lets the scan lock table rows directly. One lock per unit instead of two, which halves lock traffic on the hottest path.
  2. Gap locks on an empty pool. Under REPEATABLE READ, MySQL's default, a locking scan also locks the gaps between index records, to prevent phantom inserts. With an empty pool, there are no rows to lock, so the scan locks the gap at the end of the index, exactly where replenishment needs to insert. Reservations and refills then blocked or deadlocked each other. The fix was to run these transactions under READ COMMITTED, where such scans don't take those gap locks. Shopify said it was the first time they used a non-default isolation level anywhere in their codebase.
  3. Lock ordering. Different code paths touched the two tables in different orders, a classic recipe for deadlock. The fix was to make every path lock in the same order: remove pool rows first, then insert the hold.

The outcome. Shopify reported that the rebuilt system handled Black Friday 2025, with merchant sales peaking at a record of about $5.1 million per minute.

Expiry, in each design. The post focused on reserve and claim. Expiry follows from the design (Deep Dive 2):

  • With Redis counters, expiry needs a sorted set of deadlines plus an atomic reclaim script, or holds leak.
  • With holds in MySQL, a hold carries expires_at. Replenishment computes the pool's target as roughly "ledger minus units in unexpired holds". So an expired hold stops counting as soon as its deadline passes, and the next refill restores capacity. Cleanup becomes garbage collection.

Lessons to carry into any design:

  • If a hold and the record it guards must commit together, put them in the same database. If they don't need to, a Redis counter remains the simpler tool, and nothing here argues against it.
  • Re-check old conclusions against new database features. "MySQL can't do this" was true before SKIP LOCKED existed, and false afterwards.
  • Contention is a schema problem as much as an infrastructure one. Spreading one hot row over a pool of rows fixed what more hardware could not.
  • Every component has an operational cost. Replenishment is a new process to monitor and page on, and its natural failure mode is an empty pool in the middle of a flash sale. The trade was worth it because the new moving part sits inside the transaction boundary that matters.

6. How does the cart and checkout flow fit in?#

Outside a flash sale, most shops do not reserve inventory when you add to cart. Carts are long-lived, and most are abandoned. Reserving on add-to-cart would lock up stock for hours, for buyers who never return. The usual flow:

  1. Cart: a list of (sku, qty) per user (or per anonymous session), stored in a key-value store or in the database. It holds no inventory. It shows availability as a hint ("only 3 left").
  2. Begin checkout: the user enters an address and selects shipping. The system calculates taxes and shipping costs, and revalidates prices, because prices can change while an item sits in a cart.
  3. Reserve at payment time: when the user presses "Pay", the system reserves every line item in one transaction (all-or-nothing). If any item is out of stock, the user is told before being charged.
  4. Authorise payment, then claim: as in Flow 2.
  5. Order created: confirmation, then fulfilment.

In a flash sale, the reservation moves earlier. Pressing "Buy" reserves immediately, before the address and payment steps, because the scarce item would otherwise be gone by the time the user finishes typing their card. The hold timer (10 minutes) then bounds the checkout.

Price integrity. The flash-sale price is stored on the hold at reservation time, along with the sale id. Checkout charges the hold's price, not whatever the catalogue shows at payment time. A user who reserved at $120 pays $120, even if the sale ends or the price changes during their checkout. Conversely, a client that tampers with the price in its request changes nothing, because the server never trusts a client-supplied amount.

Multi-item carts with a flash-sale item and normal items: reserve the flash-sale unit at "Buy". Reserve the other items at payment time, together, in one transaction. If a normal item is out of stock, the user can still buy the flash-sale item.

Lock ordering for multi-item reservations: always lock SKUs in a consistent order (for example by ascending SKU id). Two carts containing the same items in different orders then cannot deadlock. That is exactly Shopify's third lesson.

Checkout as a saga. Checkout spans several services: inventory, payment, orders, tax, fraud and notifications. A single distributed transaction across them is neither practical nor desirable. Model it as a saga with compensating steps (see Pattern: Multi-Step Processes and Workflows):

  • reserve inventory, compensated by release;
  • authorise payment, compensated by void;
  • create the order, compensated by cancel;
  • capture payment at shipment, compensated by refund.

A workflow engine (Temporal, or a step-function service) or an event-driven choreography both work. What matters is that every step is idempotent and every failure has a defined compensation (see Temporal and Workflow Engines).

7. How do we integrate payment safely?#

Payment is where money moves, so it is where retries and timeouts do real damage. Principles (see the payment-system problem for the full design):

Tokenise cards on the client. The provider's client library (or hosted fields) turns card details into a token. Our servers only ever see the token, which keeps them out of most PCI DSS scope (the card industry's security standard).

Idempotency end to end.

  • The client sends an Idempotency-Key with checkout. The Checkout Service stores it with the order.
  • The call to the payment provider uses the order id as its idempotency key. If our service crashes after sending the request and retries, the provider returns the original result, not a second charge.
  • Webhook handlers are idempotent too: a "payment succeeded" event processed twice must not claim the hold twice. A conditional update WHERE status = 'ACTIVE' on the hold, plus a processed-events table, handles it.

Authorise, then capture. For physical goods, authorise at checkout (the bank reserves the money on the card) and capture when the item ships. If fulfilment fails (the warehouse can't find the unit), void the authorisation, so nothing is charged. For digital goods, capture immediately.

Unknown outcomes. A payment request that times out has an unknown result. Never assume failure and release the unit, because the money may already be authorised. Instead:

  1. keep the hold ACTIVE, extending it briefly if needed;
  2. query the provider using the idempotency key, or wait for the webhook;
  3. decide only when the outcome is known.

A reconciliation job compares our orders with the provider's settlement reports daily, and flags any mismatch: charged but no order, or an order but no charge.

TTL versus payment time. A 10-minute hold with a payment that can take 1 to 60 seconds (3-D Secure challenges, wallet pop-ups) is safe, if checkout starts early enough. Two policies prevent edge cases:

  • Extend on payment start: when the user submits payment, extend the hold by, say, 2 minutes. Extend only once, so a hold cannot be stretched indefinitely.
  • Claim checks the hold, not the clock: the claim transaction succeeds only if the hold is still ACTIVE and unexpired. If it has expired and the unit was resold, void the authorisation and apologise. If stock remains, claim a fresh unit.

Fraud checks run between authorisation and capture, or before authorisation for risky orders, using the provider's risk scores and our own signals: account age, address mismatch, velocity. Flash sales attract card testing and reseller fraud, so tighten thresholds during them.

8. What happens when one SKU is far hotter than the rest?#

A shoe drop has 10 sizes, but sizes 9 to 10.5 may draw 60 percent of demand. Hot-SKU contention has three layers.

Row level. Solved by the unit pool or bucketed counters (Deep Dive 1). Each hot SKU has its own pool. A pool of 1,000 rows serves hundreds of concurrent claimers with little skipping.

Shard level. If inventory were sharded by SKU across a big e-commerce database, the flash-sale SKUs would land on one or two shards, which would melt while the others idled. Options:

  • Isolate flash-sale inventory on a dedicated database cluster, provisioned for the event. The rest of the shop runs undisturbed, and the flash sale's failure cannot take down normal checkout (a bulkhead).
  • Split a SKU's stock across shards: 10,000 units become four allocations of 2,500 on four shards, and requests are spread by user-id hash. This scales almost without limit. The cost is the tail problem again: one shard sells out while others have stock, so route "sold out on my shard" requests to another shard before saying sold out, and rebalance near the end.

System level. Every layer must be sized for the hottest SKU's traffic, not the average: the cache keys for its status, its admission rate, and the Kafka partition for its events. Use per-SKU admission rates, so that a hot size's queue doesn't block buyers of a quiet size, and per-SKU status keys, replicated or cached in-process to avoid one hot Redis key (see Cache Failure Modes: Stampedes, Hot Keys and Penetration).

Allocation by channel or region. Many brands split a drop: 6,000 units online, 4,000 in stores; or 5,000 in the US and 5,000 in the EU. Each allocation is its own inventory pool. That also bounds the blast radius: an issue in one region doesn't sell another region's stock. Unsold units can be moved between pools near the end, using a transactional transfer between ledgers.

9. How do we show stock levels and "sold out" without a stampede?#

Users want to see "Available", "Only a few left" or "Sold out". Showing the exact live count to 10 million viewers is neither needed nor wise. It costs a lot, and it shows bots precisely when to strike.

Coarse, cached, pushed.

  • Publish status bands rather than counts: AVAILABLE above 10 percent of stock, LOW below it, SOLD_OUT at zero, and possibly "ALL RESERVED" when the pool is empty but holds may expire.
  • The Reservation Service updates the band in Redis when it changes (an event, not every reservation). The CDN caches the status JSON for ~1 second.
  • Clients in the waiting room or on the page can receive band changes via SSE (see Pattern: Pushing Realtime Updates), or poll the cached endpoint every few seconds with jitter.

Push capacity. If 4 million waiting users hold SSE connections, that is 4 million open connections. At ~50,000 to 100,000 per gateway node, that means 40 to 80 nodes for a few minutes. Polling a CDN-cached status every 10 seconds costs ~400,000 requests per second, almost all served at the edge. For a one-off event, polling the edge is often cheaper and simpler than push. Reserve SSE for users who are already admitted or hold a reservation.

Sold out is a state transition, not an error. When the last unit is reserved:

  1. set SOLD_OUT, or ALL_RESERVED, in the status cache;
  2. tell the admission controller to pause admission;
  3. flip the edge flag, so the CDN answers reserve attempts with "sold out" directly.

Within ~1 to 2 seconds, millions of requests stop reaching origin. Without this, every disappointed user retries, and the retry storm after sell-out can exceed the initial spike.

Coming back. If expired holds return units, the status moves to AVAILABLE again, and admission resumes from the queue's head. Waiting-room users get priority over new arrivals. Otherwise a refresh-happy bot snaps up returned units first.

Don't let caches lie for long. A cached SOLD_OUT that stays after units return means lost sales. A cached AVAILABLE after sell-out means wasted requests (harmless, because the reservation path is authoritative). Asymmetric TTLs help: short for SOLD_OUT, so returns are noticed quickly, and versioned updates so an older status never overwrites a newer one (see Cache Eviction and Invalidation).

10. What happens after payment: orders and fulfilment?#

Once the claim transaction commits (hold CLAIMED, ledger decremented, order PAID), the rest is asynchronous and retryable:

  • The outbox row written in the claim transaction is relayed to Kafka as OrderPaid (see Change Data Capture and the Outbox Pattern).
  • Consumers:
    • a confirmation email and push notification;
    • fulfilment, which allocates the order to a warehouse, creates a pick list and later records shipment (triggering payment capture);
    • analytics, including the best-sellers pipeline (Deep Dive 11);
    • fraud review for flagged orders.
  • Each consumer is idempotent, keyed by order id, so redelivery is harmless (see Asynchronous Processing and Message Queues).

Why asynchronous? At 12:00:05 the claim path must stay fast. Sending email, talking to the warehouse system and updating analytics synchronously would add hundreds of milliseconds, and new failure points, to every purchase. With a queue, a warehouse outage delays shipping notices, not sales.

Physical reality. The ledger's on_hand should reflect what is really in the warehouse. Before a sale, reconcile it with a stock count. Keep a small safety buffer (for example 0.5 to 1 percent of units held back) to absorb miscounts and damaged items. Release the buffer near the end of the sale, after the warehouse confirms. Overselling because the ledger was wrong is still overselling.

11. How do we compute "best sellers this week, by category"?#

Flash sales sit inside a larger shop. A classic companion feature is a sales rank: for each category, the most popular products over the past week, refreshed at least hourly. The numbers from the capacity section apply: 10 million products, 1,000 categories, ~1 billion purchases per month (~400 per second), ~40,000 reads per second of the rankings, and a product can belong to several categories.

The data. Each purchase emits a small record: timestamp, product_id, category_id, quantity, total_price, seller_id, buyer_id, ~40 bytes. A product in three categories produces three category rows (or one record with a category list, expanded later). These records come from the OrderPaid events, or from sales service logs written to object storage (such as Amazon S3), at ~40 GB per month.

Batch approach: a two-stage MapReduce job every hour.

  1. Stage 1: aggregate. The mapper reads each purchase from the last 7 days, and emits ((category, product), quantity). The reducer sums quantities per key: ((category, product), total).
  2. Stage 2: sort. A second mapper re-keys each result as ((category, total), product). The framework's shuffle phase then performs a distributed sort by category and total. The reducer passes records through, and we take the top N per category.

A tiny worked example. Purchases: (cat1, p1, 2), (cat2, p1, 2), (cat2, p1, 1), (cat1, p2, 3), (cat2, p3, 7), (cat1, p4, 1).

  • Stage 1 gives (cat1, p1) = 2, (cat2, p1) = 3, (cat1, p2) = 3, (cat2, p3) = 7, (cat1, p4) = 1.
  • Stage 2 sorts them: cat1 → p2 (3), p1 (2), p4 (1); cat2 → p3 (7), p1 (3).

In modern stacks, this is a short Spark job or a SQL query in a warehouse (BigQuery, Redshift, Snowflake), rather than hand-written MapReduce:

-- hourly: top 100 per category over the past 7 days
INSERT OVERWRITE sales_rank
SELECT category_id, product_id, units, rnk FROM (
  SELECT category_id, product_id, sum(quantity) AS units,
         row_number() OVER (PARTITION BY category_id ORDER BY sum(quantity) DESC) AS rnk
  FROM purchases
  WHERE created_at >= now() - interval '7 days'
  GROUP BY category_id, product_id) t
WHERE rnk <= 100;

Cost: 7 days of purchases is ~230 million rows, or ~10 GB. A warehouse scans that in seconds to minutes, so hourly runs are cheap. Partition the purchases table by day, so each run reads only 7 or 8 partitions.

Streaming approach for fresher rankings. If popular categories need minute-level freshness, a stream processor (Flink, Kafka Streams) keeps sliding-window counts per (category, product): for example, a 7-day window advancing every 5 minutes, built from hourly sub-aggregates. It emits a top-N per category after each step. To avoid holding exact counts for 10 million products × several categories, keep exact counts only for products with recent sales (most products sell rarely), or use a heavy-hitters sketch, such as Count-Min Sketch plus a heap. That trades a little accuracy for bounded memory (see the top-k problem).

Storing and serving the result.

  • The sales_rank table holds (category_id, rank, product_id, units), with the primary key (category_id, rank). It is tiny: 1,000 categories × 100 ranks is 100,000 rows.
  • 40,000 reads per second (with uneven traffic toward popular categories) are served from a memory cache (Redis or memcached), or even from the CDN with an hourly TTL, because the lists change only when the job runs. Precompute and push the new lists when the job finishes (refresh-ahead), so readers never wait on a cold cache (see Caching Strategies: Cache-Aside, Read-Through, Write-Through, Write-Behind).
  • Raw purchase data older than needed for rankings moves from the OLTP database to the analytics warehouse or object storage. The OLTP database keeps only what checkout needs.

Edge cases:

  • Refunds and cancellations should subtract from counts. Emit negative quantities.
  • Flash sales distort rankings: 10,000 units sold in a minute can dominate a category for a week. Decide whether flash-sale purchases count, perhaps with a weight.
  • Manipulation: sellers buying their own products to climb the ranks. Count unique buyers, or weight by buyer trust.

12. How do we survive failures and serve a global audience?#

Single region of truth for each sale's inventory. A flash sale's ledger, pool and holds live in one primary database with a synchronous standby in another availability zone. A reservation acknowledged to a user is on two machines before the response leaves (see Database Replication). A multi-primary setup that accepted reservations in two regions independently could oversell, so don't.

Global users. Buyers far from the home region pay ~100 to 250 ms extra for the reserve call. That is acceptable, because it is one call. The waiting room, status and pages are served from the edge worldwide. For the randomised queue, distance stops mattering, which is another reason to prefer it. If the business splits stock by region (Deep Dive 8), each regional pool can live in its own region, with local latency for everyone.

Failure scenarios:

  • Primary database fails mid-sale. Failover to the synchronous standby takes ~10 to 60 seconds. Reservations fail during that window. Clients retry with idempotency keys, and the admission controller pauses automatically (backend health feedback). No acknowledged hold is lost. When service returns, admission resumes from where the queue was.
  • Redis fails. Status caching and pre-checks fall back to the database path, at a lower admission rate. Rate limiting degrades to in-memory per-node limits. Correctness is unaffected, because Redis holds no inventory truth in this design.
  • Kafka or the outbox relay stalls. Reservations and payments commit normally. Emails, fulfilment and status bands lag. Status bands can also be updated directly by the Reservation Service as a fallback.
  • Payment provider outage. Holds wait. Extend TTLs during a declared provider outage, so buyers aren't punished for an outage that wasn't theirs. A second provider, behind a routing layer, provides redundancy for large merchants.
  • Waiting room failure. Fail closed: if the waiting room cannot issue tokens, the purchase path admits nobody. The alternative, failing open, would send the full spike straight to inventory. Show a "please wait" page.

Rehearse. Run the sale end to end on staging with synthetic load at the expected peak, and inject failures during it (see Disaster Recovery and Backups). The first time a primary fails mid-sale should not be in production.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
Single inventory row per SKUAll reservations queue on one lock. Throughput caps at a few hundred per second, and connections pile up.Unit pool with SKIP LOCKED, bucketed counters, or a Redis counter. Waiting room to bound concurrency.
Spike of millions of requests at 12:00Gateways, app servers and connection pools collapse before inventory is even reachedCDN for pages, a waiting room, a rate-controlled admission controller with signed tokens, pre-scaling, edge rate limits
Hold and ledger in different storesA crash between the two writes hides stock or oversellsKeep holds and the ledger in one database and one transaction. Otherwise reconcile continuously, and accept the window.
Silent abandonmentUnits stuck in dead holds. The sale shows "sold out" while stock exists.Deadlines in the data (expires_at), availability that ignores expired holds, reclaim-on-reserve, background sweep for garbage collection
Reservation pool drained faster than refillFalse "sold out", or slow requestsInline refill under a lock, then retry. Alert on pool depth. Size the pool for peak concurrency.
Gap locks and deadlocks in MySQLReservations and refills block each other, or deadlockREAD COMMITTED for these transactions, primary key ordered by the query, consistent lock ordering across all paths
Retry storm after sell-outDisappointed users and bots retry, exceeding the initial spikeSold-out flag evaluated at the edge, admission paused, clear UI messaging, rate limits per user
Payment timeout with an unknown outcomeReleasing the unit could resell a paid unit. Charging twice angers the buyer.Idempotency keys with the provider, query-before-retry, hold extension during payment, daily reconciliation
Bots and multi-account scalpersReal buyers lose. The brand suffers.Randomised queue, challenges at queue entry, per-account, card and address limits, post-sale order review
Hot SKU among manyOne size's traffic overwhelms its pool, shard or cache keyPer-SKU pools and admission, flash-sale inventory isolated on its own cluster, split allocations across shards
Inventory database primary failureReservations fail for the failover windowSynchronous standby, automatic failover, idempotent retries, admission controller pauses on health signals
Ledger out of sync with the warehouseOverselling physical stock that doesn't existPre-sale stock count, a safety buffer, warehouse confirmation before releasing the buffer

What Interviewers Expect#

Mid-level.

  • Identifies the core flow: view, reserve with a time limit, pay. Explains why you can't hold a database transaction open during payment.
  • Prevents overselling with an atomic conditional update (WHERE available >= 1) rather than read-then-write.
  • Uses a CDN for the product page and caches status.
  • Releases expired reservations with a scheduled job, and knows its delay is a weakness.

Senior.

  • Recognises the hot-row problem and offers a real fix: unit rows with SKIP LOCKED, bucketed counters, or Redis with atomic scripts, with the trade-offs of each.
  • Designs a waiting room and admission control, sized with numbers (Little's law, admission rate versus inventory throughput).
  • Makes expiry correct by construction (deadline in the data, availability that ignores expired holds), with sweeps only for cleanup.
  • Handles payment idempotency, unknown outcomes, and TTL-versus-payment-time edge cases.
  • Short-circuits "sold out" at the edge to prevent retry storms.

Staff and above.

  • Explains why a separate reservation store (Redis) and ledger (SQL) creates an unclosable atomicity window, and why 2PC and outboxes don't fix it for this use case. Chooses deliberately: same-database transactions, or an accepted window with reconciliation.
  • Discusses database internals that decide success: SKIP LOCKED, clustered-index locking, gap locks under REPEATABLE READ, lock ordering.
  • Treats fairness as a product decision with system consequences: FCFS versus a randomised queue versus a draw, bot economics, multi-account limits.
  • Plans the operational side: pre-scaling, bulkheads isolating the sale from the rest of the shop, failure rehearsals, fail-closed admission, real-time dashboards.
  • Places the flash sale within the wider shop: carts that don't reserve, checkout as a saga, and analytics such as best-seller rankings.
Deep Dive: a reserve handler with SKIP LOCKED and inline refillShow

TypeScript-style pseudo-code for the Reservation Service's hot path. It follows the unit-pool design with implicit expiry.

async function reserve(saleId: bigint, skuId: bigint, userId: bigint, qty: number, key: string) {
  if (await statusCache.isSoldOut(skuId)) return { error: 'SOLD_OUT' };   // cheap rejection
  for (let attempt = 0; attempt < 2; attempt++) {
    const res = await db.tx({ isolation: 'READ COMMITTED' }, async t => {
      const prior = await t.oneOrNone(
        `SELECT id, expires_at FROM holds WHERE user_id=$1 AND idem_key=$2`, [userId, key]);
      if (prior) return { holdId: prior.id, expiresAt: prior.expires_at };  // safe retry
      const units = await t.many(
        `SELECT id FROM reservation_units WHERE sku_id=$1
         ORDER BY id LIMIT $2 FOR UPDATE SKIP LOCKED`, [skuId, qty]);
      if (units.length < qty) return null;                    // pool short: refill, then retry
      await t.none(`DELETE FROM reservation_units WHERE sku_id=$1 AND id = ANY($2)`,
        [skuId, units.map(u => u.id)]);                       // lock order: pool first
      return t.one(`INSERT INTO holds (id, sku_id, user_id, sale_id, qty, expires_at,
          status, idem_key) VALUES (gen_id(), $1, $2, $3, $4,
          now() + interval '10 minutes', 'ACTIVE', $5)
        RETURNING id AS "holdId", expires_at AS "expiresAt"`,  // then the hold
        [skuId, userId, saleId, qty, key]);                    // unique index enforces 1 per user
    });
    if (res) { await outbox.emit('HoldCreated', { skuId, qty }); return res; }
    const refilled = await refillPool(skuId);                 // one refiller at a time
    if (!refilled) { await statusCache.markSoldOut(skuId); return { error: 'SOLD_OUT' }; }
  }
  return { error: 'TRY_AGAIN' };
}

The refill computes how many units the pool may hold, under a lock on the ledger row, so that only one refill runs at a time per SKU:

async function refillPool(skuId: bigint): Promise<boolean> {
  return db.tx(async t => {
    await t.one(`SELECT 1 FROM inventory_ledger WHERE sku_id=$1 FOR UPDATE`, [skuId]); // refill lock
    const free = await t.one(`SELECT l.on_hand
        - (SELECT coalesce(sum(qty),0) FROM holds h WHERE h.sku_id=$1 AND h.status='ACTIVE'
           AND h.expires_at > now())
        - (SELECT count(*) FROM reservation_units r WHERE r.sku_id=$1) AS n
      FROM inventory_ledger l WHERE l.sku_id=$1`, [skuId]);
    const add = Math.min(free.n, 1000);                       // bounded pool
    if (add <= 0) return false;
    await t.none(`INSERT INTO reservation_units (sku_id, id)
        SELECT $1, nextval('unit_ids') FROM generate_series(1, $2)`, [skuId, add]);
    return true;
  });
}

Notes:

  • One transaction per reservation, lasting a few milliseconds. The 10-minute hold is a row, not a lock.
  • SKIP LOCKED with ORDER BY id spreads concurrent claimers across different rows. Each takes the first rows not already locked.
  • The refill is serialised by locking the ledger row. That row is touched only by refills and claims, never by every reservation, so it is not a hot spot in normal operation.
  • Expired holds are excluded from the refill computation by expires_at > now(). Expiry needs no timer.
  • In the real code, write the outbox row inside the transaction, not after it, as in the auction problem. It is shown outside here only to keep the snippet short.
Deep Dive: contention maths for the hot SKUShow

One counter row. A transaction holding the row lock for S = 2 ms gives a capacity of 1/S = 500 per second. With admission at λ = 400 per second, utilisation ρ = 0.8. In an M/M/1 model, the mean time in the system is S / (1 − ρ) = 10 ms. At λ = 480 per second, ρ = 0.96, and it is 50 ms. Variance is high, so p99 values reach hundreds of milliseconds, and connection pools fill. Near saturation, a single row is unpredictable, which is a bad property at the most important moment of the year.

Unit pool with SKIP LOCKED. Now C concurrent transactions each lock different rows. Throughput is bounded by the database's overall commit rate: on a modern primary with synchronous commit to a nearby standby, roughly 5,000 to 20,000 short transactions per second, depending on hardware and group commit. The pool needs at least C free rows at all times, so that claimers don't find everything locked. With 200 concurrent claimers and a 1,000-row pool, that is comfortable. As the pool falls below C, claimers find too few unlocked rows, return short and trigger refills. So size the pool, and the refill threshold, for peak concurrency, not for stock.

Scanning cost of SKIP LOCKED. Each claimer scans past rows locked by others. With C concurrent claimers in a pool ordered by id, the average claimer skips about C/2 locked rows before finding a free one. At C = 200, that is ~100 index entries per claim, a few microseconds. Inserting refilled rows at the end, while claimers take from the front, keeps refills from colliding with claimers.

Bucketed counters. With N buckets, each bucket sees λ/N. With 20 buckets and λ = 4,000 per second, each sees 200 per second, at ρ = 0.4. The tail: when total stock is T and spread evenly, a random bucket is empty with probability rising toward 1 as T approaches 0. With k probes, the chance of a false "sold out" while stock remains is about (fraction of empty buckets)^k. At 15 of 20 buckets empty, and k = 3 probes, that is (0.75)^3 ≈ 42 percent. So scan all buckets before declaring sold out, or consolidate buckets when stock falls below a threshold.

Redis. A single Redis shard runs ~100,000 to 200,000 simple script executions per second. A reserve script with a capped reclaim loop costs a few microseconds. The 10,000-unit sale is gone in ~0.1 second of Redis time. Redis is never the bottleneck. The problems are atomicity with the ledger, and what happens if Redis fails mid-sale.

Admission sizing. If the reserve path handles 5,000 per second at p99 < 200 ms, set the admission rate to ~60 to 70 percent of that (~3,000 per second). That leaves headroom for retries, releases and status traffic. 10,000 units at 3,000 admissions per second sell out in ~3 to 4 seconds of admission (some admitted users fail or leave). The waiting room then holds the remaining millions, and tells them the truth.

Deep Dive: 12:00:00, step by stepShow

11:50. The pages, images and scripts have been on the CDN since the morning. App servers, gateways and Redis are pre-scaled to 3 times the forecast. The inventory database's pool is filled: 10 SKUs, up to 1,000 rows each. The admission controller is set to 3,000 per second.

11:55. The sale URL redirects to the waiting room. 4 million users join over 5 minutes. Each receives a queue ticket without a position. Polling (every 10 seconds, with jitter) generates ~400,000 requests per second, served by the waiting-room tier and its cache.

12:00:00. The waiting room shuffles the 4 million tickets into random positions: a random permutation, or a random key per ticket sorted once. Positions are published. Users see "You are number 1,234,567".

12:00:00 to 12:00:04. Admission releases ~3,000 users per second. Their clients call reserve with fresh tokens. The unit pools for the hot sizes drain. Inline refills run a few times as pools empty faster than the background refill. By 12:00:04, ~10,000 holds exist.

12:00:04. The last unit of the last size is reserved. The Reservation Service marks every SKU ALL_RESERVED. The admission controller pauses. The edge flag flips. The 3.99 million users still waiting see "All units are reserved. Some may become available in the next 10 minutes. Stay in the queue to be first in line."

12:00:04 to 12:10. Holders check out. ~1,400 payments per minute flow to the provider. About 8 percent are declined. Some of those users retry with another card while their hold lasts. Others give up, and their holds are released explicitly. Other users simply close the tab.

12:03. Released units accumulate. As soon as availability becomes positive, the refill moves them into the pool, and the controller admits the next users from the head of the queue: the waiting users with the best positions, not new arrivals.

12:10 to 12:15. The earliest holds reach their deadline. Unpaid ones stop counting at that instant. The next refill returns their units, and admission resumes for each batch. A sweeper marks them EXPIRED a minute later, for tidiness.

12:20. Everything is sold. Status is SOLD_OUT. The queue closes. Fulfilment has thousands of orders waiting. Best-seller rankings will reflect the sale at the next hourly run.

What we watched: reserve p99 (peaked at ~180 ms), pool depth per SKU (hit zero 3 times, refilled inline each time), admission rate versus backend latency, provider error rate, and oversell checks: sold + active holds ≤ on_hand for every SKU, sampled every second, and never violated.

Deep Dive: failure walkthroughsShow

1. The reserve transaction commits, but the response is lost. The client times out and retries with the same Idempotency-Key. The handler finds the existing hold by (user_id, idem_key) and returns it. Without the key, the partial unique index (one active hold per user per sale) would still prevent a second hold, but the client would see an error instead of its reservation.

2. The payment webhook arrives twice. The first delivery claims the hold (a conditional update WHERE status = 'ACTIVE'), deducts the ledger and marks the order PAID. The second finds the hold already CLAIMED, and records the webhook id as processed. The ledger is deducted exactly once.

3. Replenishment is broken mid-sale. Pools drain and are not refilled. The inline refill path still works, because it lives in the reserve path, so buyers see slower reserves rather than false sold-outs. If the inline path also fails (a bug), reserves return SOLD_OUT while the ledger has stock. The monitor "ledger shows available, but status says SOLD_OUT for more than 10 seconds" pages on-call. This is the operational cost of the pool design, and why it needs its own alerts.

4. In the Redis-counter variant, Redis fails over and loses the last second of writes. Asynchronous Redis replication means a promoted replica may lack the latest decrements, so the counter is too high, and Redis would allow oversell. Mitigations:

  • the claim path checks the ledger (sold < on_hand) before confirming an order, and rejects the oversold orders with an apology;
  • reconcile the Redis counter against the ledger and the live holds after failover, before resuming admission;
  • use Redis's WAIT command for synchronous acknowledgement by replicas, which narrows the window but does not make Redis a consensus store.

That is a concrete reason the same-database design is safer.

5. The admission controller's token key leaks. An attacker mints admission tokens and bypasses the queue. Mitigations: short token lifetimes; tokens bound to a user id, a device or session, and the sale id; key rotation per sale; and anomaly detection on reserve calls whose token was never issued by the controller (it logs every issued token id).

6. The waiting room shows wrong positions after a node fails. Positions live in a replicated store. Clients hold a signed ticket containing their random key, so even if a node's state is lost, the position can be recomputed from the ticket against the admission cursor. No user loses their place because a server died.

Deep Dive: building a waiting room that scalesShow

The waiting room has to handle more traffic than anything else in the system, so make it as close to stateless as possible.

The deli-counter model. At a deli counter, you take a numbered ticket, and a screen shows "now serving 42". Nobody keeps a list of who is waiting: your ticket and one global counter are enough.

  • At join time (or at the start, for randomised queues), each user receives a signed ticket containing their position number p.
  • The admission controller maintains one value, the admission cursor c, which advances at rate R. For example, c increases by 3,000 every second.
  • A client polling the waiting room sends its ticket. The server verifies the signature and compares p with c. If p ≤ c, it issues an admission token. Otherwise it returns "waiting", with an estimated wait of (p − c) / R.
  • The server needs no per-user state: just the signing key and the current cursor (one number, replicated or cached everywhere). That scales to millions of pollers on cheap, stateless nodes, or even at the CDN edge with edge functions.

Randomised positions. For users already waiting at the start, generate positions from a random permutation. A simple way is to give each ticket a random 64-bit key at join time, and at 12:00 assign ranks by sorting the keys. For millions of users, that is a quick sort on a single machine, or a distributed sort. Late joiners receive positions after the last randomised one, in arrival order.

Abandonment. Some admitted users have left by the time their turn comes. The cursor can advance faster than the purchase path's capacity, to compensate: if 30 percent of admitted users never call reserve, admit about 1.4 times the capacity. Measure the real ratio live, and adjust.

Stopping and resuming. When stock is gone, the controller freezes the cursor and publishes "sold out" (or "all reserved"). When units return, it advances the cursor by the number of returned units, divided by the expected conversion rate.

Anti-abuse. Tickets are bound to an account and a device, so they cannot be resold or shared, and each account can hold one ticket. Joining requires passing a challenge. Because tickets are signed, forging a better position is impossible without the key.

Deep Dive: isolation levels and locks in PostgreSQL and MySQLShow

Many surprises in this design come from the database's locking details, which differ between engines.

MySQL InnoDB (default REPEATABLE READ):

  • Locking reads (FOR UPDATE) lock the index records they scan, and under REPEATABLE READ also the gaps between them (next-key locks), to prevent phantoms.
  • A locking scan that finds nothing still locks the gap where matching rows would be inserted. In the pool design, that is exactly where refills insert. Hence Shopify's switch to READ COMMITTED for these transactions: under it, InnoDB uses record locks for searches, and generally does not take gap locks (apart from cases such as foreign-key and duplicate-key checks).
  • Secondary-index lookups lock the secondary index record and the clustered (primary key) record. Designing the primary key so that the hot query walks it directly halves the locks taken.
  • SKIP LOCKED and NOWAIT have been available since MySQL 8.0.

PostgreSQL (default READ COMMITTED):

  • Row locks are recorded in the tuple header itself. There is no lock table per row and no gap locking. Phantoms are prevented only at SERIALIZABLE, by predicate locks under Serializable Snapshot Isolation, which detect dangerous patterns and abort transactions instead of blocking.
  • FOR UPDATE SKIP LOCKED has been available since 9.5. It is widely used for job queues.
  • The conditional-update pattern (UPDATE ... WHERE available >= 1) behaves well under READ COMMITTED. If the row changed while the update waited for the lock, PostgreSQL re-evaluates the WHERE clause against the newest row version before updating, so the guard holds.
  • Under REPEATABLE READ or SERIALIZABLE, the same conflict raises a serialisation error instead, and the application must retry.

Deadlocks in both. If transaction A locks SKU 1 and then SKU 2, while B locks SKU 2 and then SKU 1, they deadlock. The database detects it and aborts one, but under load these aborts become a storm. Always acquire locks in a canonical order: by table (pool before holds, as Shopify did) and by key (ascending SKU id for multi-item carts).

Choosing the isolation level (see Concurrency Control and Database Locking): the reservation transactions are designed to be correct under READ COMMITTED, because every decision is made by a locking read or a guarded update. Higher levels add aborts and, in MySQL, gap locks without adding safety for this workload.

Deep Dive: inventory accounting beyond a single numberShow

Real inventory systems track several quantities per SKU, and "how many can we sell?" is a formula over them.

  • On hand: physical units in the warehouse.
  • Committed (allocated): units promised to paid orders but not yet shipped.
  • Reserved (held): units in active, unexpired checkout holds.
  • Safety stock: units deliberately held back to absorb miscounts, damage and returns processing.
  • Available to sell = on hand − committed − reserved − safety stock.

Multiple warehouses. A SKU stocked in three warehouses has three ledgers. Reserving "one unit" can mean reserving from any of them. Simple designs keep one aggregated sellable count for the sale, and decide the warehouse later, at fulfilment (late binding). Others reserve per warehouse based on the buyer's region, to cut shipping cost, at the price of more pools and more tail problems.

Available-to-promise (ATP) extends the formula into the future: incoming purchase orders and production schedules add to future availability. That is how pre-orders and backorders are sold safely (see the variants DeepDive).

Events as the audit trail. Every change (received, reserved, released, committed, shipped, adjusted after a count) is written as an inventory event, alongside the ledger update. The ledger is the fast current state, and the event log explains how it got there. When a count is off, the log shows which flow caused it (see Event Sourcing and CQRS).

Returns add units back only after inspection, to on_hand or to a separate "refurbished" SKU. In a flash sale, a return arriving weeks later is not resold in the same event. Stock returns go to normal channels.

Why this matters in the interview: saying "decrement a counter" is fine for the core flow. Showing that you know where that counter comes from, and that the flash sale's pool is a slice of a larger accounting system, signals real-world experience.

Deep Dive: the cart serviceShow

Carts are the everyday heart of e-commerce, and their design is shaped by one fact: most carts are abandoned. Industry studies commonly put the abandonment rate around 70 percent, although estimates vary by sector.

Storage.

  • A cart is small: a few line items (sku, qty, added_at, price_seen), under a few kilobytes. Store it in a key-value store keyed by cart id: DynamoDB, Redis with persistence, or a database table (see Amazon DynamoDB in Practice).
  • Anonymous carts are keyed by a cookie id. On login, merge the anonymous cart into the user's cart: sum quantities, cap at limits, and keep the newer price snapshot.
  • Give carts a long TTL (weeks), refreshed on each change. Expired carts are deleted, or archived for analytics.

Prices and availability are hints in the cart. The cart remembers the price the user saw, to show "price changed" messages. At checkout, prices are recomputed from the catalogue and promotions. Availability in the cart ("only 3 left") is read from a cached status, and never reserves.

Write path. Add-to-cart traffic is far higher than checkout traffic, so the cart service must not touch inventory. A simple, horizontally scaled service over a partitioned store handles it.

Availability matters more than consistency here. Amazon's Dynamo paper (DeCandia et al., "Dynamo: Amazon's Highly Available Key-value Store", SOSP 2007) famously used the shopping cart as its motivating example. It favoured always accepting "add to cart", even during failures, and merging divergent versions of a cart later, so a deleted item could occasionally reappear. That is an acceptable anomaly for a cart, and an unacceptable one for inventory. Different data, different consistency needs, in the same checkout (see Quorums and Leaderless Replication and CAP Theorem and PACELC).

Flash-sale items in carts. Many shops prevent flash-sale items from sitting in carts at all. "Buy" goes straight to a reservation and a dedicated express checkout, so the cart never holds scarce stock.

Deep Dive: designing the admission tokenShow

The admission token lets the gateway decide, without a database call, that a request comes from a user the waiting room admitted.

Contents (claims):

  • sale: the sale id, so tokens for one sale don't work for another;
  • sub: the user id, so the token is useless to anyone else;
  • sid: a session or device binding, such as a hash of a session cookie, so a stolen token can't be used from another browser;
  • jti: a unique token id, logged at issuance;
  • exp: an expiry a few minutes ahead, and nbf (not before) when needed.

Signing. Use an asymmetric signature (for example Ed25519 or ECDSA). The admission controller holds the private key, and gateways hold only the public key. Verification costs tens of microseconds of CPU, which is negligible even at hundreds of thousands per second. Rotate keys per sale, so that a leaked key is useless afterwards.

Replay and sharing. Within its lifetime, one token could be used for many reserve calls. That is fine, because the per-user limit in the database stops a second hold. Binding to sub and sid stops the token being sold to someone else. For extra safety, record used jtis in Redis with a TTL, to cap the reserve attempts per token.

Expiry choice. Too short (30 seconds), and a slow mobile user can be admitted but expire before reserving. Too long (30 minutes), and a token can be stockpiled. A few minutes, renewed once if the user is active, is a reasonable balance.

Why not just a session flag in Redis? It works, but every reserve call then needs a Redis lookup, and Redis becomes another hot dependency at the peak moment. A signed token moves that check to local CPU on the gateway (see Authentication and Authorization).

Deep Dive: rate limiting for the saleShow

Rate limits protect the system and enforce fairness. They need to be cheap, because they run on every request at the peak.

Where:

  • Edge or CDN: coarse limits per IP and per IP range (for example 20 requests per second per IP), plus bot scoring. They stop floods before they reach our servers.
  • Gateway: limits per user and per token. For example, 1 reserve attempt per second per user, and 10 status polls per minute. Use a token bucket (it allows short bursts, then a steady rate) or a sliding window counter.
  • Service: concurrency limits (at most N in-flight reserve transactions per instance). That is backpressure: excess requests get a fast "try again" instead of queueing until they time out.

Implementation:

  • Per-node in-memory buckets are fastest, but users spread across nodes see N times the limit.
  • A centralised counter in Redis (an atomic increment with expiry, or a Lua token bucket) is accurate, but adds a round trip, and creates hot keys for very active users.
  • A common compromise is sticky routing by user id at the gateway, so one node sees all of a user's requests, plus local buckets. Or local limits with periodic synchronisation.

Carrier-grade NAT puts thousands of mobile users behind one IP. IP limits must be generous, with per-user limits doing the precise work, or legitimate users are blocked together.

Response design. Return 429 with Retry-After, and have the client back off with jitter. Clients that ignore it are, by definition, misbehaving, and their limits tighten (see Rate Limiting and Throttling).

Deep Dive: pre-scaling plan for one saleShow

Auto-scaling reacts in minutes, and a flash sale peaks in seconds. So capacity is planned and provisioned before the event, from the forecast.

TierForecast peakProvision (illustrative)
CDN~1M page and status requests per secondPre-warm the cache with the page, images and status. Confirm with the CDN vendor for very large events.
Waiting room4M users, ~400k polls per secondStateless nodes or edge functions, plus a replicated cursor store
API gateway~50k requests per second after edge filtering3 times forecast instances, connection limits tuned
Reservation Service~3k reserves per second admitted, plus retries20 to 40 instances, connection pool sized to the database
Inventory database~5k short transactions per secondOne primary plus a sync standby, dedicated to the sale, buffer pool warmed
Redis~200k operations per second (limits, status)Several primaries with replicas, with hot keys cached in-process
Payment provider~25 authorisations per secondNotify the provider in advance. Use a second provider as a fallback.

These are planning estimates for this scenario. Validate them by load-testing the whole path at 1.5 to 2 times the forecast, including the sell-out moment and the retry storm that follows.

Freeze changes around the event. No deploys from an hour before to an hour after, except emergency fixes. Many flash-sale incidents are self-inflicted by a last-minute change.

Deep Dive: choosing the hold durationShow

The reservation TTL is a small number with large consequences. Too long, and abandoned holds keep stock invisible: with a 30-minute TTL and 20 percent abandonment, 2,000 of 10,000 units disappear for half an hour, and the sale reads "sold out" while buyers leave. Too short, and honest buyers lose their unit mid-checkout, which is the worst experience in the flow.

Measure the checkout time distribution. If the median time from reservation to payment is 90 seconds, and the 95th percentile is 4 minutes, a TTL of ~8 to 10 minutes covers almost everyone. Express checkout (saved address and card, wallet payments) shrinks the distribution, which makes shorter TTLs safe. That is one reason flash sales push users to sign in and save details in advance.

Expected stranded stock. If a fraction a of holds is abandoned, and abandoned holds are discovered only at expiry, the average number of invisible units is about (arrivals of holds per minute) × a × TTL. During the 10 minutes after sell-out, with 10,000 holds, a = 0.2 and TTL = 10, about 2,000 units are stranded, on average for half the TTL. Halving the TTL halves that. Explicit release (a cancel button, release on payment failure, release when the user navigates away) captures part of a immediately, and makes the effective number much smaller.

Adaptive policies:

  • a shorter TTL with one extension: 5 minutes, extended by 3 when the user reaches the payment step. Active users get time, while idle holds die quickly;
  • heartbeats: the checkout page pings every 30 seconds, and a hold without a heartbeat for 2 minutes is released early. Heartbeats can be lost, so use them only to shorten holds, never to lengthen beyond the TTL;
  • show the timer to the user. A visible countdown makes people finish, or cancel, rather than wander off.

Fairness to the queue. Every unit stranded in a dead hold is a unit a waiting user could have bought. The TTL is therefore also a fairness parameter. Shorter holds move the queue faster.

Deep Dive: proving there is no oversellShow

The invariant: for every SKU, at every committed state, sold + Σ(qty of ACTIVE holds with expires_at > now) + pool rows ≤ on_hand, and every unit sold maps to exactly one paid order. Expressed simply: units promised never exceed units owned.

How each operation preserves it:

  • Reserve moves units from the pool into a hold, in one transaction. The sum is unchanged.
  • Claim moves units from a hold into sold, in one transaction. The sum is unchanged.
  • Release and expiry move units out of holds. The sum falls, so the inequality still holds.
  • Refill adds pool rows only up to on_hand − sold − active holds − existing pool, computed under the refill lock. The sum rises at most to equality.

Because each step either keeps the sum equal or lowers it, and refill can raise it at most to on_hand, the inequality holds by induction over committed transactions. That argument is only valid if each step is atomic. That is precisely what was impossible with the hold in Redis and the ledger in MySQL.

Testing it:

  • Property-based tests generate random interleavings of reserve, claim, release, expire and refill against a model, and assert the invariant after every step.
  • Concurrency tests run thousands of real concurrent reserve and claim calls against a test database, then check the invariant and count orders per unit. Repeat them under fault injection: kill connections mid-transaction, fail over the primary, pause the refill worker.
  • Production checks: the per-second invariant monitor from the monitoring DeepDive, plus a post-sale audit that matches every order to one hold and every hold to at most one order.
Deep Dive: what to monitor during a saleShow

Correctness (page immediately):

  • Oversell invariant: for each SKU, sold + units in active unexpired holds ≤ on_hand. Check it every second from a replica, and also as a database constraint where possible.
  • Undersell signal: status shows SOLD_OUT or ALL_RESERVED while on_hand − sold − active holds > 0 for more than ~10 seconds.
  • Claims without payment, or payments without claims: they should be zero, and are verified by reconciliation.

Flow:

  • the admission rate and cursor, queue length, and estimated wait;
  • reserve attempts per second, and the split between results (RESERVED, SOLD_OUT, LIMIT_REACHED, TRY_AGAIN);
  • reserve p50, p99 and p99.9 latency; pool depth per SKU; inline refills per minute;
  • checkout conversion (reserved to paid), payment declines and timeouts, and the payment provider's latency.

Infrastructure: database CPU, commit latency, lock waits and deadlocks; connection pool saturation; Redis operations per second and hot keys; CDN hit ratio and origin requests per second; gateway rejections by reason (token invalid, rate limited).

Abuse: challenge failure rates, accounts per device or card, reserve attempts per account, and orders flagged for review.

Put all of this on one sale dashboard, with the sale's timeline marked (queue open, start, sell-out). During the event, the on-call team should be able to answer "are we overselling, underselling or stuck?" in seconds (see Observability: Logs, Metrics and Traces).

Deep Dive: a 45-minute interview planShow
MinutesFocusWhat to produce
0 to 5ClarifyScope (view, reserve, pay), stock versus demand, per-user limits, hold duration, fairness expectations
5 to 10Requirements and estimatesNo oversell, high availability for viewing. ~1M+ requests per second at the edge, against thousands per second the inventory tier can handle.
10 to 15Entities and APISKU, inventory, hold, order. Reserve and checkout endpoints, idempotency keys, admission tokens.
15 to 25High-level designCDN, waiting room, gateway, Reservation Service, Checkout Service, inventory DB, payment provider, event log
25 to 40Deep divesContention (hot row, then unit pool or Redis), expiry (deadline in data), admission (waiting room, Little's law), fairness and bots
40 to 45Wrap-upFailure modes, the Redis-versus-ledger atomicity window, monitoring, what you'd build next

Phrases that signal depth:

  • "We never hold a lock while the user pays. The hold is a row with a deadline."
  • "Availability ignores expired holds, so expiry needs no timer. The sweeper is only garbage collection."
  • "The hot SKU is a single-row problem. I spread it across many rows and use SKIP LOCKED."
  • "If the hold and the ledger must commit together, they belong in the same database."
  • "Most requests must be told 'no' cheaply, at the edge, before any inventory work happens."
Deep Dive: real-world notesShow
  • Shopify described its move of checkout reservations from Redis counters to MySQL, with a bounded pool of unit rows claimed via SKIP LOCKED, in a 2026 engineering post (Deep Dive 5). It is the clearest public account of the hot-row problem and its fix at e-commerce scale.
  • Hosted virtual waiting rooms are commercial products (for example from Cloudflare and Queue-it), used for ticket on-sales, product drops and government services during demand spikes. Their basic contract is the one described above: hold users at the edge, admit at a configured rate, show position and wait.
  • Draw-based releases are a common answer to bots in sneaker and limited-product drops: entries open for a window, and winners are chosen at random. Brand apps such as Nike's SNKRS have used draws for high-demand releases. The exact mechanisms are not public, so treat any specific internals as unknown.
  • Large shopping festivals, such as Alibaba's Singles' Day (11.11), are the extreme case of flash-sale traffic. Alibaba has publicly reported order peaks in the hundreds of thousands of orders per second. Treat the specific numbers as company-reported figures that vary by year.
  • High-profile launch failures, such as retail websites struggling during console launches and limited drops, typically fail in the layers in front of inventory: page servers, login, cart services. That is why the waiting room and the edge matter as much as the inventory algorithm.
Deep Dive: variants and how the design changesShow
  • Pre-orders and backorders. Stock isn't fixed: you sell up to a production cap, and fulfil later. Reservations become "orders against future stock", the ledger has an allocatable cap, and the same atomic decrement applies. Payment is often authorised but captured at shipment, which may be weeks later, beyond typical authorisation validity. So charge a deposit, or re-authorise before shipping.
  • Multi-item bundles. "Buy the shoe and the matching jacket together". Reserve both SKUs in one transaction, in canonical lock order. If either is unavailable, roll back both.
  • Tiered pricing. The first 1,000 units at $100, the next 2,000 at $120. The reservation must record which tier it consumed, atomically with the claim. Model each tier as its own pool, consumed in order, so no two buyers both get "the last $100 unit".
  • Limited quantity per region or channel. Separate pools per allocation (Deep Dive 8), with a controlled transfer between pools late in the sale.
  • Lottery sales. No real-time contention: entries are idempotent inserts, and the draw is a batch job that creates exclusive holds for the winners, with longer payment windows. Unpaid holds roll to a waitlist drawn in order.
  • Descending-price (Dutch) flash sales. The price falls every minute until sold out. Contention is on reserving at the current price. Include the price in the hold, and validate the price at claim time against the schedule.
  • Digital goods (codes, licences, game keys). Each unit is a distinct code. The unit pool is literally a table of codes, and claiming one with SKIP LOCKED gives each buyer a unique key.

Production reference. Shopify's ten flash-sale tactics (low timeouts, circuit breakers, fair queueing, idempotency keys, reconciliation, shard isolation and more) are summarised in More Company Architectures, and Razorpay's IPL peak preparation (per-merchant rate limit sidecars, ProxySQL, pre-scaling, smart routing) in Razorpay's engineering lessons.

Key Takeaways#

  • Reserve, then pay. A short transaction takes a unit off the table with a deadline. Payment happens afterwards, with no locks held.
  • Never oversell: every decision is an atomic guarded update, or a locked claim, at the source of truth. Never read-then-write in application code.
  • The hot SKU is a single-row problem. Spread it across many rows (a unit pool with SKIP LOCKED, or bucketed counters), or move it to an atomic in-memory counter, and understand what that costs in atomicity.
  • Holds and the ledger belong in one transaction. Two stores always leave a crash window that 2PC can't cover (Redis doesn't support it) and an outbox only repairs after the fact. That is Shopify's central lesson.
  • Put deadlines in the data. Availability ignores expired holds. Reclaim-on-reserve and sweepers are optimisations and garbage collection, not correctness.
  • Most requests must hear "no" cheaply. Use a CDN, a waiting room with signed tokens, admission at a rate derived from backend capacity (Little's law), and "sold out" served at the edge.
  • Fairness is a product decision: FCFS rewards bots, randomised queues and draws do not. Back it with per-account, card and device limits and challenges at queue entry.
  • Checkout is a saga: reserve, authorise, create the order, capture. Make each step idempotent, with a compensation for each. Unknown payment outcomes are resolved by asking, never by guessing.