Cart Hold System for High-Traffic E-Commerce
System DesignModel answerLast updated
Build a scalable service that temporarily locks inventory when users add items to their cart, prevents duplicate allocation, and releases stock automatically.
Context
You're architecting the backend for an online grocery marketplace where physical warehouses stock thousands of products with finite quantities. When a shopper adds a limited-availability item (think flash-sale electronics or holiday gift baskets) to their cart, your platform needs to guarantee that those units remain theirs until they either complete payment or their session times out. The challenge: if fifty people simultaneously try to claim the last three units of a product, your system must allocate correctly without allowing more reservations than stock available, all while maintaining fast response times and handling sudden traffic bursts.
What You Need to Design
Core Capabilities
- Temporary Allocation: Lock a requested quantity of a product for a specific user session with a time limit (assume 15 minutes default).
- Stock Return: Automatically free locked inventory when time expires or when a user manually removes items before checkout.
- Finalization: Permanently deduct inventory once payment processing confirms success.
- Real-Time Visibility: Show shoppers accurate or near-accurate stock levels while browsing.
Performance & Reliability Targets
- Accuracy: Zero cases where total allocations exceed physical stock, regardless of concurrent access patterns.
- Speed: Reserve and query operations should complete in under 50ms at the 99th percentile.
- Elasticity: Handle normal load and accommodate a 10x spike during promotional events without degradation.
- Recovery: System failures (crashed workers, network partitions) must not permanently trap inventory in a locked state.
Operating Environment
- Product Catalog: 50 million SKUs distributed across 20,000 warehouse locations.
- User Base: 10 million daily active shoppers.
- Baseline Traffic:
- Allocation requests: 20,000 per second
- Stock queries: 100,000 per second
- Peak Traffic (during sales events):
- Allocation requests: 200,000 per second
- Stock queries: 1,000,000 per second
Areas to Address
- Storage Architecture: Evaluate transactional databases versus in-memory data stores for managing the allocation ledger.
- Race Condition Prevention: Explain how you'll eliminate conflicts when many sessions compete for the same scarce product.
- Timeout Management: Design a mechanism to reclaim expired locks at scale without overwhelming your primary data layer.
- Error Handling: Describe recovery strategies for payment gateway delays, service crashes, and inconsistent state scenarios.
Hints
Hint 1
Consider separating the fast decision path from the durable record-keeping path
Hint 2
Look for storage technologies that can perform atomic read-modify-write operations in microseconds
Hint 3
Think about how to clean up expired locks without scanning every record in your database
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer: Cart Hold System for High-Traffic E-Commerce
1. Scope Clarification and Capacity Planning
Begin by establishing precise boundaries and calculating resource needs.
Key clarifications:
- Inventory granularity: tracked per
(warehouse_id, product_id)pair. With 50M SKUs across 20K warehouses, estimate ~50M actively tracked inventory records (not every SKU exists in every warehouse). - Consistency boundary: the no-overselling guarantee applies to our platform's allocation ledger. Physical warehouse stock comes from periodic POS system updates, so some drift is expected.
- Traffic breakdown: 20K allocation requests/second baseline, 200K peak. Release and finalization operations roughly double the write volume.
- Query traffic: 100K reads/second baseline, 1M peak. Queries can tolerate slight staleness (1-5 seconds).
- Lock duration: 15 minutes standard, with extension during payment processing.
Capacity estimates:
- Active locks at peak: ~200K allocations/second × average 300 seconds dwell = ~60M concurrent locks.
- Memory footprint: ~150 bytes per lock × 60M = ~9GB, easily fitting in a distributed in-memory tier.
2. API Contract
POST /cart/locks {session_id, warehouse_id, product_id, quantity, request_id}
→ {lock_id, expiration_time} | 409 INSUFFICIENT_STOCK
DELETE /cart/locks/{lock_id} // manual release
PATCH /cart/locks/{lock_id} {action: "extend"} // during payment
POST /checkout {session_id, lock_ids[], payment_token}
GET /stock?warehouse_id=&product_ids=[] // approximate availability
All mutations use idempotency:
- Allocation keyed by
request_id(client-generated UUID). - Release and finalization keyed by
lock_id.
Idempotency is mandatory because clients retry on timeout.
3. Storage Design
Durable layer: PostgreSQL sharded by warehouse_id.
stock_ledger(warehouse_id, product_id, physical_count, locked_count,
sold_count, last_updated, version)
allocation_log(lock_id PK, warehouse_id, product_id, session_id, quantity,
state ENUM(ACTIVE, PAYMENT_IN_PROGRESS, FINALIZED, RELEASED, EXPIRED),
expiration_time, created_at)
Decision layer: Redis Cluster with hash tag routing on {warehouse_id:product_id}.
stock:{w:p} HASH {physical, locked, sold}
locks:{w:p} ZSET {lock_id → expiration_timestamp}
lock:{lock_id} HASH {quantity, session_id, state}
Invariant maintained:
locked_count + sold_count + available_for_new_locks ≤ physical_count
4. System Architecture
Client → API Gateway → Session Service → Allocation Service
├─→ Redis Cluster (atomic decisions)
├─→ PostgreSQL shards (durable log)
└─→ Event Bus → Expiry Workers, Analytics, Cache Sync
Warehouse Systems → Ingestion Pipeline → Updates physical_count in Postgres + Redis
Query Path: Catalog Service → Regional Read Cache (1-5s stale data acceptable)
Allocation workflow:
-
Execute atomic Lua script on the product's Redis shard:
- Scan
locks:{w:p}ZSET for expired entries (score < current_timestamp). - Subtract expired quantities from
lockedcounter. - Verify invariant:
physical - locked - sold ≥ requested_quantity. - If valid, increment
locked, add lock to ZSET. - Single Redis operation, ~1ms, no race conditions due to single-threaded script execution.
- Scan
-
Write
allocation_logrecord to PostgreSQL:- Append-only insert with
lock_idas PK. - Use upsert semantics for idempotency.
- No hot-row contention since it's an insert, not an update.
- Append-only insert with
-
Respond to client only after PostgreSQL write confirms.
- If Postgres write fails, execute compensating Lua script to release the Redis lock.
Total end-to-end latency: 5-10ms, comfortably under the 50ms p99 target.
Why not PostgreSQL alone? Conditional updates work at moderate scale:
UPDATE stock_ledger
SET locked_count = locked_count + :quantity
WHERE warehouse_id = :wid AND product_id = :pid
AND physical_count - locked_count - sold_count ≥ :quantity
The bottleneck: row locks serialize all competing transactions for hot products. Maximum throughput drops to ~1000-2000 ops/second per product, and lock queue buildup destroys tail latencies. Redis executes atomic scripts in microseconds with no lock waiting.
The tradeoff: Redis isn't the source of truth. That's why every acknowledged allocation is also persisted (step 2).
5. Deep Dive: Critical Mechanisms
Eliminating Race Conditions
- Single-writer atomicity per product: Lua scripts on the owning Redis shard perform check-and-modify as one operation.
- No distributed locks required: Hash tag routing guarantees all keys for a product land on the same shard.
- Finalization: Second Lua script transitions lock from
ACTIVEtoFINALIZED, moving quantity fromlockedtosold. Only succeeds if lock exists and isACTIVEorPAYMENT_IN_PROGRESS. - Expired lock protection: Finalization fails if lock has passed expiration_time, forcing checkout to re-attempt allocation or gracefully fail.
Expiration Without Database Overload
Three-layer approach, ordered by execution cost:
-
Lazy cleanup in every operation:
- Each Lua script scans for expired locks before making decisions.
- Available stock calculation is always correct at decision time, even without background processing.
- Guarantees no stock remains locked when someone needs it.
-
Shard-local sweeper workers:
- Maintain a global
expiry_scheduleZSET per Redis shard containing{warehouse:product}keys. - Background workers pop due entries in small batches, invoke cleanup Lua scripts.
- Work naturally partitions across shards, scales horizontally.
- Maintain a global
-
Durable log reconciliation:
- Cleanup events published to event bus (Kafka).
- Consumers batch-update
allocation_log.state = EXPIRED. - PostgreSQL never polled directly.
- Low-priority reconciliation job scans
WHERE state='ACTIVE' AND expiration_time < now() - grace_periodusing indexed query to catch edge cases.
Avoid Redis keyspace notifications: they're unreliable (fire-and-forget, lost on reconnect) and only trigger on actual eviction.
Failure Recovery Strategies
Payment processor timeout:
- Before calling processor, transition lock to
PAYMENT_IN_PROGRESSstate and extend TTL (e.g., 30 minutes). - If outcome unknown, query processor by idempotency token during reconciliation.
- Finalize or release based on authoritative payment status. Never release while outcome is uncertain.
- Sequence: authorize payment → finalize inventory → capture payment. If inventory finalization fails, void authorization.
Service crash mid-allocation:
- Redis lock exists but no PostgreSQL record: client never received acknowledgment.
- Reconciliation finds Redis locks older than threshold (e.g., 60 seconds) with no corresponding ledger entry and releases them.
- Lock TTL provides automatic upper bound on leakage.
Redis failover with asynchronous replication:
- Last few writes before failover may be lost.
- Use
WAIT 1command to ensure replica acknowledgment on allocation (adds <1ms latency). - Attach shard generation number (fencing token) to each lock. After failover, new primary increments generation.
- Finalization requests carrying stale generation are re-validated against PostgreSQL ledger.
6. Key Tradeoffs
Strict allocation, eventual query consistency:
- The 1M read requests/second served from cached or replica data.
- Show "only 3 remaining" from approximate counts; let allocation be the authoritative arbiter.
Fail-safe default:
- If a product's Redis shard is unavailable, reject allocations rather than risk overselling.
- Availability impact is localized to products on the affected shard.
Memory vs. durability:
- Redis provides speed; PostgreSQL provides recovery.
- In disaster scenarios, rebuild Redis state from PostgreSQL allocation_log (takes minutes, acceptable for rare events).
Complexity cost:
- Dual-write pattern requires careful orchestration and reconciliation logic.
- Simpler single-database approach works up to ~5-10K requests/second; beyond that, the performance jump justifies the complexity.
7. Monitoring and Observability
Essential metrics:
- Per-product allocation success rate and p99 latency.
- Redis-PostgreSQL drift (locks in Redis missing from ledger, or vice versa).
- Expiration lag (time between lock expiration and actual cleanup).
- Payment-finalization reconciliation backlog.
Alerting thresholds:
- Allocation success rate drops below 99% for products with available stock.
- Drift count exceeds 0.1% of active locks.
- Reconciliation lag exceeds 5 minutes.