Learning pathsPricingChecking sign-in…
GUIDED PRACTICE

Flash Sale

Design a high-demand sale for a limited inventory item.

Clarify this prompt before choosing components

Ask the highest-impact questions first, agree on priorities, and record the interviewer’s answers. If a detail is unspecified, state an assumption and explain which decision depends on it. The numbers in this worked lesson are exercise assumptions, not company facts.

Ask the interviewerWhy the answer changes the design
Single-item inventory, cart holds or multi-item checkout?Reservation atomicity and partial-cart policy differ.
Queue fairness, per-user caps and bot protection?Admission identity and overload responses become product decisions.
Hold expiry, payment unknown and abandoned checkout?Fenced reservations and reconciliation avoid overselling or leaking stock.

Use the Interview Playbook for the shared 45-minute sequence and fresher, intermediate, senior and staff evidence. Start with one complete operation. Extend the answer with the failure/recovery traces below, then defend a workload-specific alternative and a measurable rollout. Scope and evidence matter more than a large component list.

Flash Sale: Understand the building blocks

Choose a mechanism because it satisfies a requirement. These explanations describe the exercise design, not undisclosed implementation choices at the named company.

Flash Sale: Quick vocabulary

TermMeaning and role in this exercise
API: Application Programming InterfaceThe contract for requests, responses and errors between components. An API route does not itself enforce every business invariant.
PK: Primary KeyThe declared row identity in a database schema; it does not automatically enforce every cross-row business rule.

Flash Sale: Relational database transaction and constraints

What it means: A relational store keeps structured rows; a transaction commits a bounded group of changes together. Constraints reject specified invalid states.

Why this problem needs it: Stock must not go negative despite a hot item.

How to use it: Use primary/unique keys and a chosen isolation/locking protocol for the actual invariant. Atomically persist related rows and the operation result before acknowledgement.

Example in this design: Reserve H1 in the same enforcing transition that consumes available stock.

When it fits: Useful for bounded cross-row correctness, joins and access paths that fit the relational model.

Alternative and limits: Key/value stores can fit simpler keyed operations. “SQL” alone does not prevent lost updates, validate every cross-row rule or coordinate an external provider.

Mechanism reference

Flash Sale: Durable work queue and backpressure

What it means: A queue separates accepted work from execution. Backpressure limits admission or consumption when downstream capacity is finite.

Why this problem needs it: Traffic admission must protect the stock/payment owner.

How to use it: Persist a stable job identity, consume with bounded concurrency, acknowledge after the required durable transition, and cap retries/backlog according to policy.

Example in this design: A bounded waiting room absorbs a finite burst without claiming every request will eventually succeed.

When it fits: Useful for asynchronous work that must survive worker failure or absorb a finite burst.

Alternative and limits: A synchronous call is simpler for short bounded work. A queue does not create capacity, strict global ordering or exactly-once external effects.

Flash Sale: Saga and compensation

What it means: A saga coordinates several separately committed business steps. Compensation is an explicit corrective business action after a partial outcome.

Why this problem needs it: Payment can remain uncertain when an inventory hold reaches expiry.

How to use it: Track each step and its stable identity; on failure reconcile uncertain outcomes before requesting an allowed compensating action.

Example in this design: Do not let H2 steal H1 solely because P1 timed out; reconcile according to the declared policy.

When it fits: Useful when inventory, payment and dispatch have independent authorities.

Alternative and limits: A local transaction is simpler when all required state shares one database. Compensation may be partial or impossible; it is not automatic transaction rollback.

Flash Sale: Idempotency key and stored operation result

What it means: Idempotency means replaying the same logical operation produces no additional business effect. A key identifies that operation under a defined scope.

Why this problem needs it: Repeated checkout requests must refer to one operation.

How to use it: Atomically associate a request key and payload fingerprint with its effect and result. Return the stored result on replay; reject incompatible payload reuse.

Example in this design: Retry P1 with the same payload and identity rather than creating a fresh charge.

When it fits: Needed when a timeout can hide a successful commit or a queue can redeliver.

Alternative and limits: Unique business identities can enforce selected effects. A cache of recent requests alone may expire too early or race; local keys cannot control an uncooperative external provider.

Interview scope and guarantees

Admit buyers, reserve scarce inventory, create orders, collect payment and show a durable outcome. Define fairness and per-user purchase limits. Approximate stock displays are acceptable; successful purchases must never exceed available stock.

Capacity worksheet

Assume 1 million arrivals in 10 seconds for 10,000 units: 100,000 requests/s at the edge. If inventory safely handles 2,000 reservation attempts/s, admission must shed or queue the excess. At most 10,000 units can be sold regardless of compute capacity; rejecting early is part of the design.

Concrete API contract

Contract / pseudocode
POST /sales/{id}/admissions -> {ticket,expiresAt}
POST /sales/{id}/reservations {ticket,quantity,requestKey}
POST /orders/{id}/pay {paymentToken}
GET /orders/{id}

Data model and access paths

Contract / pseudocode
stock(sale_id,sku,available,reserved,sold,version); PK(sale_id,sku)
reservations(id PK,sale_id,sku,user_id,request_key,request_hash,quantity,state,expires_at); UNIQUE(sale_id,user_id,request_key)
orders(id PK,reservation_id UNIQUE,user_id,state)
purchase_limits(sale_id,user_id,held_qty,bought_qty); PK(sale_id,user_id)

Evolve a solution and explain each change

Three architecture decisions for Flash Sale, including the pressure each introduces.
Three architecture decisions for Flash Sale, including the pressure each introduces.
Read the diagram

Own stock authoritatively / Conditionally reserve units with unique customer/order identity. / A displayed cached count cannot prevent overselling.; Bound checkout admission / Use a waiting room, per-user limits, and short reservation deadlines. / Admission capacity and reserved inventory are different quantities.; Reconcile the checkout / Confirm matching reservations after payment and release expired holds once. / Late payment can race with stock reassignment.

Open original
Flash Sale · architecture decisions
Three architecture decisions for Flash Sale, including the pressure each introduces.

Three architecture decisions for Flash Sale, including the pressure each introduces.

Step 1: Own stock authoritatively

Conditionally reserve units with unique customer/order identity. A displayed cached count cannot prevent overselling.

Step 2: Bound checkout admission

Use a waiting room, per-user limits, and short reservation deadlines. Admission capacity and reserved inventory are different quantities.

Step 3: Reconcile the checkout

Confirm matching reservations after payment and release expired holds once. Late payment can race with stock reassignment.

Responsibility overview

Connected responsibilities for Flash Sale. Trace the authoritative and derived paths separately.
Connected responsibilities for Flash Sale. Trace the authoritative and derived paths separately.
Read the diagram

Buyer to Waiting room: join admission; Waiting room to Sale API: bounded checkout; Sale API to Stock ledger: conditional unit reservation; Sale API to Payment provider: stable payment identity; Payment provider to Hold reconciler: ambiguous or late outcome; Hold reconciler to Stock ledger: confirm or release same hold

Open original
Flash Sale · connected architecture
Connected responsibilities for Flash Sale. Trace the authoritative and derived paths separately.

Connected responsibilities for Flash Sale. Trace the authoritative and derived paths separately.

Worked end-to-end scenario

There are 100 units, but 10,000 customers click buy. Admission allows a bounded set to attempt checkout; it does not allocate units. A conditional reservation consumes one unit and records hold h17 for customer C. C retries after a timeout and gets the same hold. Payment is delayed past expiry; the reservation is released and another customer owns the unit. A late success for h17 goes to reconciliation rather than decrementing stock again or stealing the new reservation. Publish remaining stock as an approximate browsing signal and use the ledger/reservation transaction for the promise.

Why these access paths matter

Store item stock and reservations with owner, quantity, state, expiry, and payment identity. Unique customer-plus-sale constraints enforce the stated purchase limit. Index expiring holds and pending payment attempts for repair. Release checks reservation state atomically so duplicate cleanup cannot add inventory twice. A distributed cache increment is not enough unless its durability and ownership model meet the stock contract.

Build the baseline first

Flash Sale: baseline request paths.
Flash Sale · working baseline
Read the diagram

Buyer → admission gate → stock reservation transaction; Reservation → order and outbox → payment workflow; Payment outcome → confirm or release reservation

Open original
Flash Sale · working baseline
Flash Sale: baseline request paths.

Flash Sale · working baseline

  1. Buyer → admission gate → stock reservation transaction.
  2. Reservation → order and outbox → payment workflow.
  3. Payment outcome → confirm or release reservation.

Evolve the design under load

Flash Sale: additional scaling and recovery paths.
Flash Sale · scale and recovery paths
Read the diagram

Edge protection → signed queue tickets → bounded origin; Inventory token partitions → controlled allocation; Status cache → jittered polling → durable order state

Open original
Flash Sale · scale and recovery paths
Flash Sale: additional scaling and recovery paths.

Flash Sale · scale and recovery paths

  1. Edge protection → signed queue tickets → bounded origin.
  2. Inventory token partitions → controlled allocation.
  3. Status cache → jittered polling → durable order state.

Defend the hardest decision

An atomic decrement with available >= quantity enforces nonnegative stock on one authority. Splitting inventory into token pools can distribute contention, but the sum allocated to all pools must not exceed the global inventory. Per-user limits must be checked at the same business boundary as reservation or reconciled with a clearly stated overshoot policy. A countdown cache is not a reservation ledger.

Failure and recovery analysis

Payment succeeds after reservation expiry. Reconcile against the current reservation state and refund when stock has been reassigned. Releasing inventory must be conditional and idempotent; duplicate expiry events cannot increment stock twice. After a service restart, rebuild sold and reserved totals from durable state and compare the stock conservation equation.

Security and privacy boundary

Rate-limit bots, validate signed admissions at the origin, and keep payment calls outside inventory locks.

Interview follow-ups with reasoning

Question: How do you stop token replay?

Show answer and explanation

Answer: Bind admission tokens to user, sale, expiry and a consumption record.

Question: How do you keep the waiting room fair?

Show answer and explanation

Answer: Define queue ordering and prevent repeated sessions from gaining extra positions.

Question: How do you test the invariant?

Show answer and explanation

Answer: Run concurrent reserve/pay/expire races and assert sold + reserved + available equals initial stock.

Operate and verify the design

Admission rejection, reservation conflicts, payment uncertainty and inventory conservation.

Replay reserve, pay and expire events out of order and assert that available + reserved + sold stays constant.

A second scenario to test transfer

A request arrives when one unit remains. Two regions both display a cached count of one, but the authoritative reservation condition allows exactly one decrement. The winner receives a reservation ID; the other receives sold out or a queue retry response. The public product page can lag slightly without changing the stock decision.

How can the service admit users gradually while still guaranteeing that 10,000 units are never reserved twice?

Show answer and explanation

Answer: Admission limits load, while a conditional inventory reservation or globally partitioned allocation enforces the cap. Use stable idempotency keys and one current reservation per purchase. If allocation is split by region, each region receives a disjoint bounded quota and the sum of quotas cannot exceed sale inventory.

Compare alternatives

LayerPurposeInvariant
Waiting roomShape arrival rateDoes not own stock
Inventory ownerAtomic reservationTotal reserved ≤ available
Payment workflowResolve external resultLate success is reconciled
Sale status viewFast communicationMay lag within stated bound

A design-changing exercise

Can the waiting room guarantee that the first 100 admitted customers own the 100 units?

Show answer and explanation

Answer: Only if admission is explicitly coupled to reservation. Usually it controls load; authoritative inventory allocation is a separate conditional operation.

Design workshop: admission and inventory conservation

Scope, interfaces, and data model

Core scope is one sale/SKU, a per-user quantity cap, temporary holds and payment. A shopping cart across unrelated merchants is excluded. Assume a cap of two units/user, a two-minute hold and zero oversold units. Waiting-room order is a product policy, not ownership of stock. Product pages can be stale and cached; reservation success must come from the inventory authority. Admission fairness does not weaken stock correctness.

GET /sales/{id} serves cacheable description and availability estimates. POST /sales/{id}/waiting-room returns a signed, user-bound admission token and bounded refresh interval. POST /sales/{id}/reservations takes quantity, admission token, and stable request key; it returns the same reservation on an identical retry. POST /orders starts one payment attempt against that reservation; GET /orders/{id} reports hold, payment, and reconciliation state. An internal expiry worker releases only a still-active hold with no ambiguous payment. The API names the hold deadline and returns sold_out, limit_conflict, expired, or payment_unknown distinctly.

Sale(sale_id, sku, initial_stock), Inventory(available, reserved, sold), PurchaseLimit(sale_id, user_id, held_qty, bought_qty), QueueTicket(joined_at, state), one-use AdmissionToken(user_id, sale_id, expires_at), Reservation(owner, quantity, expires_at, state), PaymentAttempt(idempotency_key, provider_status), and Order separate browse, fairness, inventory, and payment authority. Stable request identity is unique by sale/user/key with a payload fingerprint. Payment callbacks have their own provider event identity; callback dedupe does not replace reservation idempotency.

Browse cheaply and admit one bounded purchase. Buyer to Catalog edge: Read cacheable sale description and estimate; Buyer to Waiting room: Join the fair queue with one account-bound ticket; Waiting room to Waiting room: Issue short-lived signed admission token and expiry; Buyer to Stock authority: Submit quantity, token, and stable reservation request key; Stock authority to Buyer: Return durable hold ID or sold_out/limit_conflict
Browse cheaply and admit one bounded purchase.
Read the diagram

Read cacheable sale description and estimate; Join the fair queue with one account-bound ticket; Issue short-lived signed admission token and expiry; Submit quantity, token, and stable reservation request key; Return durable hold ID or sold_out/limit_conflict

Open original
Browse cheaply and admit one bounded purchase
Browse cheaply and admit one bounded purchase. Buyer to Catalog edge: Read cacheable sale description and estimate; Buyer to Waiting room: Join the fair queue with one account-bound ticket; Waiting room to Waiting room: Issue short-lived signed admission token and expiry; Buyer to Stock authority: Submit quantity, token, and stable reservation request key; Stock authority to Buyer: Return durable hold ID or sold_out/limit_conflict

Browse cheaply and admit one bounded purchase.

Stock has available + reserved + sold = initial_total within the sale adjustment ledger. Lock the user limit and SKU inventory in the same declared stable order for every command. Ensure the limit row exists before locking it. The reserve operation checks held_qty + bought_qty + requested <= user_limit and available >= requested, then updates inventory, limit, reservation, request result, and payment outbox in one transaction. Return an existing matching request before checking whether its token is now expired; changed terms under that key conflict.

Stock has available,reserved,sold with available+reserved+sold=initial_total within the chosen adjustments ledger. Purchase limit authority stores held_qty and bought_qty under unique(sale,user). Stable request mapping is unique(sale,user,request_key) with fingerprint; retry returns the same reservation. Lock user limit and SKU stock in the same declared stable order for every command.

sql
BEGIN;
SELECT * FROM purchase_limits WHERE sale_id=:sale AND user_id=:user FOR UPDATE;
SELECT * FROM stock WHERE sale_id=:sale AND sku=:sku FOR UPDATE;
-- First return an existing matching request result.
-- Require held_qty+bought_qty+requested<=2 and available>=requested.
UPDATE stock SET available=available-:q,reserved=reserved+:q WHERE ...;
UPDATE purchase_limits SET held_qty=held_qty+:q WHERE ...;
-- Insert reservation/request result and payment outbox together.
COMMIT;

Ensure the limit row exists before locking it. Release and confirm lock the same rows and compare reservation state/identity. Only active→expired releases quantity; repeated expiry does nothing. Only active matching payment success→sold moves reserved to sold and held_qty to bought_qty. Late success after expiry becomes refund/unknown reconciliation; it cannot consume a newer user's hold.

Conservation for initial stock 10. Initial / 10 / 0 / 0 / 10; Reserve two units / 8 / 2 / 0 / 10; Confirm same hold / 8 / 0 / 2 / 10; Duplicate confirmation / 8 / 0 / 2 / 10; Reserve a second hold for two / 6 / 2 / 2 / 10; Expire that hold once / 8 / 0 / 2 / 10; Replay expiration / 8 / 0 / 2 / 10
Conservation for initial stock 10.
Read the diagram

Event / Available / reserved / sold / Sum; Initial / 10 / 0 / 0 / 10; Reserve two units / 8 / 2 / 0 / 10; Confirm same hold / 8 / 0 / 2 / 10; Duplicate confirmation / 8 / 0 / 2 / 10; Reserve a second hold for two / 6 / 2 / 2 / 10; Expire that hold once / 8 / 0 / 2 / 10; Replay expiration / 8 / 0 / 2 / 10

Open original
Conservation for initial stock 10
Conservation for initial stock 10. Initial / 10 / 0 / 0 / 10; Reserve two units / 8 / 2 / 0 / 10; Confirm same hold / 8 / 0 / 2 / 10; Duplicate confirmation / 8 / 0 / 2 / 10; Reserve a second hold for two / 6 / 2 / 2 / 10; Expire that hold once / 8 / 0 / 2 / 10; Replay expiration / 8 / 0 / 2 / 10

Conservation for initial stock 10.

The waiting room issues signed sale/user/admission/expiry tokens. A durable one-use admission map associates a token with its checkout request; signatures alone do not prevent replay. Choose FIFO after sale opening with a published pre-opening lottery if desired. A user cannot reuse a token for unlimited parallel holds. Queue admission responds 202 with position/refresh interval, and reserve responds 201 or 409 sold_out/limit_conflict under a stable request result.

Expired hold and late payment preserve new ownership. Buyer A to Stock authority: Reserve H1 for two units; Buyer A to Payment provider: Payment H1 accepted but response lost; Stock authority to Stock authority: H1 expires; conditional release once; Buyer B to Stock authority: Reserve H2 using released stock; Payment provider to Stock authority: Late success for H1; Stock authority to Buyer A: Compensate H1; never steal H2 inventory
Expired hold and late payment preserve new ownership.
Read the diagram

Reserve H1 for two units; Payment H1 accepted but response lost; H1 expires; conditional release once; Reserve H2 using released stock; Late success for H1; Compensate H1; never steal H2 inventory

Open original
Expired hold and late payment preserve new ownership
Expired hold and late payment preserve new ownership. Buyer A to Stock authority: Reserve H1 for two units; Buyer A to Payment provider: Payment H1 accepted but response lost; Stock authority to Stock authority: H1 expires; conditional release once; Buyer B to Stock authority: Reserve H2 using released stock; Payment provider to Stock authority: Late success for H1; Stock authority to Buyer A: Compensate H1; never steal H2 inventory

Expired hold and late payment preserve new ownership.

A global authority is simplest for a scarce sale. A regional quota extension gives disjoint durable stock pools whose sum equals sale inventory. Local reservations consume only their pool. Rebalancing is a fenced transfer: source freezes the transfer amount under a generation, durable coordinator records it, destination activates once under transfer ID, and source cannot reclaim ambiguous transferred stock. Never reallocate a disconnected region's unknown pool just because a lease expired; it may have sold units. Strand uncertain stock until reconciled rather than oversell.

Partition stock budgets without losing fairness. Waiting-room rank / FIFO after declared opening lottery / Durable ticket sequence / One ticket per account and sale; Regional stock pool / Disjoint preallocated unit quota / Fenced transfer ID / Sum of pool budgets equals initial stock; Per-user purchase cap / Check held plus bought globally / Sale/user limit row / Region changes cannot bypass the cap; Hot-item overload / Bound checkout and DB in-flight work / Admission token expiry / Queue order never grants stock ownership
Partition stock budgets without losing fairness.
Read the diagram

Dimension / Admission or inventory policy / Stored authority / Invariant; Waiting-room rank / FIFO after declared opening lottery / Durable ticket sequence / One ticket per account and sale; Regional stock pool / Disjoint preallocated unit quota / Fenced transfer ID / Sum of pool budgets equals initial stock; Per-user purchase cap / Check held plus bought globally / Sale/user limit row / Region changes cannot bypass the cap; Hot-item overload / Bound checkout and DB in-flight work / Admission token expiry / Queue order never grants stock ownership

Open original
Partition stock budgets without losing fairness
Partition stock budgets without losing fairness. Waiting-room rank / FIFO after declared opening lottery / Durable ticket sequence / One ticket per account and sale; Regional stock pool / Disjoint preallocated unit quota / Fenced transfer ID / Sum of pool budgets equals initial stock; Per-user purchase cap / Check held plus bought globally / Sale/user limit row / Region changes cannot bypass the cap; Hot-item overload / Bound checkout and DB in-flight work / Admission token expiry / Queue order never grants stock ownership

Partition stock budgets without losing fairness.

For a high-contention sale, begin with a single linearizable inventory authority. If one key cannot sustain required writes, preallocate disjoint regional stock budgets whose sum is total stock; a local sale can never exceed its budget. Rebalance only through a durable transfer ID and monotonically fenced source generation. User limits remain sale/user scoped across all regions. The waiting room uses one-use tokens, rate limits, account/device abuse signals, and a published FIFO/lottery policy; it does not promise that queue position equals eventual purchase if the token expires.

Payment is a separate state machine. Start a stable provider attempt only while the matching reservation is logically active. A timeout is unknown, not failure: keep units reserved and the user limit held until provider lookup/reconciliation returns a definitive result. A success received at or after expires_at cannot take stock from a later reservation; release the old hold if still held and enqueue a refund/compensation keyed by the original payment ID. Cleanup jobs are accelerators only; every confirmation checks the deadline in the transaction. If a payment callback wins the lock before the deadline, it changes reserved to sold once; if expiry wins first, late success compensates instead. Never use queue delivery as proof of exactly-once payment.

For an illustrative workload assumption, one million buyers arrive over ten seconds, or 100,000/s. If checkout can sustain 2,000 admitted/s, a queue drains that population in roughly 500 seconds before retries and withdrawals. A two-minute hold and provider throughput further constrain useful admission; admitting every queued user simultaneously is pointless. Serve queue/status at an edge-safe tier and maintain bounded checkout/database in-flight work. Report sold, reserved, expired and payment-unknown amounts separately.

Final topology: separate fairness, stock, and payment. Catalog edge / Cacheable sale details and estimates / Stale estimate never grants stock; Waiting room / Ticket order and signed admission token / Token is user-bound, one-use, and expires; Inventory authority / Available/reserved/sold and user limit / Atomic conservation transaction; bounded in-flight writes; Payment/reconciliation worker / Provider attempt and callback evidence / Unknown holds stock; late success refunds; Order/event API / Durable order status and client replay / Stable request key; bounded event history
Final topology: separate fairness, stock, and payment.
Read the diagram

Component / Authority and data / Bound or recovery contract; Catalog edge / Cacheable sale details and estimates / Stale estimate never grants stock; Waiting room / Ticket order and signed admission token / Token is user-bound, one-use, and expires; Inventory authority / Available/reserved/sold and user limit / Atomic conservation transaction; bounded in-flight writes; Payment/reconciliation worker / Provider attempt and callback evidence / Unknown holds stock; late success refunds; Order/event API / Durable order status and client replay / Stable request key; bounded event history

Open original
Final topology: separate fairness, stock, and payment
Final topology: separate fairness, stock, and payment. Catalog edge / Cacheable sale details and estimates / Stale estimate never grants stock; Waiting room / Ticket order and signed admission token / Token is user-bound, one-use, and expires; Inventory authority / Available/reserved/sold and user limit / Atomic conservation transaction; bounded in-flight writes; Payment/reconciliation worker / Provider attempt and callback evidence / Unknown holds stock; late success refunds; Order/event API / Durable order status and client replay / Stable request key; bounded event history

Final topology: separate fairness, stock, and payment.

Replay requests and payment events across expiry. Buyer to Stock authority: Reserve two units with request K; authority returns hold H; Stock authority to Payment provider: Start payment P; provider may accept while response is lost; Buyer to Stock authority: Retry K; return H without decrementing stock again; Expiry and refund worker to Stock authority: At deadline, keep H reserved while P is unknown; Payment provider to Stock authority: Late P success cannot claim stock; emit refund for P; Stock authority to Expiry and refund worker: Retry callback/reconciliation with same IDs; no second release/refund
Replay requests and payment events across expiry.
Read the diagram

Reserve two units with request K; authority returns hold H; Start payment P; provider may accept while response is lost; Retry K; return H without decrementing stock again; At deadline, keep H reserved while P is unknown; Late P success cannot claim stock; emit refund for P; Retry callback/reconciliation with same IDs; no second release/refund

Open original
Replay requests and payment events across expiry
Replay requests and payment events across expiry. Buyer to Stock authority: Reserve two units with request K; authority returns hold H; Stock authority to Payment provider: Start payment P; provider may accept while response is lost; Buyer to Stock authority: Retry K; return H without decrementing stock again; Expiry and refund worker to Stock authority: At deadline, keep H reserved while P is unknown; Payment provider to Stock authority: Late P success cannot claim stock; emit refund for P; Stock authority to Expiry and refund worker: Retry callback/reconciliation with same IDs; no second release/refund

Replay requests and payment events across expiry.

Operations and practice

SLIs: waiting-room age and admission-token expiry; reservation acceptance/limit conflict/sold-out rates; transaction latency and stock conservation violations; hold expiry lag; payment unknown age; refund reconciliation lag; and checkout queue depth. Overload controls: cap waiting-room refresh frequency, admitted checkouts, per-account ticket count, reservation quantity, and inventory-owner/database in-flight work. Degrade catalog freshness before admitting unbounded writers. Recovery: rebuild inventory from the durable reservation/order ledger, compare provider settlement/authorization reports, retain unknown holds until resolved, and repair regional budgets only through fenced transfers. Access: bind tokens to sale, user, and expiry; recheck account and purchase limit in the stock transaction; payment callback signatures/provider identity are verified before event dedupe. Dominant cost: contention on scarce stock and payment-provider capacity during the opening burst, not catalog reads.

Practice prompt: Design a limited 10,000-unit sale for one million arrivals over ten seconds, a two-unit account cap, two-minute holds, and an external payment provider. Follow-up: a hold expires while payment is unknown, another buyer reserves the released stock, then the first payment reports success twice. Rubric: calculate queue drain/checkout capacity; distinguish cached browse from authoritative reserve; define FIFO/lottery and token replay; keep stock and user cap atomic; conserve available+reserved+sold; treat expiry as a transaction predicate even if cleanup is late; retain ambiguous payment holds; compensate late success without stealing inventory; dedupe both client requests and provider events; bound overload and describe reconciliation. Invariant: one unit is in exactly one of available, reserved, or sold, and payment uncertainty never transfers a reservation to another buyer.

Exercise: User U holds two units, payment outcome is unknown, and U retries with a different request key. May it reserve two more?

Show answer and explanation

Answer: No under the cap. held_qty+bought_qty already equals two; another identity is another operation, not resolution of the first. Return the original reservation status when its request key is reused, and reconcile unknown payment without releasing stock twice.

Requirement trace and verification

RequirementImplementing design blockVerification link
R1 — Complete the primary user journey within the stated scope.P01–P04; P09–P10.V1 — Exercise the successful journey and the excluded/boundary case stated in the scope.
R2 — Preserve the problem's authoritative data invariant under concurrency.P05–P06; P11–P12; DD1.V2 — Run the race/replay case below and assert the invariant at the durable authority.
R3 — Meet the declared scale and API behavior without unbounded work.P05–P08; P13–P14; relevant overload deep dives.V3 — Exercise the API errors/retry identity and recompute the workload assumption that drives partition or capacity.
R4 — Recover from the named failure without losing or duplicating the user-visible outcome.P15–P16; deep dives; Operations contract.V4 — Send a burst exceeding stock, replay purchase requests, and race expiry with payment; sold plus reserved never exceeds total stock.

Operational contract

AreaDecision and signals
SLIsAdmission wait/expiry; reservation conflicts; sold/reserved conservation; payment-unknown age; late-refund backlog.
Overload limitsCap admitted tokens, checkout writes, per-user holds, provider concurrency, and waiting-room refresh rate.
RecoveryKeep unknown payment stock reserved; reconcile by stable attempt ID; release only active unambiguous holds.
Access controlsBind queue/reservation to authenticated account; prevent token replay and protect payment data.
Dominant costPeak inventory-authority capacity, payment-provider fees, and reserved-stock opportunity cost.

Senior-level interviewer follow-ups

Question: How do regional inventory pools avoid selling more than the global stock?

Show answer and explanation

Answer: Allocate conservative, fenced stock leases whose total never exceeds global inventory, or route the SKU to one owner. Regional availability improves latency but stranded leases reduce sellable stock.

Question: A reservation expires while payment is awaiting an unknown provider result. Can stock be released?

Show answer and explanation

Answer: Only under a policy that reconciles payment uncertainty first or compensates a confirmed charge. Bind the reservation and payment attempt to one generation so a delayed success cannot steal a new buyer's stock.

A 60-second design answer

I would absorb the burst with a fair admission queue, then use an authoritative per-SKU conditional hold and per-user cap. Checkout binds a hold generation to an idempotent payment intent; expiration releases stock only after the payment outcome policy is satisfied. Regional token leases improve locality at the cost of stranded inventory. I would measure queue fairness, stock conservation, hold leakage, payment uncertainty, and recovery time.

Dealing with Contention Redis

Technical references

Provider idempotency contract example.

PostgreSQL transaction isolation and concurrent updates.

Keep the unit attached to its current hold

One unit belongs to H1 while payment P1 is uncertain. Under the declared policy, either keep it reserved until reconciliation or expire it with a tracked late-success compensation rule. If H2 now owns it, a late P1 success cannot overwrite H2. Waiting-room admission tokens and payment operations do not independently grant stock.

Contract / pseudocode
unit U1: H1 / version 4
policy expires H1; H2 acquires version 5
P1 late success references H1
confirmation H1/version4 -> reject; compensation tracked
unit U1: H1 / version 4; policy expires H1; H2 acquires version 5; P1 late success references H1; confirmation H1/version4 -> reject; compensation tracked
Keep the unit attached to its current hold
Read the diagram

unit U1: H1 / version 4; policy expires H1; H2 acquires version 5; P1 late success references H1; confirmation H1/version4 -> reject; compensation tracked

Open original
Keep the unit attached to its current hold
unit U1: H1 / version 4; policy expires H1; H2 acquires version 5; P1 late success references H1; confirmation H1/version4 -> reject; compensation tracked

Keep the unit attached to its current hold

For 10,000 global units, regional budgets might be 6,000 and 4,000 with fenced transfer. Giving each region 10,000 creates a possible 20,000-unit promise. Rebalancing transfers applicable unused allocation under an epoch and prevents both owners spending the same transferred units. One-use admission tokens limit duplicate arrivals, while an authoritative inventory transition protects unit ownership.

Show answer and explanation

Answer: Fair admission improves overload and customer experience, but it is not the no-oversell proof. The proof names unit/budget authority, matching hold identity and fenced regional transfer.

Decision review: Flash Sale

Flash Sale: What it is

A flash-sale checkout admits a bounded burst, owns scarce units and reconciles payment against the original reservation.

Flash Sale: Why it is needed

Traffic control cannot repair a late payment that refers to an expired hold; stock ownership must stay attached to its current hold.

Flash Sale: When to use it

Use bounded admission before expensive checkout and a durable ownership rule when demand exceeds stock or provider capacity.

Flash Sale: How to use it

Give hold and payment separate stable identities. Define expiry while payment is unknown, then condition confirmation on the same eligible hold. Reconcile a late success using the product remedy.

Flash Sale: Compare an alternative

A waiting room can protect capacity but adds waiting and fairness policy. Direct checkout is simpler at moderate demand; neither removes inventory or provider uncertainty.

Flash Sale: Worked decision exercise

The following inputs and policies are original exercise assumptions; they are not measurements or undisclosed company behavior.

H1 owns a unit, payment P1 is unresolved, and its deadline arrives. Under a policy that protects uncertain payment, keep that unit unavailable pending reconciliation. Under a release policy, P1’s later success cannot steal a new H2 hold.

Flash Sale: Unit U7 belongs to hold H1; Payment P1 is unknown at the deadline; Policy decides retain-and-reconcile or release; Late P1 cannot confirm or release later hold H2
Flash Sale: a concrete state and recovery trace under the exercise assumptions.
Read the diagram

Unit U7 belongs to hold H1; Payment P1 is unknown at the deadline; Policy decides retain-and-reconcile or release; Late P1 cannot confirm or release later hold H2

Open original
Flash Sale: worked example
Flash Sale: Unit U7 belongs to hold H1; Payment P1 is unknown at the deadline; Policy decides retain-and-reconcile or release; Late P1 cannot confirm or release later hold H2

Flash Sale: a concrete state and recovery trace under the exercise assumptions.

What must a late confirmation compare before changing inventory?

Show answer and explanation

Answer: The current unit owner and the original hold/payment relation, not just the SKU quantity. If H1 is no longer eligible, use a tracked refund or other agreed remedy. A stale sweeper must not release or confirm H2 using an H1 event.

Flash Sale: Check the design

Monitor admitted demand, current holds, unresolved payments, expiry age and refunds. Reconcile the total unit states instead of using queue depth as inventory truth.

Regional stock and global purchase limits

Start with the existing complete baseline. The following workshop extends its authority, evidence and recovery contract under a changed requirement. Preserve scoped operation identities and distinguish durable acceptance from completed external work.

Deep dive: regional stock and per-user limits must conserve different budgets

The existing baseline already atomically reserves stock and the user's cap. This workshop extends it to regional allocation, uncertain payment and recovery. High availability cannot justify selling the same unit or granting the same account allowance independently in two regions. All quantities and timing rules below are exercise assumptions.

Start with two conservation equations

For one sale/SKU and a fixed adjustment ledger, use available + held + sold + transfer_escrow = initial_stock. Payment-unknown inventory remains held in the conservative policy chosen here. For a user with cap two, unspent_grants + held + bought <= 2 across every serving region. These are distinct budgets: disjoint stock pools alone do not enforce a global per-user limit.

Contract / pseudocode
sale_stock(sale, sku, region, epoch, available, held, sold, escrow)
user_cap(sale, principal, version, granted, held, bought)
cap_grant(id, sale, principal, region, quantity, state, generation)
reservation(id, sale, principal, request_hash, quantity, stock_epoch,
            cap_grant, deadline, state, payment_operation)
stock_transfer(id, source, destination, quantity, source_epoch,
               state, destination_receipt)

Resolve user identity from authenticated policy. Account limits are not a guarantee against a person creating many accounts; device/payment/bot signals are additional abuse controls with their own trade-offs. Bound quantity and request rate before entering the hot authority.

Spend a grant once, then reserve locally

The single-authority baseline remains the simplest safe design. When regions need local reservation decisions, preallocate disjoint stock and obtain a durable user-cap grant scoped to sale, principal, region and quantity. The global cap authority records outstanding grants before acknowledging them. Local grant consumption, inventory reservation, stable request receipt and publication intent share one transaction or a recoverable protocol.

If U receives two units of cap in region A, region B cannot issue two more merely because A is unreachable. A missing consumption response is unknown, not unused. Retry resolves the same grant/request fingerprint. Changed quantity or destination conflicts. Refund/release cannot automatically restore a lifetime purchase cap unless the business policy explicitly permits that; state whether the cap counts currently held plus completed purchases or net completed purchases after cancellation.

With grants this design trades coordination on every reservation for bounded up-front coordination and possibly stranded allowance. Grants, source stock allocation and actual reservations have independent expiry/reclamation contracts. A worker lease is not sufficient evidence that unspent grant credit is recoverable.

Transfer stock through durable escrow

Transfer T moves three free units from A to B. At A, atomically subtract three available and add three escrow under T and the current source epoch. B activates its received quantity once using a durable T receipt. Repeated delivery or a lost activation reply cannot add another three. Source completion retires the escrow into the recorded destination allocation; the logical stock equation counts the transfer quantity once across the declared transition states.

Flash-sale stock transfer: A escrows three units under transfer T; B activates T once; its reply is lost; A keeps the transfer unresolved; retry returns B's original receipt without minting stock
Lost transfer acknowledgment cannot justify restoring source stock and keeping destination stock.
Read the diagram

A escrows three units under transfer T → B activates transfer T exactly once → The activation response is lost → A preserves unresolved transfer evidence → Retry returns B receipt; no stock is minted

Open original
Flash Sale: recovery decision
Flash-sale stock transfer: A escrows three units under transfer T; B activates T once; its reply is lost; A keeps the transfer unresolved; retry returns B's original receipt without minting stock

Lost transfer acknowledgment cannot justify restoring source stock and keeping destination stock.

Do not time out escrow back to A while B might already have activated it. Cancellation must arbitrate with activation under an explicit transfer decision protocol. On region failover, restore transfer receipts, allocations, reservation and cap-grant state before allowing new sales. A disconnected region's nominal pool cannot be reassigned solely because a lease expired: it may have sold units. If the required history/authority is unavailable, strand the uncertain stock rather than duplicate it.

Distinguish deadline, payment uncertainty and capacity release

An ordinary active reservation can expire under authoritative time and release matching stock/cap commitments once. Starting payment first commits its operation identity and a bounded payment state. In this conservative variant, an unknown provider outcome preserves stock and user commitments while reconciliation resolves it; the UI deadline is not evidence of no charge. New request keys cannot spend the same cap again.

A successful payment after the permitted sale deadline follows compensation rather than quietly confirming a new claim. Preserve current reservation/generation and never take another buyer's inventory. If business policy instead releases stock at the deadline while retaining uncertain financial liability, name that alternate policy, its bounded exposure and its mandatory late-success compensation. Mixing early stock release with later unconditional sale confirmation is invalid.

Repeated release/cancel callbacks compare original reservation state and quantity. A reservation sold once cannot be returned to available by a delayed expiry message. Financial cancellation/refund status and stock availability remain separate outcomes; map each allowed transition explicitly.

Bound admission and interpret sold-out honestly

A region with zero free stock may be allocation-empty while another region has free units. Return that distinction or offer a bounded reallocation/wait path; do not label a partial regional view as globally sold out. Queue admission controls demand but does not reserve stock. A receipt for durable queued intent should report queued status, not confirmed reservation.

Suppose 10,000 units are divided A:6,000 and B:4,000. A transfers 1,000 free units without changing global total; its unknown transfer cannot be counted free at both ends. One million arrivals over ten seconds is 100,000/s. At 2,000 admitted attempts/s, merely evaluating that population takes at least 500 seconds before retries/withdrawals; there are still only 10,000 units.

A two-minute hold at 100 accepted units/s can tie up 12,000 units in a stationary approximation, exceeding total inventory. Cap outstanding held units and provider uncertainty independently of request concurrency. A 60,000-case recovery backlog with 300/s processing and 200/s fresh cases drains at 100/s over at least 600 seconds. More consumers cannot exceed shared provider or inventory decision budgets.

Track stock/cap equations, unspent grant age, escrow uncertainty, regional empty versus global sold-out outcomes, reservation deadline lag and late-payment compensation. Canary transfers with lost replies and stale epochs, rebuild from authoritative allocation/reservation history, and pause affected allocations when evidence disagrees. Rollback cannot discard old grant/transfer receipts still within recovery horizons.

Flash-sale assessment: conserve both allowances

Question: A user holds its two-unit allowance in an unreachable region. May another region grant two more because local stock is available?

Show answer and explanation

Answer: No. Stock and account-cap budgets are independent. Recover the original grant or wait under a bounded policy.

Question: B activated transfer T but its reply was lost. Can A restore its escrowed units on timeout?

Show answer and explanation

Answer: No. Query/retry T or arbitrate a terminal transfer decision; restoring while B retains activation duplicates stock.

Question: An unknown payment crossed the UI deadline. Does that prove reserved stock and cap can be released under this conservative policy?

Show answer and explanation

Answer: No. Preserve unresolved commitments until the declared outcome/recovery boundary. A different release-with-liability policy must be explicit.

Score one point for stock/cap conservation, scoped one-use grant/reservation identity, fenced escrow transfer and receipt recovery, explicit payment/deadline release policy, and finite regional/admission/recovery evidence. Compare Checkout, Rate Limiter and Payments.

29:00Self-guided practice timer
The timer resets when you leave this page. Save your design separately.
Your challenge

How can the service admit users gradually while still guaranteeing that 10,000 units are never reserved twice?

Your design draft

Clarify assumptions, explain your approach, and test the difficult cases. Save your draft, then compare it with the study notes.

Read study notes

Self-review checklist

Self-guided practice. Automated AI feedback and code execution are not connected.