“Design an inventory system” sounds like a CRUD table with a quantity column until you ask the one question that breaks it: what happens between the moment a user clicks “Buy” and the moment their payment clears? That gap is 30 seconds to 3 minutes of a human entering a card number, a bank doing a 3DS challenge, a gateway round-tripping. During a flash sale, 10,000 people are in that gap at once for a SKU that has 500 units. If you decrement stock only after payment succeeds, every one of those 10,000 sees “in stock,” 9,500 of them will pay, and you have just sold 500 units to 10,000 people. If you decrement at “Buy” and never put it back when they abandon the cart, your shelf shows “sold out” with 500 units sitting unsold. Neither is acceptable.

The real answer is a reservation: when checkout starts, you place a time-bounded soft hold on N units - they are neither available to anyone else nor permanently gone. If payment succeeds within the window, the hold becomes a hard commitment (the unit is truly sold). If payment fails or the user walks away, the hold expires and the unit flows back to available automatically. The interviewer is testing whether you can run this reserve/commit/expire lifecycle atomically at high throughput (decrementing an in-memory count millions of times without ever letting available go negative) while keeping the reservation state durable enough that a cache node dying mid-checkout does not either lose a paid customer’s unit or silently double-sell it. That tension - speed in memory versus durability on disk - is the whole design.

This overlaps with a flash-sale coupon giveaway, but the inventory here is not a single fungible counter you run to zero once. Units are reserved, then either committed or released back, so the count goes both down and up, per SKU, concurrently, under a clock. The hard part shifts from “decrement one number to zero” to “run a two-phase hold-then-commit lifecycle that is correct under concurrency, survives node failure, and self-heals abandoned carts.” Let me build it properly.

Functional Requirements (FR)

In scope:

  • Check availability. Given a SKU (and optionally a quantity), return whether that many units are currently available to buy. This is a read, allowed to be slightly approximate for display.
  • Reserve stock (soft hold). When a user enters checkout, atomically place a time-bounded hold on N units of a SKU. If fewer than N are available, reject (or partially fulfill if the API allows). The hold has a TTL (say 10 minutes).
  • Commit a reservation (hard sell). On payment success, convert the soft hold into a permanent decrement. The units are now truly sold and can never be released back.
  • Release a reservation. On payment failure, explicit cart abandonment, or TTL expiry, return the held units to available stock. Expiry must be automatic - a user who closes the tab must not strand inventory.
  • Restock / adjust. Warehouse receives new units, or an order is cancelled/returned; available count goes up. Admin adjustments too.
  • Idempotent operations. Reserve, commit, and release must each be safe to retry - a network retry on commit must not double-decrement.
  • Multi-item reservations. A cart has several SKUs; reserving the cart is all-or-nothing across its lines (a basic saga), so you do not sell a user 2 of 3 items and charge them.

Explicitly out of scope (say it so you own the scope):

  • Payments internals. We consume a payment-succeeded / payment-failed signal; we do not build the gateway, 3DS, or refunds. The reservation system reacts to payment outcomes, it does not process money.
  • Pricing, promotions, tax, shipping. A separate concern; we hold units, not prices.
  • Warehouse / WMS physical fulfillment, pick-pack-ship. We track sellable inventory, not bin locations. We emit “committed” events that fulfillment consumes.
  • Full product catalogue, search, recommendations. Not this system; we key everything by an opaque sku_id.
  • Multi-warehouse allocation routing (which DC ships from) beyond noting how the schema extends to it. Primary design is a single logical availability pool per SKU.

The one decision that drives everything: stock is a two-phase resource, not a one-way counter. available can go down (reserve, commit) and up (release, restock, expiry). The invariant is not “never below zero” alone - it is a conservation law: on_hand = available + reserved + committed_not_yet_shipped, and available must never go negative while reservations can expire concurrently with commits and releases. Getting that arithmetic to hold atomically, at flash-sale throughput, with reservation records durable across a cache crash, is the entire job.

Non-Functional Requirements (NFR)

  • Scale: catalogue of ~10M SKUs; normal load a few thousand reservations/sec. During a flash sale, a few hundred hot SKUs absorb the storm - a single hot SKU can see 50,000+ reserve attempts/sec while holding only a few thousand units. Most attempts will fail (sold out); the system must reject them cheaply.
  • Latency: a reserve call must return yes/no in under ~100ms p99 - it is on the critical checkout path, blocking the user. Availability reads a few ms (cached). Commit/release can be slightly slower (async-tolerant) but should land within a second.
  • Availability: 99.95%+ on the reserve and commit paths. The reserve path may fail closed: if we cannot confirm a unit is available, we refuse. Refusing a sale is a lost conversion; overselling a unit means cancelling a paid order later, which is far worse (angry customer, refund, support cost, reputation).
  • Consistency: the reserve decrement and commit are strongly consistent / linearizable per SKU - available never goes below zero, a committed unit is never released, and a unit is never counted twice. Availability display can be eventually consistent (stale by a second). The conservation law holds exactly at rest.
  • Durability: a reservation that a user is actively paying against must survive a crash. If the in-memory stock node dies while 3,000 people hold reservations, we must not (a) lose a reservation a customer then pays for, nor (b) forget a held unit and hand it to someone else. Committed sales are sacred - never lost.
  • Correctness invariants (the whole point):
    • available >= 0 for every SKU, always, under any interleaving.
    • available + reserved + committed = on_hand (conservation), always at rest.
    • A reservation is committed at most once and released at most once; commit and release are mutually exclusive for a given reservation.
    • An expired reservation returns exactly its held units to available - no more, no less, even if expiry races a late commit.

Back-of-the-Envelope Estimation (BoE)

Real numbers, because they tell us where the pressure actually is.

Catalogue and baseline:

SKUs:                         10,000,000
Avg reservations/sec (steady): ~5,000/s across the catalogue
Reserve : commit : release ratio ~ 1 : 0.4 : 0.6
  (40% of holds convert to a sale, 60% abandon or fail payment)
So commits ~2,000/s, releases ~3,000/s at steady state.

The flash sale (the number that matters):

Hot SKUs in a sale:           ~200
Attempts on one hot SKU:      50,000 reserve attempts/sec
Units available on that SKU:  3,000
=> ~47,000 of those 50,000/s must be rejected as sold-out, cheaply.
Across 200 hot SKUs:          ~10,000,000 reserve attempts/sec aggregate peak.

Ten million reserve attempts per second, concentrated on 200 keys. That is the whole problem: extreme per-key contention on a tiny number of hot SKUs, not raw catalogue volume.

Storage:

Inventory row per SKU ~ 150 bytes (sku_id, on_hand, available, reserved, committed, version).
10,000,000 * 150 B = 1.5 GB for the authoritative stock table. Fits in RAM easily.

Reservation record ~ 250 bytes (res_id, sku_id, user_id, qty, state, expires_at, ...).
Peak concurrent holds: say 2M active reservations during a big sale.
2,000,000 * 250 B = 500 MB of live reservation state.
Over a day with churn: ~50M reservation records * 250 B = 12.5 GB/day of history.

Storage is small. This is a concurrency-and-durability problem, not a big-data one.

Bandwidth:

At 10M reserve attempts/s peak, req+resp ~500 B => ~5 GB/s aggregate.
Mostly absorbed by the edge/gateway and per-SKU rejection; the authoritative
store sees only the successful trickle (bounded by actual stock) plus
commits/releases.

Cache / in-memory sizing:

Hot-SKU counters live in memory (Redis). Even all 10M SKUs as
{available, reserved} integers = ~10M * 32 B = ~320 MB. Trivially cacheable.
The reservation index (res_id -> state, expiry) for 2M live holds = a few hundred MB.

The takeaway: the authoritative data is tiny and fits in RAM; the churn and history are modest; the only hard resource is a handful of hot SKU counters that millions of requests per second converge on, combined with the requirement that the reservation ledger behind those counters be durable across a crash. The design budget goes into (1) making reserve/commit/release atomic per SKU in memory, (2) persisting reservation state durably without blocking the hot path, and (3) auto-expiring abandoned holds so inventory self-heals. Nothing else is hard.

High-Level Design (HLD)

The architecture splits into a fast in-memory decision plane (the atomic per-SKU counters that decide reserve/commit/release in microseconds) and a durable ledger plane (the reservation records and authoritative stock table that survive crashes). A write-ahead discipline ties them together so a cache node can die mid-checkout without losing or double-counting a unit. Expiry is handled by a background reaper plus lazy expiry on access.

   ┌───────────────┐    enter checkout / pay / abandon    ┌────────────────────┐
   │   Shoppers     │  ──────────────────────────────────▶ │  Payment Service    │
   │  (web/app)     │                                       │ (emits paid/failed) │
   └──────┬─────────┘                                       └─────────┬──────────┘
          │                                                           │ paid/failed events
   ┌──────▼──────────────────────────────┐                           │
   │        CDN / Edge + API Gateway       │                          │
   │  - authn, per-user/IP rate limit      │                          │
   │  - caches availability (short TTL)    │                          │
   │  - sheds sold-out floods at the edge  │                          │
   └──────┬────────────────────────────────┘                         │
          │  reserve / commit / release                              │
   ┌──────▼────────────────────────────────────────────────┐         │
   │        Reservation Service (stateless, autoscaled)      │◀────────┘
   │   reserve: WAL-append -> atomic DECR available (Redis)  │
   │   commit:  move reserved -> committed (idempotent)      │
   │   release: move reserved -> available  (idempotent)     │
   └───┬──────────────────────┬───────────────────┬──────────┘
       │ (1) write-ahead       │ (2) atomic op      │ (3) async durable
       │     reservation       │    on hot counter  │     commit/release
   ┌───▼────────────────┐ ┌────▼─────────────┐ ┌────▼───────────────────┐
   │ Reservation Ledger  │ │ Redis (per-SKU   │ │  Kafka (reservation     │
   │ (durable, source of │ │ counters +       │ │  state-change events)   │
   │  truth for holds;    │ │ res index +     │ └────┬───────────────────┘
   │  sharded by sku_id)  │ │ Lua atomicity)  │      │ consumer
   └───────┬─────────────┘ └────┬─────────────┘ ┌────▼───────────────────┐
           │ reconcile          │ TTL / reaper   │  Inventory DB (on_hand, │
   ┌───────▼─────────────┐  ┌───▼─────────────┐  │  committed; authoritative│
   │  Expiry Reaper       │  │ Keyspace-expiry │  │  sellable truth, SQL)   │
   │ (sweeps expired holds │ │ + lazy expiry   │  └─────────────────────────┘
   │  back to available)   │ └─────────────────┘
   └──────────────────────┘

Availability read (“is it in stock?”) - the easy path:

  1. The product page / cart reads a GET availability endpoint, served from the edge cache with a 1-2s TTL, backed by the Redis available:{sku} counter.
  2. It is deliberately approximate. Showing “In stock” that is a second stale is fine - correctness is enforced at reserve time, not display time. 50M page views cost nothing at the origin.

Reserve flow (“hold these for me”) - the hard path:

  1. User clicks “Buy”/enters checkout. Request hits the edge (drops abuse, serves cached “sold out” for already-exhausted hot SKUs), then the gateway (authn, rate limit).
  2. The Reservation Service generates a res_id, then does the write-ahead step first: it appends a PENDING reservation record to the durable Reservation Ledger (or to Redis AOF-backed state with a durable flag; see the deep dive on why ordering matters). Only after the hold intent is durably recorded does it touch the counter.
  3. It runs an atomic Lua script on Redis: check available:{sku} >= qty; if so, available -= qty and reserved += qty and record res:{res_id} with an expires_at. All in one atomic step. If not enough available, it returns “insufficient stock” and the ledger record is marked FAILED.
  4. On success the user is in checkout with a live hold and a TTL countdown. The service returns the res_id and expiry.

Commit flow (“payment succeeded”):

  1. The Payment Service emits a payment_succeeded{res_id} event (or the client calls POST commit with the res_id and an idempotency key).
  2. The Reservation Service runs an atomic op: if res:{res_id} is in state HELD, flip it to COMMITTED, and move the quantity reserved -= qty; committed += qty. available is untouched (those units already left available at reserve time). This is idempotent: a second commit for an already-COMMITTED res is a no-op returning success.
  3. The commit is persisted durably (ledger + Inventory DB committed), async via Kafka. The unit is now truly sold and will never be released.

Release / expiry flow (“payment failed / abandoned / timed out”):

  1. Explicit failure or abandonment calls release, or the TTL fires. Atomic op: if res:{res_id} is HELD, flip to RELEASED, and available += qty; reserved -= qty. The units are back for sale. Idempotent - a second release is a no-op.
  2. Expiry is covered two ways: Redis key TTL on res:{res_id} plus a reaper that sweeps the ledger for HELD records past expires_at and releases them. Belt and suspenders, because we cannot rely on an evicted key alone (durability).

The key insight: reserve and commit/release are a two-phase lifecycle where the atomic decision lives in memory but the intent is written durably first (write-ahead), so a crash between steps can always be reconciled from the ledger - we can replay what was held and reconcile against what was actually committed, and the conservation law is restored without ever double-selling. The counter is fast; the ledger is the truth; the reaper heals abandoned holds.

Component Deep Dive

The hard parts, naive-first then evolved: (1) the atomic reserve/commit/release lifecycle without overselling, (2) surviving a cache-node crash mid-checkout without losing or double-selling, (3) auto-expiring abandoned holds correctly, and (4) hot-SKU contention at 50k attempts/sec.

1. The reservation lifecycle: never oversell, never strand

The correctness core. Available must go down on reserve, stay down on commit, go back up on release/expiry, and never go negative or get double-counted.

Naive approach: decrement a DB column at payment time.

-- at payment success:
UPDATE inventory SET available = available - :qty WHERE sku_id = :sku;

Where it breaks:

  • The checkout gap oversells massively. Nothing is held while the user types their card. 10,000 users enter checkout for 500 units; all 10,000 saw “in stock”; the ones who pay all decrement. You oversell by thousands. The entire reason reservations exist is this gap.
  • No hold means no fairness. A user who committed to buying first has no protection; whoever’s payment clears first wins, and the rest get “sorry, sold out” after being charged (then refunded). Terrible experience.

First evolution: decrement at “Buy” (reserve on checkout entry), restore on abandon.

-- at checkout start:
UPDATE inventory SET available = available - :qty
 WHERE sku_id = :sku AND available >= :qty;      -- atomic compare-and-set
-- rows_affected == 1 -> held;  == 0 -> sold out
-- at abandon/failure: UPDATE inventory SET available = available + :qty ...

The AND available >= :qty makes the check-and-decrement one atomic conditional write, so available can never go negative - this kills the oversell race. Good. But two problems remain:

  • You cannot tell a held unit from a sold one. available dropped, but was that a committed sale or a hold that might come back? You have lost the distinction between reserved and committed. If the process crashes after decrementing and before you record why, you cannot tell whether to restore it. You need to track the hold as a first-class record, not just a number.
  • Abandoned carts leak forever. If the restore on abandon never fires (user closes the tab, the release call is lost, the server handling it dies), the unit is decremented with no record and no expiry. It is stranded - “sold out” with stock on the shelf. You need time-bounded holds that auto-return.
  • The hot row melts. Every reserve/commit/release on a hot SKU serializes on one DB row. At 50k attempts/sec that single row is a wall (a few thousand writes/sec max). Correct but not scalable.

Second evolution: a three-field model plus first-class reservation records, with the atomic op in memory.

Track three numbers per SKU and a record per hold:

on_hand    = physical units we have
available  = free to be reserved         (what shoppers can grab)
reserved   = held by in-flight checkouts (soft, time-bounded)
committed  = paid, awaiting fulfillment  (hard, never released)
invariant: on_hand = available + reserved + committed   (conservation)

The three state transitions, each one atomic operation:

RESERVE(sku, qty):   if available >= qty:  available -= qty; reserved += qty
                     create res{HELD, expires_at}
COMMIT(res):         if res.state == HELD: reserved -= qty; committed += qty
                     res.state = COMMITTED
RELEASE/EXPIRE(res): if res.state == HELD: reserved -= qty; available += qty
                     res.state = RELEASED

Run these on Redis with a Lua script so the check, the two counter mutations, and the reservation-state write happen as one atomic, single-threaded step - no interleaving, no partial application. Redis does hundreds of thousands of such scripts/sec per key, versus a few thousand for a DB row. The guards (available >= qty, res.state == HELD) make every transition a compare-and-set: you cannot oversell (reserve guarded on availability), cannot double-commit or double-release (both guarded on the HELD state - the first transition flips the state so the second is a no-op), and expiry versus late-commit race is resolved by whichever flips HELD first winning, atomically.

The Lua script for reserve, concretely:

-- KEYS[1]=avail:{sku} KEYS[2]=resv:{sku} KEYS[3]=res:{res_id}
-- ARGV[1]=qty ARGV[2]=res_id ARGV[3]=ttl_ms ARGV[4]=user_id
local avail = tonumber(redis.call('GET', KEYS[1]) or '0')
if avail < tonumber(ARGV[1]) then return {err='INSUFFICIENT'} end
redis.call('DECRBY', KEYS[1], ARGV[1])
redis.call('INCRBY', KEYS[2], ARGV[1])
redis.call('HSET', KEYS[3], 'sku', ..., 'qty', ARGV[1],
           'state', 'HELD', 'user', ARGV[4], 'expires_at', ...)
redis.call('PEXPIRE', KEYS[3], ARGV[3])
return {ok='HELD'}

This gives correctness and throughput. What it does not yet give is durability - Redis is memory, and a crash loses holds. That is the next problem, and it is the heart of the assignment.

2. Surviving a cache-node crash mid-checkout

Redis holds the live counters and reservation state in memory. A hot-SKU node crashes while 3,000 reservations are live and some are being committed. We must not (a) lose a reservation a customer is about to pay for, (b) forget a held unit and re-sell it, or (c) double-count on recovery.

Naive approach: just trust Redis, reload the counters from the DB on restart.

Where it breaks:

  • In-flight holds vanish. On restart you reload available from the Inventory DB, but every HELD reservation that lived only in Redis is gone. Two bad outcomes: a user who was mid-payment commits against a res_id that no longer exists (commit fails - lost sale after charging them), and the units those holds covered are now “available” again, so you re-sell units that were reserved - the exact double-sell we must prevent.
  • Counter drift. If the DB’s available was last synced before the crash, replaying it either restores stale values (ignoring recent commits) or loses recent reserves. The conservation law is violated and you cannot tell by how much.

First evolution: Redis AOF + replication.

Run Redis with AOF (appendfsync everysec or always for the critical path) and a replica with automatic failover. On a primary crash, the replica takes over with near-current state; AOF replays the last writes. This shrinks the loss window but does not close it: everysec can lose up to a second of writes, and async replication can lose the last few ops on failover. At 50k reserves/sec, a one-second gap is tens of thousands of holds - unacceptable for money-bearing state. Replication helps availability; it is not a durability guarantee for committed intent.

The answer: write-ahead the reservation to a durable ledger, then reconcile on recovery.

Treat the reservation like a database treats a transaction - write the intent durably before (or synchronously with) applying it to the fast counter, and make recovery a reconciliation against ground truth.

  • Write-ahead ordering. On reserve: first append a PENDING reservation record to the durable Reservation Ledger (a replicated store - the Inventory DB itself, or a dedicated durable log), then run the Redis atomic op, then mark the ledger record HELD. The ledger is the source of truth for “a hold was intended/granted”; Redis is the fast working copy.

  • Why this ordering survives a crash. Consider the failure points:

    • Crash after ledger PENDING but before Redis op: the hold was never applied to the counter, so no unit was removed. The reaper sees a PENDING record with no confirmed Redis hold, times it out, marks it FAILED. No unit lost, none double-sold.
    • Crash after Redis op but before ledger flips to HELD: Redis has the hold, the ledger has it as PENDING. On recovery we see a PENDING ledger record and a live Redis res; we reconcile them to HELD. The unit is correctly held.
    • Crash that loses Redis entirely: we rebuild Redis from the ledger plus the Inventory DB. available for a SKU is reconstructed as on_hand - committed - sum(qty of HELD reservations not yet expired). Because the ledger durably records every granted hold and the DB records every commit, the rebuild is exact - we re-create the reserved set from HELD records and recompute available by the conservation law. We can only ever under-count available (if a ledger write was in flight and lost, that hold simply never existed, which is safe), never over-sell.
  • Commit is the durable promotion. On payment success, commit writes COMMITTED to the ledger and increments committed in the Inventory DB durably (this is the one transition that can never be undone, so it must hit stable storage before we acknowledge the order as fulfilled-eligible). The Redis counter move (reserved -> committed) is the fast reflection; the DB write is the truth. If Redis dies after a durable commit, recovery reads COMMITTED from the ledger/DB and does not re-hold or re-sell that unit.

  • Reconciliation job. A periodic reconciler compares Redis counters against the ledger + DB and corrects drift: for each SKU, available_redis should equal on_hand - committed - active_held. Any mismatch (from lost ops, evictions) is repaired toward the durable ground truth. Because commits are durable and holds are logged, reconciliation can always restore the invariant and is biased to under-sell on uncertainty (fail closed).

The principle, regardless of implementation: the fast in-memory counter is a cache of a durable ledger, not the system of record. Every state-changing intent is durably recorded before or atomically with its fast application, and recovery recomputes the counters from the ledger and the committed truth. That is what lets a cache node die mid-checkout without ever double-selling a unit.

3. Auto-expiring abandoned holds

A soft reservation is time-bounded: if the user does not pay within the TTL (say 10 min), the units must return to available automatically. Abandonment is the common case (most carts are abandoned), so expiry is a high-volume, must-be-correct path, not an edge case.

Naive approach: rely on Redis key TTL to expire res:{res_id}.

PEXPIRE res:{res_id} 600000   -- key disappears in 10 min

Where it breaks:

  • Expiring the key does not return the units. When Redis evicts res:{res_id}, the reserved and available counters are not automatically adjusted - the key just vanishes. You have lost the hold record without crediting its quantity back to available. The unit is now stranded (reserved count stuck high, available stuck low, with no record to fix it). Key TTL deletes the record; it does not run your release logic.
  • No durability. An evicted Redis key leaves no trace for the durable ledger. The ledger still shows HELD forever. Conservation is broken.
  • Keyspace-notification races. You could listen to Redis keyspace expiry events and run release on the notification, but those events are best-effort (dropped under load, lost on failover) - exactly when a flash sale is hammering the node. You cannot hang correctness on them.

The answer: a reaper sweeping the durable ledger, plus lazy expiry on access, with key-TTL only as an optimization.

  • Reaper (authoritative). A background job periodically queries the Reservation Ledger for records where state = HELD AND expires_at < now(), and for each runs the same atomic RELEASE transition (idempotent): flip ledger HELD -> EXPIRED, and in Redis available += qty; reserved -= qty guarded on the HELD state. Because release is idempotent and guarded, it is safe even if the reaper runs twice or races a commit. The reaper is the authority on expiry because it reads durable state, so an evicted Redis key cannot hide an unexpired hold.

  • Lazy expiry on access. When any reserve/commit touches a SKU, cheaply check if the touched reservation is past expires_at and, if so, release it inline before proceeding. This keeps hot SKUs tight without waiting for the reaper’s next sweep - the moment someone tries to grab a unit on a hot SKU, stale holds for that SKU are swept first.

  • Expiry versus late-commit race (the subtle one). A user pays at second 599 while the reaper fires at second 601. Whichever atomic transition flips the ledger/Redis state from HELD first wins; the second sees a non-HELD state and no-ops. If commit wins, the sale stands (we honor the paid customer - we may even allow a short grace window past TTL for in-flight payments). If expiry wins and the payment then succeeds, the commit finds the res EXPIRED and must reconcile: either re-reserve if stock still exists (preferred, since the customer paid), or fail the order and refund (fail closed if stock is gone). The guard makes the race deterministic; business policy (honor paid customers, grace window) resolves the human-facing outcome.

  • TTL tuning. Short TTLs (2-3 min) free stranded stock fast and improve conversion under scarcity but risk expiring a slow-but-real payment; long TTLs (15 min) are customer-friendly but strand scarce inventory during a sale. During flash sales we shorten the TTL so abandoned holds recycle quickly into available. State the trade-off: TTL length trades inventory liquidity against payment-completion headroom.

4. Hot-SKU contention at 50k attempts/sec

A single hot SKU sees 50k+ reserve attempts/sec against a few thousand units, with most attempts failing. The per-key atomic op, even in Redis, becomes the bottleneck and the failure domain.

Naive approach: one Redis key per SKU, all reserves serialize on it.

Where it breaks:

  • Single-key throughput ceiling. Redis is single-threaded per key; a hot available:{sku} tops out around a few hundred thousand simple ops/sec, less for a Lua script doing several ops. At 50k reserve attempts/sec per SKU across 200 SKUs (10M/s aggregate) with payment commits and reaper releases layered on, the hottest keys saturate and latency spikes past the 100ms budget.
  • Single failure domain. If the node owning a hot SKU’s key dies, that SKU’s entire checkout stops until failover.
  • Wasted work on losers. 47k of 50k attempts/sec just want to hear “sold out” but each still runs the full Lua script and touches the hot key.

The answer: shed losers early, then shard the hot counter across stock buckets.

  • Edge-shed the sold-out flood. Once a hot SKU hits zero available, set an edge-cached soldout:{sku} flag (1s TTL). The CDN/gateway answers the ~47k/s losers with a cached “sold out” without touching Redis. This is the single biggest relief - most of the 10M/s aggregate never reaches the decision plane. Only requests with a real chance of success proceed.

  • Shard the counter into stock buckets. Split a hot SKU’s available into K sub-counters (e.g. 3,000 units into 30 buckets of 100 each) spread across the Redis cluster: avail:{sku}:{bucket}. A reserve hashes to a random bucket and runs the atomic op there. Throughput multiplies by K; the sum of bucket availabilities is the true availability, so the global stock is still exact (you cannot oversell a bucket, bucket caps sum to on_hand). This is the same sharded-counter trick as a fungible flash-sale counter, applied per hot SKU.

  • Retry-on-empty to avoid stranded buckets. If a reserve hits an empty bucket while others have stock, it retries another random bucket (bounded hops) before returning sold-out, so the last few units are not stranded in unlucky buckets. A user sees “sold out” only when several random buckets are empty - genuinely near-zero.

  • Only hot SKUs need sharding. The 10M cold SKUs stay as a single counter each (their traffic is trivial). A control signal promotes a SKU to “sharded/hot” mode when its attempt rate crosses a threshold, and demotes it after the sale. You pay the sharding complexity only for the ~200 SKUs that need it.

  • Stateless, autoscaled Reservation Service. The service itself holds no state (all state is in Redis + ledger), so it scales horizontally behind the LB to absorb connection load; the real contention is on the keys, which sharding addresses.

The elegant part: the finite stock (a few thousand units) bounds the real work no matter how many attempt it. The edge sheds the sold-out majority, bucket-sharding spreads the surviving contention, and only the bounded set of successful reserves flows to the durable ledger. Demand can be 50k/s; useful work is bounded by the units that exist.

API Design & Data Schema

The availability read is a cacheable REST endpoint; reserve/commit/release are strongly-consistent, idempotent operations keyed by res_id and an idempotency key.

REST endpoints

GET /api/v1/inventory/{sku}/availability?qty=1
  -> { sku, available_approx: 240, in_stock: true }     (edge-cached, ~1-2s TTL)

POST /api/v1/reservations
  headers: Authorization: <user token>, Idempotency-Key: <client key>
  body: { items: [ { sku, qty } ], ttl_seconds: 600 }
  -> 201 { res_id, state:"HELD", expires_at, items:[...] }     (held, all-or-nothing)
  -> 409 { state:"INSUFFICIENT_STOCK", sku, available: 2 }     (not enough units)

POST /api/v1/reservations/{res_id}/commit
  headers: Idempotency-Key: <client/payment key>
  body: { payment_ref }
  -> 200 { res_id, state:"COMMITTED" }                         (idempotent; second call = same)
  -> 409 { state:"EXPIRED" }                                   (hold lapsed; reconcile/refund)

POST /api/v1/reservations/{res_id}/release
  headers: Idempotency-Key: <client key>
  -> 200 { res_id, state:"RELEASED" }                          (idempotent)

GET /api/v1/reservations/{res_id}
  -> { res_id, state, items, expires_at }

POST /api/v1/inventory/{sku}/restock        (admin / WMS)
  body: { delta: 500 }
  -> 200 { sku, on_hand, available }

reserve is all-or-nothing across its line items: the service reserves each SKU and, if any line fails, releases the ones already held (a compensating release - a tiny saga) and returns INSUFFICIENT_STOCK, so a cart never half-reserves. Every mutating call carries an Idempotency-Key so client/network retries never double-apply; a retried commit returns the existing COMMITTED result rather than committing twice.

Data stores - the right tool per job

1. Hot counters + reservation index - Redis, in-memory, atomic (Lua). The contended front line, a cache of the ledger.

avail:{sku}            -> integer available            (cold SKUs: one key)
avail:{sku}:{bucket}   -> integer available per bucket  (hot SKUs: K sharded keys)
resv:{sku}             -> integer reserved
res:{res_id}           -> hash { sku, qty, state, user, expires_at }, PEXPIRE = ttl
soldout:{sku}          -> bool flag, edge-cached, set when available hits 0

Redis is chosen because the reserve/commit/release decision must resolve in microseconds under tens of thousands of concurrent ops per SKU, and single-threaded-per-key Lua gives multi-step atomicity for free. A durable per-request DB write on the hot path would melt. Redis runs AOF + replication so it is durable-ish and highly available, but it is explicitly a cache of the ledger, not the truth.

2. Reservation Ledger - durable source of truth for holds (SQL, sharded by sku_id).

The ledger needs strong per-row consistency, a clean state machine with guarded transitions, secondary lookups (by user_id, by expires_at for the reaper), and absolute durability for money-bearing intent. This is a textbook relational fit: the transitions are a small state machine with invariants best expressed as constraints, and the reaper’s WHERE state='HELD' AND expires_at < now() query wants a real index. We shard by sku_id so hot SKUs spread across shards.

Table: reservations            (SQL, PK = res_id, sharded by sku_id)
  res_id       UUID        PRIMARY KEY
  sku_id       STRING      NOT NULL          -- shard key
  user_id      STRING      NOT NULL
  qty          INT         NOT NULL CHECK (qty > 0)
  state        ENUM(PENDING, HELD, COMMITTED, RELEASED, EXPIRED, FAILED) NOT NULL
  idempotency_key STRING   NOT NULL
  payment_ref  STRING      NULL
  expires_at   TIMESTAMP   NOT NULL
  created_at   TIMESTAMP   NOT NULL
  updated_at   TIMESTAMP   NOT NULL
  UNIQUE (idempotency_key)                   -- retries map to the same reservation
  INDEX (sku_id, state)                      -- rebuild/reconcile per SKU
  INDEX (state, expires_at)                  -- the reaper's sweep
  INDEX (user_id, state)                     -- "my active holds"
  -- State machine: PENDING->HELD->{COMMITTED | RELEASED | EXPIRED}, PENDING->FAILED
  -- Transitions are guarded (optimistic): UPDATE ... WHERE res_id=? AND state='HELD'

3. Inventory DB - authoritative sellable stock (SQL).

Table: inventory              (SQL, PK = sku_id)
  sku_id       STRING      PRIMARY KEY
  on_hand      INT         NOT NULL          -- physical units
  committed    INT         NOT NULL DEFAULT 0 -- paid, awaiting fulfillment
  version      BIGINT      NOT NULL           -- optimistic-lock version
  updated_at   TIMESTAMP   NOT NULL
  CHECK (on_hand >= committed)
  -- available is DERIVED: on_hand - committed - sum(HELD qty).
  -- Redis caches `available`; this table + reservations ledger are the truth.
  -- Optimistic locking on commit/restock:
  --   UPDATE inventory SET committed = committed + :q, version = version + 1
  --    WHERE sku_id = :sku AND version = :expected_version;

Why Redis for counters but SQL for the ledger and inventory: opposite needs. The counter is ephemeral, violently contended, and must resolve in microseconds - a durable write per reserve at 50k/s is impossible, so an in-memory atomic store owns it. The ledger and inventory are money-bearing records that must survive crashes, enforce a state machine with guarded transitions, and answer the reaper’s indexed sweep - loss is unacceptable, so a replicated relational store owns them. Optimistic locking (the version column / guarded WHERE state='HELD' updates) handles the lower-rate commit/restock writes without pessimistic row locks, so concurrent commits either succeed with a version bump or retry on conflict. The fast decision promotes into the durable record via the async stream; matching the store to the job is the whole schema decision.

Durability of the counter (the subtle bit). Redis is the live counter, but a crash must not double-sell. Defenses: (1) AOF + replication shrink the loss window; (2) every hold is write-ahead-logged to the ledger before the Redis op; (3) commits are durably written to the Inventory DB before order-fulfillment ack; (4) on recovery, Redis available is recomputed as on_hand - committed - sum(active HELD qty) from the durable stores. Because the durable committed count and the durable HELD set are ground truth, recovery reconstructs counters exactly and can only ever under-sell on uncertainty - never over-sell.

Bottlenecks & Scaling

Where it breaks first, in order, and the fix for each:

1. Overselling across the checkout gap (the correctness bottleneck, breaks first logically). Many users enter checkout for scarce units with nothing held. Fix: a time-bounded soft reservation at checkout entry - an atomic guarded decrement (available >= qty then available -= qty; reserved += qty) in Redis Lua - so held units leave the available pool immediately and the gap cannot oversell. Available can never go negative because the check and the take are one atomic op.

2. Hot-key / hot-row on a popular SKU. One counter cannot take 50k reserves/sec plus commits and releases. Fix: bucket-shard the hot SKU’s counter into K sub-counters across the Redis cluster (bucket caps sum to on_hand, so stock stays exact), with retry-on-empty to avoid stranded units. Only hot SKUs are promoted to sharded mode; cold SKUs stay single-key.

3. Cache-node crash mid-checkout. Redis dies with thousands of live holds; losing them double-sells or strands. Fix: write-ahead every hold to the durable ledger before the Redis op, write commits durably before fulfillment ack, and on recovery recompute counters from the ledger + Inventory DB (available = on_hand - committed - active_held). Recovery is exact and biased to under-sell. AOF + replication shrink the live-loss window.

4. Abandoned carts stranding inventory. Most holds never convert; if they do not return, stock shows sold-out with units on the shelf. Fix: time-bounded holds auto-returned two ways - a ledger-driven reaper (WHERE state='HELD' AND expires_at < now()) running the idempotent release, plus lazy expiry on access for hot SKUs. Redis key TTL is only an optimization, never the authority (it deletes the record without crediting units).

5. The sold-out request flood. ~47k of 50k/s per hot SKU just want “sold out.” Fix: an edge-cached soldout:{sku} flag (1s TTL) so the CDN/gateway answers losers without touching Redis, shedding the bulk of the 10M/s aggregate before the decision plane.

6. Double commit / double release from retries and races. Network retries or a reaper-vs-payment race could apply a transition twice. Fix: idempotent, guarded transitions - commit and release both check state == HELD and flip it atomically, so the second application no-ops; plus a UNIQUE(idempotency_key) in the ledger so retried calls map to the same reservation. The expiry-vs-late-commit race is deterministic (first to flip HELD wins) with a grace window honoring in-flight payments.

7. Durable-write throughput / hot path blocking on disk. Persisting every commit/release synchronously on the hot path would slow reserves. Fix: decide in memory, persist async via Kafka for commit/release reflection into the Inventory DB, with the reserve write-ahead being the one synchronous durability point (small and bounded by actual stock). The DB sees a trickle bounded by real units, not by demand.

8. Commit/restock write contention. Concurrent commits and restocks on the same SKU row. Fix: optimistic locking (version column) on the Inventory DB - concurrent writers bump the version or retry on conflict, avoiding pessimistic locks. Commit rate is far below reserve rate (only ~40% convert), so this row is not the hot path.

9. Multi-item cart partial reservation. A cart reserves 2 of 3 SKUs then the third is sold out. Fix: all-or-nothing reserve as a small saga - on any line failure, compensate by releasing the already-held lines, so a cart never half-holds or charges for a partial order.

10. Single points of failure. Fix: Redis replicated with automatic failover; the ledger and Inventory DB replicated across AZs and sharded by sku_id; Reservation Service stateless and autoscaled; the edge globally distributed. The system fails closed - if availability cannot be confirmed, refuse the reserve, so uncertainty under-sells rather than oversells.

11. Hot-shard skew during a sale. A handful of SKUs dominate; their shards concentrate on a few Redis nodes. Fix: spread a hot SKU’s buckets across different cluster nodes (bucket key includes a spread salt), monitor per-key QPS, and rebalance hot buckets off saturated nodes. Promotion-to-hot is driven by observed attempt rate.

Wrap-Up

The trade-offs that define this design:

  • Two-phase soft-then-hard reservation over a one-way counter. Stock is reserved at checkout entry and only committed after payment, so the checkout gap cannot oversell, and abandoned holds flow back. We accept a richer state machine (HELD -> COMMITTED | RELEASED | EXPIRED) and a conservation invariant in exchange for never selling a unit we cannot deliver.
  • In-memory atomic decision, durable ledger as truth. The reserve/commit/release decision is a Redis Lua op for microsecond latency at 50k/s, but Redis is explicitly a cache of a durable ledger. Every hold is write-ahead-logged and every commit is durably persisted, so a cache node dying mid-checkout is reconciled from the ledger and never double-sells. We trade some write-ahead latency on reserve for crash safety on money-bearing state.
  • Reaper-authoritative expiry over key-TTL. Abandoned holds self-heal via a ledger-driven reaper plus lazy expiry, not Redis key expiry (which would delete the record without crediting units). We pay for a sweep job to guarantee conservation holds even across evictions and failovers.
  • Bucket-sharded hot SKUs over uniform single counters. Only the ~200 hot SKUs are sharded into stock buckets (caps summing to on_hand) with retry-on-empty; cold SKUs stay simple. We buy throughput and fault isolation for the few keys that need it, at the cost of sub-percent tail-stranding smoothed by retry.
  • Fail closed. When availability is uncertain (recovery, drift, a drained bucket after retries), refuse the reserve. We may lose a handful of conversions at the tail, but we never commit a unit we cannot ship.

One-line summary: an inventory system where availability display is a cheap approximate edge-cached read, overselling is prevented by a time-bounded soft reservation that atomically moves units from available to reserved in a Redis Lua op, every hold is write-ahead-logged to a durable sku_id-sharded ledger so a cache crash recomputes counters exactly (available = on_hand - committed - active_held) and never double-sells, holds convert to hard committed sales only after payment and otherwise auto-return via a ledger-driven reaper, and hot SKUs are bucket-sharded with sold-out floods shed at the edge so demand can be 50k/s while useful work stays bounded by the units that actually exist.