Design a Real-Time Stock Availability Service
System DesignModel answerLast updated
Design a distributed inventory service that tracks stock across many locations, handles concurrent reservations without overselling, and pushes availability updates to clients in near real-time.
Scenario
You're joining the platform team at a company that connects shoppers to retail locations. The platform needs an inventory service that can tell shoppers whether a product is available at a nearby store, hold stock while a cart is being checked out, and keep displayed availability reasonably fresh without hammering the database on every page load.
Unlike a warehouse system where the company controls every shelf, store stock levels here are tracked indirectly: data comes from retailer feeds, point-of-sale integrations, and signals from field workers reporting what they actually found. That makes the inventory count an estimate with a confidence level, not a hard truth.
What to Cover
Spend a couple of minutes scoping the problem before diving in. Then walk through:
- Functional and non-functional requirements — what operations the system must support, and what consistency and latency targets matter
- Scale estimates — order-of-magnitude numbers for locations, SKUs, read QPS, and write throughput
- API design — key endpoints for reads, reservations, commits, releases, and adjustments
- Data model — schema for inventory state, reservations, and an audit ledger; justify your storage choices
- Architecture — how components fit together end-to-end (read path, write path, real-time fan-out)
- Deep dives on at least two of:
- Preventing overselling under high concurrency
- Handling hot SKUs (a promoted item that gets hammered all at once)
- Keeping the read cache fresh without dual-write bugs
- Expiring abandoned reservations safely
- Ingesting large bulk retailer feeds reliably
A strong answer surfaces trade-offs rather than presenting one approach as obviously correct. Numbers, even rough ones, are better than vague adjectives like "high traffic."
Hints
Hint 1
Start by separating the read path (browse/search, very high QPS, tolerates slight staleness) from the write path (reservations, requires strong consistency per location+SKU). The two paths have different consistency needs and can be optimized independently.
Hint 2
The safest way to reserve stock without a race condition is a conditional UPDATE — decrement the count in the WHERE clause rather than reading first and writing second. Think about what happens when multiple orders hit the same popular SKU at the same millisecond.
Hint 3
A reservation that is never committed or released will lock up stock forever. How does the system recover from a shopper who abandons their cart or whose app crashes mid-checkout? And how do you make sure retried requests don't double-reserve?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Scoping the Problem
Before drawing boxes, nail down what "inventory" means here. The system needs to:
- Track a quantity and a confidence score per (location, SKU) pair
- Let clients read availability fast, with slight staleness acceptable
- Reserve stock when an order is placed, commit it on fulfillment, and release it on cancellation or timeout
- Accept updates from retailer feeds, POS signals, and field-worker reports
- Push availability changes to client apps within a few seconds
The key tension: reads vastly outnumber writes and can tolerate staleness, but reservations need strong consistency per row to prevent overselling. Every design decision flows from that.
Scale Estimates
| Signal | Estimate |
|---|---|
| Locations | ~40K stores |
| SKUs per store | ~30K → ~1.2B (location, SKU) rows |
| Row size | ~200 B → ~250 GB hot inventory data |
| Availability reads (peak) | ~100–200K QPS |
| Item-level reservations (peak) | ~100K/s (5K orders/s × ~20 items each) |
| Bulk feed rows (nightly) | ~1B rows |
Reads outnumber writes roughly 100:1. The data volume is large but shards cleanly by location.
API Design
# Read availability for a set of SKUs at one location
GET /v1/locations/{loc}/items?sku=a,b,c
→ [{sku, available_qty, confidence, updated_at}]
# Reserve stock (idempotency_key prevents double-reservation on retry)
POST /v1/reservations
{order_id, location_id, items:[{sku, qty}], idempotency_key}
→ {reservation_id, status, expires_at, failed_items}
# Commit or release a reservation
POST /v1/reservations/{id}/commit
POST /v1/reservations/{id}/release
# Apply a stock adjustment (delta or absolute, with a reason code)
POST /v1/locations/{loc}/adjustments
{sku, delta, reason, source, idempotency_key}
# Subscribe to live availability changes
WS /v1/stream?loc=...&skus=...
Every mutating call carries an idempotency key. The service stores the response for each key and returns it on replay, so retries from clients or message queues are safe.
Data Model
-- Sharded by location_id; one row per (location, SKU)
inventory (location_id, sku_id)
on_hand int
reserved int -- sum of all active holds
confidence float -- 0–1 score from feeds + ML
version bigint -- for optimistic locking
updated_at timestamptz
-- Reservation headers
reservation (reservation_id PK, order_id, location_id,
status [HELD|COMMITTED|RELEASED|EXPIRED],
expires_at, idempotency_key)
reservation_item (reservation_id, sku_id, qty)
-- Append-only ledger; source of truth for auditing and rebuilds
stock_ledger (event_id, location_id, sku_id,
delta, type, source, ref_id, ts)
idempotency (key PK, response_body, created_at)
available = on_hand - reserved. The stock_ledger is append-only and can always reconstruct inventory from scratch.
Storage choice: a sharded relational database (Postgres with Vitess, or CockroachDB/Spanner) for inventory and reservation. They need row-level transactions and conditional updates. Shard by location_id — a single order touches one store, so a multi-item reservation fits on one shard and avoids distributed transactions.
Architecture Overview
Clients ──→ API Gateway ──→ Availability Service ──→ Redis (per loc:sku)
│ ▲
└──→ Reservation/Adjustment Service ─────┤ (write-through)
│ (sharded SQL + outbox) │
▼ │
CDC (Debezium) ──→ Kafka ─────────────┤──→ Realtime Gateway (WS/SSE)
│ ├──→ Search index
Retailer feeds ──→ Ingestion workers ──────┘ └──→ ML confidence pipeline
Field-worker signals ──→ Adjustments API
Reservation expiry worker ──→ releases HELD rows past expires_at
Deep Dives
Preventing Overselling
Never read, then decide, then write — a concurrent request will slip through between the read and the write. Instead, put the availability check inside the WHERE clause of a single atomic update:
UPDATE inventory
SET reserved = reserved + :qty,
version = version + 1
WHERE location_id = :loc
AND sku_id = :sku
AND on_hand - reserved >= :qty;
-- 0 rows updated → insufficient stock
Wrap all items in one transaction. For cases where partial fulfillment is acceptable (the business may prefer to reserve what's available and suggest substitutions), process items individually and return a failed_items list.
Reservations carry a TTL (e.g., 15 minutes). A background sweeper queries for HELD reservations past expires_at and releases them, restoring reserved back to the live row.
Hot SKUs
A promoted item or a seasonal spike can funnel thousands of writes per second to a single row. Options:
- Stock buckets: split the SKU's quantity across N sub-rows; reserve from a random bucket, fall back to others when one empties. Trade-off: small quantities can get stranded in buckets, causing false "out of stock" results.
- Serialized queue: partition Kafka by
(location_id, sku_id)and process with a single consumer per partition. Simpler consistency guarantee, but adds latency. - Pre-allocated quotas: hand out blocks of reservation capacity to individual service instances. Fastest, but requires a rebalancing step when instances scale.
Pick the approach that matches the business's tolerance for false negatives vs. complexity.
Keeping the Cache Fresh Without Dual Writes
Writing to the database and then writing to Redis separately creates a window where a crash leaves them inconsistent. Instead, use the outbox pattern: the Reservation/Adjustment Service writes a change record to an outbox table in the same database transaction as the inventory update. A CDC tool (Debezium) streams committed outbox rows to Kafka. Downstream consumers — Redis, the search index, the realtime gateway — update from that single reliable stream. The write is only in one place; everything else is a derived read.
Coalesce rapid updates to the same SKU (e.g., at most one Redis write and one push per SKU per second) to avoid flooding clients during bulk feed ingestion.
Common Mistakes to Avoid
- Read-modify-write for reservations. A SELECT followed by an UPDATE is not atomic under concurrent load. Put the guard condition in the WHERE clause.
- Skipping idempotency keys. Network retries and queue redeliveries will happen. Without a deduplication step, you double-reserve.
- Treating inventory as exact. When stock levels come from third-party feeds and field workers, the count is an estimate. Modeling a confidence score prevents overselling AND avoids refusing valid orders based on stale data.
- Synchronous cache invalidation. Writing to the cache in the same request path creates a failure mode where the DB succeeds but the cache update fails silently. Use the outbox/CDC path instead.