E-Commerce Catalog, Dynamic Pricing, and Stock Reservation System
Medium · System Design · Software Engineer · Onsite
Prompt
Design the core Catalog, Dynamic Pricing, and Inventory backend for a large online retailer. Shoppers continuously load item pages and multi-item search grids displaying product attributes, active selling prices, and stock badges. Meanwhile, merchandising staff and automated repricing services adjust base prices and promotional discounts, and a downstream checkout service verifies unit prices and reserves physical units when customers place orders.
Your system must meet the following functional and operational requirements:
- Core operations: Serve single-SKU and batch product views (descriptive metadata, effective price, and stock status); process authenticated, role-authorized pricing and promotion changes with a complete audit log; and atomically lock and deduct stock at checkout while returning held stock if payment fails or expires.
- Target scale & latency:
20,000,000active SKUs in the catalog.100,000QPS peak browsing read load withp99 < 25 msresponse latency.2,000operations/s peak write and reservation load under normal traffic, plus single-SKU "flash-sale" surges up to10,000QPS on one hot item.
- Consistency & security: Storefront browsing views may reflect eventual consistency within a few seconds, whereas checkout must guarantee tamper-proof price verification and zero overselling. Administrative and automated write endpoints require strict authentication and role-based access control.
Scope & Expectations
- API contracts & concurrency headers: Define browsing, back-office pricing, warehouse adjustment, and checkout quote/reservation endpoints, incorporating idempotency keys and optimistic version checks.
- Polyglot storage & partitioning: Contrast relational and NoSQL stores across flexible catalog specs, audited pricing tables, and high-concurrency inventory ledgers, and specify sharding keys.
- Multi-tier caching & hot-SKU contention: Detail CDN, in-process, and distributed cache layers plus race-free invalidation to hit
p99 < 25 ms, alongside contention control for10,000QPS single-SKU flash sales. - Checkout integrity & failure recovery: Walk through preventing stale or manipulated client prices, coordinating multi-item reservations, and reliably reclaiming stock from failed payments or abandoned checkouts.
Step-by-step walkthrough
Clarify requirements and state the core rule
Start by separating the two completely different workloads hiding inside this system. Browsing needs massive speed (100,000 requests per second) and tolerates data that is a second or two old. Checkout runs at much lower volume (2,000 writes per second normally) but demands bank-vault accuracy: we must never charge a customer a tampered or silently changed price, and we must never oversell (promise the last unit in a warehouse to two shoppers at the same time).
State the guiding rule up front: serve browsing entirely from multi-tier memory caches using coarse availability badges, and run checkout price quotes and stock reservations strictly against primary databases.
Key terms we will use
- SKU (Stock Keeping Unit): a unique ID for each distinct purchasable product variant (for example,
shoe-air-blue-10, not just "running shoe"). - QPS (Queries Per Second): how many requests hit the service each second.
- p99 latency: the 99th-percentile response time, meaning 99 out of every 100 requests finish faster than this target.
- TTL (Time-To-Live): an automatic expiration window after which a cached value or temporary reservation expires.
Functional requirements
- Get product details: return catalog metadata (title, attributes, image URLs), the current active price, and an availability badge (
IN_STOCK,LOW_STOCK, orOUT_OF_STOCK) for either one SKU or a batch of SKUs (search and category pages render 20–50 product tiles at once). - Update pricing with auditability: accept base-price updates and scheduled promotional discounts from human merchandisers and automated pricing engines, recording who changed what, when, why, and the old and new values.
- Lock a price quote at checkout: verify and freeze the customer's unit prices when they confirm their cart so browser-side tampering or background repricing cannot surprise them at payment.
- Reserve, commit, and release inventory: atomically hold stock at checkout start, permanently deduct it when payment succeeds, and return it to available stock if payment fails or the shopper abandons their cart.
- Warehouse adjustments: record receiving shipments, damaged goods, and physical cycle counts (strictly role-authorized).
Non-functional requirements and explicit assumptions
- Scale: 20 million active SKUs; 100,000 read QPS peak with p99 < 25 ms; 2,000 checkout write QPS peak, plus 10,000 QPS bursts on a single "flash-sale" SKU.
- Money representation: store all prices in integer minor units (for example,
$24.99is stored as2499cents) in a single currency (USD) to start, avoiding binary floating-point rounding bugs (0.1 + 0.2 != 0.3). - Active price rule: active price = base price minus the single best active promotion (no coupon stacking here; user-specific promo codes belong to the downstream cart/order service). A checkout price quote is honored for 15 minutes unless an operator explicitly revokes a broken price (such as a
$1,000TV accidentally listed for$10). - Reservation window: a checkout reservation holds stock for 15 minutes and can be extended once (+5 minutes) while a slow payment provider finishes processing.
- SKU (Stock Keeping Unit): a unique ID for each distinct purchasable product variant (for example,
Back-of-the-envelope numbers
Estimate storage, memory, read lookups, and single-row contention so every architectural choice comes directly from math.
Storage & memory footprint (20M active SKUs) Static catalog metadata 20M x ~5 KB (title, specs, image URLs) = ~100 GB Price rows 20M x ~200 B = ~4 GB (+ append-only audit log) Inventory rows 20M x ~100 B = ~2 GB (+ append-only ledger) Redis volatile cache 20M keys x ~200 B (payload + key overhead)= ~4 GB across primaries -> ALL 20M active prices + badges fit in RAM (~8 GB with replicas)! Read traffic (100,000 QPS peak) Assume 70% single-SKU product views (70k QPS x 1) + 30% search/category tile batches (30k QPS x 20 SKUs) Total SKU lookups 70,000 + 600,000 = 670,000 SKU lookups/s Redis cluster sizing at ~60,000 lookups/s per primary -> 12 primaries + 12 replicas Stateless read pods at ~4,000 HTTP req/s per pod -> 25 pods (run 35 for headroom) Write traffic (2,000 ops/s normal peak) ~1,000 checkouts/s x 2 phases (reserve, then commit or release) = 2,000 reservation ops/s At ~3 SKUs per cart ~3,000 row updates/s to reserve + ~3,000 row updates/s to commit/release = ~6,000 SQL row updates/s Across 8 SQL shards 6,000 / 8 = ~750 row updates/s per shard Reservation history ~5M checkouts/day x 300 B = 1.5 GB/day -> ~135 GB for 90 days hot retention The flash-sale bottleneck (10,000 QPS on ONE SKU) A database updates a single row one transaction at a time under a row lock. With ~1-5 ms per synchronous commit, ONE row tops out at ~200-1,000 updates/s. 10,000 attempts/s on one row is 10x-50x beyond what a single database row can serialize!Three concrete design lessons fall straight out of these numbers:
- Reads are pure memory work: 670,000 SKU lookups per second must be answered from RAM (
< 2 msnetwork hop), leaving databases to handle only writes and rare cache misses. - Normal checkout writes are modest: 750 row updates per second per shard is comfortable for PostgreSQL when spread across millions of SKUs.
- Flash sales are a single-row lock contention problem, not a cluster capacity problem: adding more database shards does not split one SKU row. Since 99% of those 10,000 requests/s must fail anyway once stock runs out, we need a fast in-memory gatekeeper that rejects losers before they touch the database.
- Reads are pure memory work: 670,000 SKU lookups per second must be answered from RAM (
API design, idempotency, and authorization
Every state-changing endpoint requires an idempotency key—a unique client-generated identifier (like a UUID or
checkout_id) stored with the operation so that if a network timeout triggers a retry, the server safely returns the original result instead of reserving stock or updating prices twice.Price edits also use optimistic concurrency control via the HTTP
If-Matchheader: the caller sends thebase_versionnumber it last read, and the database updates the price only ifbase_versionhas not changed in the meantime, preventing a pricing engine and a human merchandiser from silently overwriting each other.1. Browsing APIs (public, read-only, cacheable) GET /v1/products/{sku} -> 200 { sku, title, attributes, media_urls, price: { amount_cents: 2499, currency: "USD", price_version: 41, valid_until: "..." }, availability: { status: "IN_STOCK" | "LOW_STOCK" | "OUT_OF_STOCK", as_of: "..." } } POST /v1/products:batchGet { skus: ["sku-1", ... up to 50] } 2. Pricing & Merchandising APIs (authenticated; OAuth scope prices:write) PUT /v1/prices/{sku} Headers: Idempotency-Key: <uuid>, If-Match: "18" Body: { base_amount_cents: 2399, reason: "competitor_match", source: "pricing-bot" } -> 200 { sku, base_version: 19 } -> 412 PRECONDITION_FAILED { current_base_version: 20 } # concurrent edit detected -> 422 GUARDRAIL_TRIPPED { rule: "max_drop_30_pct" } # routed for human approval POST /v1/prices:batchUpdate { updates: [... up to 1,000 SKUs] } POST /v1/promotions { sku_set_id, discount_pct: 15, starts_at, ends_at } 3. Checkout & Reservation APIs (internal mTLS; called only by Order Service) POST /v1/quotes Body: { cart_id, user_id, items: [{ sku, qty }] } -> 201 { quote_id, user_id, items: [{ sku, qty, unit_cents, price_version }], total_cents, expires_at, key_id, hmac_signature } POST /v1/reservations Headers: Idempotency-Key: <checkout_id> Body: { quote: {...signed quote...}, items: [{ sku, qty }] } -> 201 { reservation_id, status: "HELD", expires_at } -> 409 INSUFFICIENT_STOCK { failed_sku, available } -> 409 QUOTE_INVALID { reason: "EXPIRED" | "REVOKED" | "BAD_SIGNATURE" } POST /v1/reservations/{id}:extend # +5 min once while payment gateway is still pending POST /v1/reservations/{id}:commit # payment succeeded -> moves reserved to committed POST /v1/reservations/{id}:release # payment failed or user canceled -> returns stock 4. Warehouse Adjustment API (internal; OAuth scope inventory:adjust) POST /v1/inventory/{sku}/adjustments Headers: Idempotency-Key: <warehouse_event_id> Body: { delta: +120, reason: "RECEIVING" | "SHIP" | "DAMAGE", ref_id: "PO-7781" }Why we track two separate price version numbers:
base_versionincrements only when someone edits the base price inPUT /v1/prices/{sku}, so editors usingIf-Matchdo not collide with scheduled promotions.price_versiontracks the derived customer-facing active price and increments whenever either the base price changes or a promotion starts or ends; checkout quotes carryprice_version.Authentication and role authorization: internal microservices authenticate using mTLS (mutual TLS, where both client and server verify cryptographic certificates) plus narrow OAuth client scopes (
reservations:write,prices:write). Human merchandisers log in via corporate Single Sign-On (SSO) with RBAC (Role-Based Access Control) scoped to their product category, and automated drops exceeding 30% or falling below unit cost require a second human approver.Data model: SQL vs. NoSQL and partitioning
Split storage by how data changes and what consistency it requires. Static product specs vary wildly between laptops, lipsticks, and sofas and never participate in money or stock transactions; prices and stock have tiny, fixed schemas and demand ACID transactions (database operations guaranteed to succeed or roll back as a single indivisible unit).
Dataset Access pattern Storage choice Why SQL vs. NoSQL here Catalog metadata (~100 GB) Read-heavy, flexible per-category attributes, key lookup by skuNoSQL Document Store (e.g., DynamoDB / MongoDB), partitioned by hash(sku)Flexible JSON schema per category; horizontal key-value reads; needs no multi-row joins or locks Prices & promotions (~4 GB + history) Moderate writes (~1,000/s peak), strict audit trail Relational SQL (PostgreSQL), single primary + read replicas Atomic transaction across prices,price_history, andoutbox; rich SQL queries for financial auditsInventory & reservations (~2 GB + ledger) High concurrency (~6,000 updates/s), zero negative stock Sharded Relational SQL (8 PostgreSQL shards), partitioned by hash(sku)Conditional UPDATE,CHECK (available >= 0)guardrails, and atomic writes across stock + reservation item + ledgerRelational schemas and invariants
-- Price Database (single PostgreSQL primary + replicas) prices (sku PK, base_cents, currency, base_version, updated_at, updated_by) price_history (sku, base_version, old_cents, new_cents, reason, source, principal_id, request_id, created_at, PRIMARY KEY (sku, base_version)) -- append-only! promotions (promo_id PK, sku_set_id, discount_type, discount_val, starts_at, ends_at) active_price (sku PK, active_cents, price_version, valid_from, valid_until, revoked_below_version) outbox (event_id PK, topic, partition_key, payload_json, created_at) -- Inventory Database (8 PostgreSQL shards, sharded by hash(sku)) inventory (sku PK, available INT, reserved INT, committed INT, version BIGINT, CHECK (available >= 0 AND reserved >= 0 AND committed >= 0)) reservation_items (reservation_id, sku, qty INT, state TEXT, -- 'HELD', 'COMMITTED', 'RELEASED' PRIMARY KEY (reservation_id, sku)) inventory_ledger (entry_id PK, sku, d_available INT, d_reserved INT, d_committed INT, reason TEXT, ref_id TEXT, created_at, UNIQUE (reason, ref_id, sku)) outbox (event_id PK, topic, partition_key, payload_json, created_at) -- Reservation Coordinator Table (lives on Inventory shards, partitioned by hash(reservation_id)) reservations (reservation_id PK, checkout_id UNIQUE, status TEXT, settled BOOL, quote_id TEXT, expires_at TIMESTAMPTZ, created_at TIMESTAMPTZ) -- status: 'PENDING' -> 'HELD' -> 'COMMITTED' | 'RELEASED' | 'EXPIRED' -- INDEX (status, expires_at) for fast abandoned-cart sweepingPhysical stock accounting equation: at every moment for every SKU,
available (free to sell) + reserved (held in active checkouts) + committed (paid, awaiting ship) = physical units on hand in the warehouseReserving moves units from
availabletoreserved; committing payment movesreservedtocommitted; releasing an abandoned cart movesreservedback toavailable; and when the warehouse physically ships the box, aSHIPadjustment subtractsqtyfromcommitted. Every single movement appends an immutable row toinventory_ledger, just like bank statement lines summing to your account balance.What is the
outboxtable? If a service updated PostgreSQL and then tried to publish a cache-invalidation message to Kafka directly, a server crash between those two steps would leave Redis permanently stale. Writing anoutboxrow inside the exact same SQL transaction guarantees the event is saved if and only if the database change succeeded; a lightweight relay process tails the outbox and forwards events to Kafka at-least-once.High-level architecture
BROWSING READ PATH (100,000 QPS, p99 < 25 ms) Customer Browser / App | v +--------------+ Static metadata & images (TTL 5 min + purge on catalog edit) | CDN |---------------------------------------------------+ +------+-------+ | | Dynamic fetch (price + availability badge) v v +-----------------+ +--------------+ +---------------------------------+ | Document Store | | API Gateway |---->| Product Read Service (35 pods) | | (20M SKU specs) | | TLS, rate | | L1 local RAM cache (hot, 1s TTL)| +-----------------+ +--------------+ +--------+------------------+-----+ | 670k lookups/s | rare cache miss (single-flight) v v +-----------------+ +-------------------------------+ | Redis Cluster | | Price & Inventory SQL Replicas| | 12 primaries | +-------------------------------+ | (4 GB, no TTL) | +--------^--------+ | Lua set-if-newer-version +--------+--------+ | Cache Projector |<-- Kafka (price-events, badge-events) +-----------------+ ^ | outbox relay CHECKOUT & BACK-OFFICE WRITE PATH | Merchandising / +-----------------+ +-------+--------------+ Pricing Bots ------->| Pricing Service |--->| Price DB (Primary) | | updates, quotes | | prices, history, ... | +--------^--------+ +----------------------+ | 1. POST /quotes +--------+--------+ +----------------------+ Customer Checkout -->| Order Service |--->| Inventory Service | +--------+--------+ +---+--------------+---+ | 2. reserve / | | hot SKUs only | commit v v | +---------------+ +------------------+ +--------+------+ | Inventory DB | | Flash-Sale Gate | | Expiry Sweeper|->| (8 SQL shards)| | (Redis + Lua) | +---------------+ +---------------+ +------------------+- Browsing read flow: static descriptions and photos come straight from the CDN (Content Delivery Network: geographically distributed edge servers close to shoppers). For dynamic price and availability, the Product Read Service checks its tiny 1-second local RAM cache (for viral items), then pipelines a lookup to the 12-shard Redis cluster, touching database read replicas only if a cache shard just restarted.
- Write & invalidation flow: Pricing and Inventory services commit strictly to their SQL primaries alongside an
outboxrow. An outbox relay streams those events through Kafka to the Cache Projector, which updates Redis without ever overwriting newer versions with delayed older messages.
Deep dive 1: Low-latency browsing and race-free cache invalidation
Hitting p99 < 25 ms at 670,000 SKU lookups per second requires eliminating cache misses, hot-key bottlenecks, and out-of-order cache updates.
Four defensive layers on the read path
- CDN edge caching (static data): product titles, descriptions, and image URLs change rarely. Caching them at the CDN for 5 minutes with stale-while-revalidate (serving slightly expired content instantly while refreshing it in the background) plus explicit purge events on catalog edits offloads 95%+ of response bandwidth.
- In-process L1 cache (1-second TTL for hot keys): if a celebrity tweets a link to one sneaker, 50,000 QPS hitting a single Redis key (
p:shoe-99) would overwhelm the single CPU core of that one Redis shard. Keeping the top 2,000 hottest SKUs in each read pod's local memory for 1 second caps Redis load for that viral sneaker at35 pods × 1 read/s = 35 reads/s. - Pre-warmed Redis L2 cluster with zero TTL eviction: because all 20 million
{active_cents, price_version, valid_until, badge, stock_version}records take only ~4 GB across 12 primaries, we store every active SKU permanently in Redis without a TTL. Why no TTL? Setting a 10-minute TTL on 20 million long-tail SKUs would force20,000,000 / 600 s = ~33,000 database misses/sall day long for products whose price never changed! - Single-flight request coalescing on misses: if a newly created SKU is requested by 500 users simultaneously before the projector populates Redis, single-flight ensures each pod sends 1 query to the read replica and shares that single result across all 500 waiting threads instead of stampeding the database.
Keeping Redis fresh without out-of-order bugs
- Version-guarded Lua updates: Kafka consumers can process partitions at different speeds or replay messages after a restart. Instead of plain
SET, the Cache Projector runs an atomic 4-line Redis Lua script that updates price fields only ifincoming.price_version > cached.price_version(and updates badge fields only ifincoming.stock_version > cached.stock_version). Stale replayed events become harmless no-ops. - Badge threshold filtering (100x fewer events): inventory changes 6,000 times per second, but shoppers only see
IN_STOCK(available > 10),LOW_STOCK(1 <= available <= 10), orOUT_OF_STOCK(available == 0). The Inventory Service writes abadge-eventsoutbox row only whenavailablecrosses10or0, slashing Redis writes from 6,000/s to a few dozen per second. - Scheduled promotion boundaries (
valid_until): when a promotion is scheduled to start or end at00:00:00,active_pricestoresvalid_until = 00:00:00. At00:00:01, even before the background promotion worker finishes pushing new Redis values, read pods seenow > valid_untiland treat the entry as expired, fetching the fresh price on demand. - Self-healing background scrubber: in case an asynchronous Redis failover drops a few milliseconds of writes, post-failover Kafka replay (last 5 minutes) plus a low-priority hourly replica scan (
20M / 3,600 s = ~5,600 rows/s) re-appliesset-if-newer, guaranteeing bounded eventual consistency.
End-to-end p99 latency budget: API Gateway (
~2 ms) + Read Pod logic (~3 ms) + parallel pipelined RedisMGETacross at most 12 shards (~2 msp99) + JSON serialization (~1 ms) =~8 mson cache hit, and~18 mson replica fallback — comfortably inside the 25 ms p99 target.Deep dive 2: Atomic stock reservation, multi-item carts, and flash sales
Why naive code oversells, and how conditional SQL prevents it
A beginner often writes two separate queries:
SELECT available FROM inventory WHERE sku = 'X', checksif available >= qtyin Python, and then runsUPDATE inventory SET available = available - qty. Under concurrency, two threads both readavailable = 1at the same millisecond, both pass the Pythonif, and both subtract1— selling 2 units of the last item (available = -1).Instead, we combine the check and the subtraction into a single conditional
UPDATEinside PostgreSQL, wrapped in a single-round-trip CTE (Common Table Expression) so retries are idempotent and we never hold a row lock open across multiple network hops:WITH existing AS ( -- Check if this (reservation_id, sku) was already processed on an earlier attempt SELECT state FROM reservation_items WHERE reservation_id = :rid AND sku = :sku ), inserted AS ( -- Only insert if no row exists yet INSERT INTO reservation_items (reservation_id, sku, qty, state) SELECT :rid, :sku, :qty, 'HELD' WHERE NOT EXISTS (SELECT 1 FROM existing) RETURNING 1 ), updated_stock AS ( -- Atomically check available >= :qty AND move units into reserved ONLY on a fresh insert! UPDATE inventory SET available = available - :qty, reserved = reserved + :qty, version = version + 1 WHERE sku = :sku AND available >= :qty AND EXISTS (SELECT 1 FROM inserted) RETURNING available, version ), ledger_row AS ( INSERT INTO inventory_ledger (entry_id, sku, d_available, d_reserved, d_committed, reason, ref_id) SELECT :entry_id, :sku, -:qty, :qty, 0, 'RESERVE', :rid FROM updated_stock ) SELECT (SELECT state FROM existing) AS prior_state, (SELECT count(*) FROM updated_stock) AS did_reserve, (SELECT available FROM updated_stock) AS new_available;Trace the three possible outcomes of this single round-trip:
- Fresh success (
prior_state = NULL, did_reserve = 1): stock was sufficient,reservation_items,inventory, andinventory_ledgerall updated atomically; commit the transaction! (Ifnew_availablecrossed10or0, include theoutboxinsert too.) - Out of stock (
prior_state = NULL, did_reserve = 0):available < :qty, soupdated_stockmatched 0 rows; roll back the transaction (undoinginserted) and return409 INSUFFICIENT_STOCK. - Network retry (
prior_state = 'HELD'): a previous call already succeeded;insertedandupdated_stockdo zero work and never subtract stock twice! (Ifprior_state = 'RELEASED', the reservation already expired, so return410 EXPIREDinstead of pretending it is still held.)
Multi-item carts across shards: short saga instead of two-phase commit
Suppose a cart holds
sku-A(on Shard 2) andsku-B(on Shard 7). Two-phase commit (2PC)—a distributed transaction protocol that locks rows on both shards until both vote and commit—would hold row locks across network hops, stalling hot items. Instead, we run a saga (a sequence of fast single-shard transactions with compensating undo steps if a later item fails):1. Insert header on reservation shard: status = 'PENDING', expires_at = now() + 15m 2. Sort cart SKUs alphabetically (prevents deadlocks) and run the single-shard SQL above per SKU. 3. If every SKU succeeds: UPDATE reservations SET status = 'HELD' WHERE reservation_id = :rid AND status = 'PENDING' AND expires_at > now(); -> If 1 row updated: return 201 HELD! -> If 0 rows updated (sweeper expired a stalled attempt first): release all SKUs & return 410. 4. If SKU #2 fails with INSUFFICIENT_STOCK: Immediately run the idempotent release SQL on SKU #1 (HELD -> RELEASED, reserved -> available), mark header status = 'RELEASED', and return 409 INSUFFICIENT_STOCK.Handling flash sales (10,000 QPS on one hot SKU)
Remember our math: one PostgreSQL row can only commit ~200–1,000 updates/s. Let's compare three ways to handle 10,000 QPS on one SKU:
Approach How it works Trade-off Split into N sub-rows Store 1,000 units as 10 rows of 100 ( sku#0..9); pick one at randomCuts lock contention 10x with no extra infra, but near sell-out buyers hit empty sub-rows while other sub-rows still have 1 unit left Per-SKU queue Push requests into a single-partition queue; one worker drains serially Strict first-come-first-served fairness, but adds queueing latency and extra worker state Redis + Lua admission gate (chosen) Atomic in-memory counter rejects 9,900 losers/s in < 1 ms; only winners touch SQLHandles 50,000+ QPS per shard effortlessly; SQL remains the source of truth against overselling For SKUs flagged as flash sales (manually by merchandising or automatically when per-SKU QPS crosses 200/s), Inventory Service runs an atomic Redis Lua gate first:
def try_flash_gate(redis_client, sku, user_id, qty): """Conceptual logic of the atomic single-threaded Redis Lua admission script.""" holders_key = f"flash:{sku}:holders" stock_key = f"flash:{sku}:available" # Enforce 1 reservation per customer during flash sales to block scalper bots if redis_client.sismember(holders_key, user_id): return "ALREADY_HOLDING" # Reject losers in RAM (~0.2 ms) without touching PostgreSQL! remaining = int(redis_client.get(stock_key) or 0) if remaining < qty: return "SOLD_OUT" # Admit winner and decrement the in-memory gate counter atomically redis_client.decrby(stock_key, qty) redis_client.sadd(holders_key, user_id) return "ADMITTED"Only
ADMITTEDcallers proceed to run the PostgreSQL conditionalUPDATE. PostgreSQL stays the ultimate guard: even if Redis were misconfigured to admit 105 users for 100 units, PostgreSQL'savailable >= :qtyrejects the extra 5 and resets the Redis counter to0. Whenever a reservation is released or expires, the release path incrementsflash:{sku}:availableand removesuser_idfromholdersso another shopper can buy that unit. And if a pod crashes right between Redis admission and the SQL write (leaking 1 gate count), a 30-second reconciler compares Redis0against PostgreSQLavailable > 0and tops Redis back up — meaning a crash can briefly delay selling the last unit by 30 seconds, never oversell.- Fresh success (
Deep dive 3: Checkout flow, cryptographic price quotes, and abandoned carts
Stopping stale or tampered browser prices
Never accept
priceas a parameter from the browser! Instead, at cart confirmation, Order Service fetches an authoritative price quote from Pricing Service's primary database and seals it with an HMAC-SHA256 signature (Hash-based Message Authentication Code: a cryptographic checksum computed using a secret server-only key so nobody can alter a single digit without invalidating the signature):Browser Order Service Pricing Service (Primary) Inventory Service |-- Confirm Cart ------>| | | | |-- 1. POST /quotes ---------->| | | |<-- {unit_cents, price_ver, | | | | expires_at, hmac_sig} ---| | | (If price changed | | | | since browse, ask | | | | user to re-confirm)| | | |-- Click Pay --------->|-- 2. POST /reservations (quote + checkout_id) ------->| | | (verifies HMAC, expires_at, revoked_below_ver, | | | then atomically moves available -> reserved) | | |<-- 201 HELD (15-min TTL) -----------------------------| | |-- 3. Authorize Card (PSP) | | |-- 4. POST /reservations/{id}:commit ----------------->| | | (moves reserved -> committed; returns 200) | | |-- 5. Capture Card (PSP) | |<-- Order Confirmed! --| | |Why combine a stateless HMAC quote with a tiny
revoked_below_versioncolumn onactive_price?- No per-quote database writes: we do not have to insert and garbage-collect 1,000 quote rows per second.
- 15-minute price honor: if a routine pricing bot bumps a toaster from
$24.99to$25.49while the user is typing their credit card number, their valid signed quote for$24.99is still honored untilexpires_at, preventing frustrating checkout failures. - Instant emergency revocation: if an operator accidentally priced a
$1,000laptop at$10.00(price_version = 41), fixing it to$1,000(price_version = 42) and settingrevoked_below_version = 42causes Inventory Service to reject every unredeemed$10.00quote immediately (41 < 42 -> 409 QUOTE_INVALID).
Reliable stock expiration for abandoned carts
Relying on Redis key-expiration notifications (
__keyevent@0__:expired) to release stock is dangerous: if a subscriber disconnects or restarts, expiration events vanish and inventory stays stuck inreservedforever! Instead, the PostgreSQLreservationsrow itself is the durable timer, indexed by(status, expires_at).Sweeper workers on every shard run every few seconds using
FOR UPDATE SKIP LOCKED(a SQL clause that locks expired rows for this worker while skipping rows already locked by sibling workers, allowing parallel sweeping with zero lock waits):-- Step A (on reservation shard): claim a batch of expired headers and win the state transition WITH batch AS ( SELECT reservation_id FROM reservations WHERE status IN ('PENDING', 'HELD') AND expires_at < now() ORDER BY expires_at LIMIT 500 FOR UPDATE SKIP LOCKED ) UPDATE reservations r SET status = 'EXPIRED', settled = FALSE FROM batch b WHERE r.reservation_id = b.reservation_id AND r.status IN ('PENDING', 'HELD') RETURNING r.reservation_id;Why a late payment
:commitand the sweeper can never collide or double-release:- Single point of decision on the header:
:commitrunsUPDATE reservations SET status = 'COMMITTED' WHERE reservation_id = :rid AND status = 'HELD'. Because PostgreSQL serializes updates to that single header row, either:commitwins (HELD -> COMMITTED) or the sweeper wins (HELD -> EXPIRED), never both. - Idempotent item settlement: for each
EXPIREDheader, the sweeper visits each SKU shard and runsUPDATE reservation_items SET state = 'RELEASED' WHERE reservation_id = :rid AND sku = :sku AND state = 'HELD'inside a CTE that returnsqtytoavailableonly if that transition matched 1 row, then setsreservations.settled = TRUE. If the sweeper crashes halfway through, a secondary query picks upstatus = 'EXPIRED' AND settled = FALSErows and finishes the remaining items safely. - What if
:commitgets410 EXPIREDright before card capture? Order Service requests a fresh quote (asking the user to re-confirm only if the price changed) and tries a new reservation undercheckout_id + ":attempt2"; if stock sold out in the meantime, it voids the card authorization so the shopper is never charged.
Scaling, failure recovery, and summary of trade-offs
Price auditability and reconciliation
- Tamper-evident price audit log:
PUT /v1/prices/{sku}writesprices,price_history, andoutboxin one SQL transaction. The application database role hasINSERTandSELECTprivileges onprice_history—neverUPDATEorDELETE—and daily snapshots export to write-once object storage (such as S3 Object Lock) for compliance audits. - Nightly ledger reconciliation: an offline job verifies two invariants per SKU: (1)
available,reserved, andcommittedeach equal the exact sum ofd_available,d_reserved, andd_committedininventory_ledger, and (2)reservedequals the sum ofqtyacrossHELDreservation_items. Any discrepancy pages on-call immediately.
How the system survives component failures
Failure scenario Impact & automatic recovery Redis cache shard fails Replica promotes in seconds; meanwhile read pods fall back to SQL read replicas behind a concurrency limiter. If overloaded, product pages degrade gracefully to showing price + "Check availability at checkout"while checkout continues normally.Kafka or Cache Projector lags Browsing badges/prices lag by seconds ( valid_untilstill forces expired promos to refresh, and hourly scrubbing bounds drift). Checkout is 100% unaffected because it reads SQL primaries.Inventory SQL primary crashes Synchronous standby promotes with zero lost reservations ( RPO = 0). In-flight checkout calls retry with the sameIdempotency-Key(checkout_id) and resume cleanly without double-reserving.Flash-sale Redis gate crashes Pause admission for that hot SKU for ~2 seconds, reload flash:{sku}:availablefrom PostgreSQL's authoritativeavailablecolumn, and reopen.Payment provider hangs > 15 min Order Service calls :extendonce (+5 minutes). If still unresolved after 20 minutes, the sweeper expires the hold and Order Service voids the card authorization when the PSP responds.Summary of key trade-offs
- Decoupled NoSQL catalog + sharded SQL prices/stock: gives flexible schemas and CDN caching for static specs plus strict ACID guarantees for money and stock, at the cost of merging two fast in-memory sources in the Product Read Service.
- No-TTL versioned push cache vs. short-TTL pull cache: keeps all 20M SKUs in ~4 GB of Redis RAM with zero long-tail misses and sub-second freshness, trading off the operational cost of running an outbox relay and Kafka projector.
- Availability badges vs. exact counts on browse pages: drops inventory cache invalidation traffic by ~100x while enforcing exact unit counts at checkout via conditional SQL.
- Single-shard conditional SQL + saga vs. distributed 2PC locks: avoids cross-shard lock contention on hot SKUs, in exchange for writing compensating release logic on multi-item cart failures.
- HMAC-signed quotes + version floor vs. server-stored quote rows: eliminates 1,000 quote-table writes/s while preserving tamper resistance and emergency price-error revocation.
- Tamper-evident price audit log:
Intuition & how it works
Think of an online retail catalog, pricing, and stock reservation backend like a massive concert stadium with giant digital lobby screens and a locked box-office vault. Outside in the lobby, 100,000 fans per second glance at the digital screens (browsing product and search pages): those screens only need to show product photos, the current price, and a simple status badge (IN_STOCK, LOW_STOCK, or OUT_OF_STOCK) refreshed within a second or two from fast memory. When a fan actually steps up to buy, they enter the box-office vault (checkout): the clerk prints a tamper-proof 15-minute price slip (a cryptographically signed quote) and physically moves tickets from the available tray into a reserved envelope inside the primary database, returning them to available if the fan walks away without paying.
Why do the naive designs break? Reading prices and stock directly from the transactional database on every product view melts the database at 670,000 SKU (Stock Keeping Unit—a unique purchasable item ID) lookups per second, while caching with naive short TTLs (Time-To-Live expiration timers) causes tens of thousands of cache misses every second across 20 million long-tail items. At checkout, checking stock in application code (SELECT available, then if available >= qty: UPDATE) lets two concurrent shoppers read available = 1 in the same millisecond and buy 2 copies of the last item (overselling), while trusting whatever price the browser submits lets anyone edit page JavaScript to buy a $1,000 laptop for $1.
Walk through a tiny concrete trace on one item, sku-100 (starting with available = 2, reserved = 0, price 2500 cents = $25.00, price_version = 1):
1. Price update: Merchandising lowers sku-100 to 2000 cents -> Price DB commits prices +
append-only price_history + outbox row (price_version = 2) -> Kafka projector
updates Redis via Lua only because version 2 > version 1.
2. Buyer A checkout: Confirms cart -> Pricing primary issues HMAC-signed quote (2000 cents, v2).
Order Service calls POST /reservations (Idempotency-Key = "chk-A") for qty = 2.
SQL runs: UPDATE inventory SET available = available - 2, reserved = reserved + 2
WHERE sku = 'sku-100' AND available >= 2;
-> 1 row updated! (available = 0, reserved = 2). Badge flips to OUT_OF_STOCK.
3. Buyer B races in: Milliseconds later, Buyer B requests qty = 1 on sku-100.
SQL checks WHERE available >= 1 -> 0 rows updated! Instant 409 INSUFFICIENT_STOCK.
4. Buyer A abandons: Buyer A closes the tab. 15 minutes later, the Expiry Sweeper transitions header
"chk-A" from HELD -> EXPIRED and moves 2 units back (available = 2, reserved = 0).
Key trade-offs
- Separate static catalog storage from volatile price and stock tables. Storing flexible product specs and image URLs in a NoSQL document store (a non-relational database keyed by
skuwith flexible JSON fields) behind a CDN (Content Delivery Network of edge caches near users) while keeping prices and stock in relational SQL databases gives each workload the right tool. The trade-off is that the Product Read Service merges two fast sources in memory when assembling a response. - No-TTL version-guarded push caching vs. TTL-based pull caching. Keeping all 20 million compact
{price, badge}records (~4 GB) permanently in Redis (an in-memory key-value store) and pushing updates from a transactional outbox (an event table written in the same SQL transaction as the data change) via Kafka (a durable streaming log) avoids all long-tail cache misses and prevents out-of-order events from moving prices backward. The trade-off is operating the outbox relay, Kafka pipeline, and an hourly background scrubber instead of relying on a simpleEXPIRE 60timer. - Coarse availability badges vs. exact unit counts on browse pages. Emitting cache updates only when
availablecrosses10or0cuts inventory invalidation events by ~100x and avoids giving shoppers false precision on fast-moving items, while conditional SQL still enforces exact unit counts at checkout. - Single-shard conditional
UPDATE+ saga vs. distributed two-phase commit (2PC). ExecutingWHERE available >= :qtyatomically under a sub-millisecond single-row lock requires no external lock service. Multi-item carts spanning shards become a saga (a sequence of single-shard reservations with compensating release calls if a later SKU fails) rather than 2PC (holding cross-shard locks until the slowest shard responds), trading brief intermediate stock holds for vastly higher throughput on popular items. - Redis Lua admission gate vs. sub-row splitting vs. per-SKU queues for flash sales. A single SQL row tops out around ~200–1,000 commits/s, far short of 10,000 QPS bursts. A single-threaded Redis Lua gate rejects 99% of losing requests in
< 1 msin RAM while keeping PostgreSQL as the final guard against overselling. Splitting one SKU into 10 sub-rows needs no Redis gate but causes false out-of-stock errors when 9 sub-rows hit0and 1 sub-row still has stock; a per-SKU queue gives strict arrival fairness at higher tail latency. - Stateless HMAC-signed quotes + version floor vs. database-stored quotes. Sealing quotes with an HMAC (a cryptographic signature created with a server-secret key) avoids writing and expiring 1,000 quote rows per second, while a tiny per-SKU
revoked_below_versioninteger onactive_pricestill lets operators revoke fat-finger pricing mistakes immediately. Server-stored quotes make revoking a single user's quote trivial, at the cost of extra write load and cleanup jobs. - Honoring quoted prices for 15 minutes vs. re-checking live prices at payment. Honoring a valid quote until
expires_atguarantees the customer pays the exact price they confirmed on screen, at the minor business cost of honoring the old price for up to 15 minutes after a routine price increase. - Database sweeper vs. cache-expiration events for abandoned carts. Polling an indexed
(status, expires_at)column in PostgreSQL withFOR UPDATE SKIP LOCKED(locking expired rows without blocking sibling workers) means an expiration can never be lost if a cache node restarts, trading a few seconds of sweep delay for 100% reliability.
Common mistakes
- Read-then-write stock checks in application code (
SELECT available, thenUPDATE). Concurrent requests read the same positive count before either writes back, driving inventory negative and overselling. Always combine the check and subtraction inside one atomicUPDATE ... WHERE available >= :qty. - Trusting browser-submitted prices or reading checkout prices from Redis. Browsers can be tampered with, and caches can lag by seconds; checkout quotes must always read from the Pricing SQL primary and be cryptographically signed.
- Decrementing inventory on "Add to Cart" instead of at checkout start. Shoppers leave millions of items sitting in casual carts for days, locking up sellable inventory and enabling denial-of-inventory attacks by bots.
- Missing idempotency keys (or double-decrementing on SQL retry). Without
Idempotency-Key: <checkout_id>—and without conditioning theinventorydecrement onreservation_itemsactually inserting a new row—every network timeout retry reserves stock a second time. - Unguarded state transitions between late payment commits and the expiry sweeper. If
:commitand the sweeper do not compete on a single guardedUPDATE reservations ... WHERE status = 'HELD'header row (andWHERE state = 'HELD'on item rows), a slow checkout can both expire and commit, corrupting inventory counts. - Relying solely on Redis TTL expiry notifications to release held stock. Redis keyspace events are fire-and-forget; any brief subscriber disconnect permanently leaks reserved units.
- Adding SQL read replicas to fix a flash-sale bottleneck. Read replicas only scale
SELECTqueries; 10,000 reservation attempts on one SKU contend on the primary's single row lock and require an upstream gatekeeper. - Updating prices without
If-Matchoptimistic concurrency or same-transaction audit rows. Without version checks, an automated repricer silently clobbers a merchandiser's manual edit, and writing audit logs outside the SQL transaction loses audit entries on crashes. - Representing money as
FLOATorDOUBLE. Always use integer minor units (cents) so totals and signatures never suffer binary rounding drift.
Follow-up questions
- Suppose a limited-edition drop draws 50,000 simultaneous checkout attempts for just 100 units of one SKU; how do you protect the database while selling every unit cleanly? Make losing fast and cheap at the edge so the database only ever sees the ~100 winners. Place a virtual waiting room at the CDN/edge before the sale opens: pre-arrival shoppers receive a randomized queue position (neutralizing low-latency scalper bots alongside bot-challenge tokens and per-account limits) and trickle through at a controlled rate (say 2,000/s) into the dedicated Redis Lua gate. The Lua script atomically checks
SISMEMBER(1 unit per user) and decrementsflash:{sku}:available, rejecting 49,900 losers in< 1 mswhile only the 100 admitted winners execute the PostgreSQL conditionalUPDATE. The instant the gate hits0, aSOLD_OUTflag pushes to the CDN and L1 caches to short-circuit remaining traffic at the edge; if any winner's 15-minute hold expires unpaid, the sweeper returns that unit to PostgreSQL and the Redis gate so the next user in the waiting room can claim it. - What mechanism guarantees that units held by shoppers who close their browser mid-checkout always return to sellable stock without racing against slow payment confirmations? Store
expires_atdirectly on thereservationstable with a composite index on(status, expires_at), and run stateless sweeper workers on every shard every few seconds. Each worker claims batches of expiredPENDINGorHELDheaders usingSELECT ... FOR UPDATE SKIP LOCKEDand executes a guarded header transition (status IN ('PENDING', 'HELD') -> 'EXPIRED', settled = FALSE), which cleanly resolves any race with a late:commit(PENDINGalso cleans up multi-item sagas that crashed mid-flight). For each expired header, the worker runs an idempotent item release (state = 'HELD' -> 'RELEASED'+available += qty+ ledger row) on each SKU shard before markingsettled = TRUE, and retries anyEXPIRED AND NOT settledstragglers on the next sweep. You can optionally pair this with a 15-minute delayed queue message to release stock within milliseconds of expiry while keeping the SQL sweeper as the unbreakable safety net, and alert if any reservation staysHELDmore than 2 minutes pastexpires_at. - How would you evolve your data model, browse caching, and checkout reservation logic when stock is split across dozens of geographic warehouses? Change the primary key of
inventoryfrom(sku)to(sku, fc_id), sharding or co-locating rows in the database region closest to each fulfillment center. For low-latency browsing, the Cache Projector aggregates stock across the fulfillment centers eligible to ship to each delivery region (for example,badge:US-West:{sku}) so product pages still make a single Redis lookup. At checkout, insert a sourcing step before reservation that ranks candidate fulfillment centers—preferring a single center that holds all items in the cart to avoid costly split shipments, then shortest shipping distance—and runs the conditionalUPDATEagainst(sku, fc_id), falling back to the second-choice center if the first just ran out. Finally, hold back a smallsafety_stockbuffer per(sku, fc_id)to absorb lag from physical warehouse scanners, and track stock transfers between centers in an explicitin_transitbucket until the receiving dock scans them in.
Follow-up questions
- Suppose a limited-edition drop draws 50,000 simultaneous checkout attempts for just 100 units of one SKU; how do you protect the database while selling every unit cleanly?
- What mechanism guarantees that units held by shoppers who close their browser mid-checkout always return to sellable stock without racing against slow payment confirmations?
- How would you evolve your data model, browse caching, and checkout reservation logic when stock is split across dozens of geographic warehouses?
Similar questions
- Extract Sorted Keys from a Level-Order BST
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform
- Prior Authorization Status Engine, Clinical Worklists, and Digests
- Diagnosing and Optimizing Full-Stack Web Request Latency