Stock Reservation Service for a Flash-Sale Storefront
System DesignModel answerLast updated
Design a stock service that reports sellable quantity and reserves items for orders without overselling under concurrency, with idempotent retries, expiry, and contention handling.
Stock Reservation Service for a Flash-Sale Storefront
You are designing the stock-keeping part of an online store. The service must support two main capabilities:
- Availability lookup: report how many units of a product can currently be sold.
- Order placement: accept an order for one or more units and hold stock for it, so that the store never sells more than it owns, even when many buyers hit the same product at once.
Concentrate on contention on hot rows, where transaction boundaries belong, and how optimistic and pessimistic concurrency control compare.
Assumptions
- Stock is tracked per SKU at a single logical warehouse.
- Each placement request carries an idempotency key. It must reserve every requested unit or none of them.
- Many concurrent orders may target the same popular SKU.
- Cancelled or expired orders return their held units to stock.
- Payment is out of scope, but the reservation must have a state that supports a later confirm or cancel step.
Questions worth raising with the interviewer
- Can availability reads be a little stale, or must they reflect every committed reservation?
- Must an order spanning several SKUs succeed or fail as a whole?
- How long should a hold last before it expires?
- How hot is the hottest SKU (requests per second)?
- On failure, should the response identify which SKU was short and by how much?
What to deliver
Describe the data model and invariants, the API contracts (query, place, confirm, cancel, expire), the logic that prevents overselling, how retries are handled, a comparison of optimistic and pessimistic control under low and high contention, and how you deal with multi-SKU deadlocks, expiry, monitoring, and failure recovery.
Hints
Hint 1
Track three numbers per SKU: physically on hand, held by pending orders, and the derived sellable amount (on hand minus held). Decide which ones you store and which you compute.
Hint 2
The check 'is there enough?' and the write 'hold it' must happen as a single atomic step, for example a conditional UPDATE, so that two requests cannot both pass the check.
Hint 3
Compare what happens to a hot SKU when conflicting writers retry (optimistic) versus when they queue behind a row lock (pessimistic), and think about what changes for multi-SKU orders.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model answer
1. Data model and invariants
inventory (one row per SKU)
sku_id(PK),on_hand,reserved,version- Sellable quantity =
on_hand - reserved - Invariants:
reserved >= 0andreserved <= on_hand. Enforce these with aCHECKconstraint so a bug in application code cannot silently oversell.
reservation (one row per order)
reservation_id,idempotency_key(UNIQUE),statusin {HELD,CONFIRMED,CANCELLED,EXPIRED},expires_at,created_at
reservation_item
reservation_id,sku_id,qty
Storing reserved as a counter makes reads O(1). The reservation_item rows are the source of truth, so the counter can be audited and rebuilt by a reconciliation job.
2. API contracts
GET /availability/{sku}returnson_hand - reserved.POST /reservationswith{idempotency_key, items[]}returns 201 with the reservation, or 409 with the short SKUs.POST /reservations/{id}/confirmmovesHELDtoCONFIRMED(payment succeeded).on_handis decremented andreservedis decremented by the same amount at fulfillment or confirmation.POST /reservations/{id}/cancelmovesHELDtoCANCELLEDand releases the units.- Expiry is performed by a background sweeper, described below.
3. Atomic no-oversell placement
Run everything in one database transaction:
- Insert the
reservationrow with the idempotency key. If the unique constraint fires, load and return the existing result (see section 5). - Sort the requested items by
sku_id. - For each item run a conditional update:
UPDATE inventory
SET reserved = reserved + :qty, version = version + 1
WHERE sku_id = :sku AND on_hand - reserved >= :qty;
- If any statement affects 0 rows, roll back the whole transaction. This gives all-or-nothing behavior.
- Insert the
reservation_itemrows and commit.
The check and write are a single statement, so two concurrent requests cannot both pass the check on the last unit. No application-side read-then-write is needed.
4. Optimistic vs pessimistic control
Pessimistic (SELECT ... FOR UPDATE, or the conditional UPDATE itself, which takes a row lock):
- Writers on the same SKU queue behind the lock. There are no failed attempts, only wait time.
- Low contention: lock cost is negligible.
- High contention: the queue serializes throughput on that row (roughly 1 / transaction time, e.g. 1-2k per second per row on a tuned DB). Long transactions, for example ones that call other services while holding a lock, make this much worse. Keep transactions short and never call out to payment inside them.
Optimistic (read version, write WHERE version = :v, retry on conflict):
- Low contention: best option, no locks held, conflicts are rare.
- High contention: many writers read the same version, one wins, the rest retry. Wasted work grows and can cause retry storms and unfair starvation. Needs capped retries with jittered backoff.
Recommendation: use the conditional atomic UPDATE (effectively a short pessimistic lock) as the default, since it is simple and correct. Use optimistic versioning for rarely contended SKUs if lock overhead matters. For truly hot SKUs, see below.
5. Idempotent retries
The UNIQUE idempotency_key guarantees one reservation per key. On a duplicate, return the stored outcome (success or failure) rather than re-running. Store the request hash too, so the same key with a different payload returns an error. Because the key insert and the stock updates share one transaction, a crash leaves either nothing or a complete reservation, never a half-applied one.
6. Multi-SKU orders and deadlocks
If order A locks SKU 1 then 2 while order B locks 2 then 1, they deadlock. Always acquire in a global order (sorted sku_id). Also set a lock timeout and retry once on a deadlock error as a safety net.
7. Expiry and release
A sweeper runs every few seconds:
SELECT reservation_id FROM reservation
WHERE status='HELD' AND expires_at < now()
FOR UPDATE SKIP LOCKED LIMIT 100;
For each, in a transaction, move status to EXPIRED only if it is still HELD and decrement reserved per item. The status guard makes cancel, confirm, and expire mutually exclusive, so a late confirm after expiry fails cleanly rather than double-releasing. Confirm should check expires_at and status in the same conditional update.
8. Hot SKUs at scale
- Reads: serve availability from a cache or replica with a short TTL (1-2 seconds) and accept staleness. The write path remains the authority, so a stale "in stock" display can at worst produce a clean 409.
- Writes: if one row becomes the bottleneck, split the counter into N shards (for example 16 sub-rows each holding part of the stock). A request picks a shard and falls back to others on failure. The trade-off is that the total is approximate and the last few units may be hard to claim, so use it only for very hot SKUs.
- Alternatively, route all requests for a SKU through a single-threaded queue or partition (Redis Lua script or a per-SKU actor), which removes lock contention at the cost of a new component that needs durability.
9. Observability and recovery
- Metrics: reservation success rate, 409 rate per SKU, lock wait time, deadlock count, retry count, expiry lag, number of
HELDreservations. - A nightly reconciliation job compares
reservedagainst the sum of activereservation_itemrows and alerts on drift. - Emit events (reserved, confirmed, released) through a transactional outbox so downstream systems stay consistent without dual writes.
Common mistakes
- Reading availability, then writing in a separate step (race, oversell).
- Holding row locks across a payment call.
- Inconsistent lock ordering for multi-SKU orders.
- Forgetting that expiry, cancel, and confirm can race.
- Treating idempotency as a cache lookup outside the transaction.
- Using optimistic retries blindly on a hot SKU.