Build a Consistent Online Store with Cart and Payment Handling
System DesignModel answerLast updated
Design an online shopping system handling product discovery, shopping carts, order placement, inventory management, and payment processing with consistency guarantees.
You need to design an online shopping system. Explain your approach to letting customers browse products, manage their shopping cart, submit orders, and track the results—while keeping product stock, payment transactions, and order records consistent even under concurrent access and failures.
Scope and Boundaries
Design for physical goods sold through distinct product codes (SKUs). Your system should include:
- A browsable product catalog with search
- Shopping cart functionality
- Order submission and checkout
- Stock tracking and allocation
- Integration with a third-party payment processor
- Order status visibility
You may omit personalized recommendations, multi-seller marketplaces, and warehouse-specific fulfillment logic.
Technical Considerations
- No specific traffic numbers, uptime targets, or geographic requirements are given. Discuss how these would influence your choices rather than inventing constraints.
- The system must handle multiple customers trying to buy the same limited-stock item simultaneously.
- Customers may retry a checkout action, and payment webhooks may arrive more than once.
- Stock may run out between when a customer adds an item to their cart and when they complete checkout.
Questions You Should Ask
Before diving into design, clarify:
- Should adding items to a cart reserve inventory, or does reservation happen only during checkout?
- Can product prices or stock status change after a customer has added items to their cart?
- What guarantees does the payment provider offer? Can we make idempotent payment requests? Does it support a two-phase authorize-then-capture flow? Can we query definitive payment status?
- If an order contains multiple items, must we allocate stock for all of them or none?
- Which parts of product browsing can tolerate stale data, and where do we need real-time accuracy?
Part 1: Core Architecture and Data Flow
Describe the major components and data structures needed for browsing, cart management, checkout, and order tracking. Explain where authoritative data lives for pricing, inventory, and order state.
Expected coverage:
- How read-optimized catalog views differ from the authoritative data used during purchase decisions
- Data models for products with variants, cart line items, finalized order records, and order identity
- How you partition data and requests by customer to maintain isolation
Part 2: Ensuring Checkout Correctness
Walk through the checkout flow for a multi-item order. Cover inventory allocation, price confirmation, payment initiation, handling success and failure, and dealing with duplicate requests.
Expected coverage:
- How you make an all-or-nothing decision about stock availability and track order progress through explicit states
- Techniques to make customer checkout requests and payment provider callbacks idempotent
- Recovery strategy when payment completes successfully but the acknowledgment is lost, avoiding double charges or double-selling inventory
Part 3: Scaling and Reliability
Discuss how you would scale product browsing independently from checkout transactions, handle a high-demand item with limited stock, and identify orders that get stuck between payment and fulfillment.
Expected coverage:
- Caching and search indexing strategies with clear boundaries around where stale data is acceptable
- Managing contention on scarce inventory, using durable background jobs, and applying backpressure when needed
- Reconciliation procedures between inventory records, order state, and the payment provider to detect and resolve inconsistencies
Hints
Hint 1
Distinguish between optimistic views for browsing and authoritative checks at checkout—catalog search can be eventually consistent while inventory decisions must be transactional.
Hint 2
Use explicit order state machines (pending, authorized, confirmed, failed) and make every state transition idempotent by keying on a client-provided request ID.
Hint 3
When payment succeeds but confirmation is lost, re-querying the payment provider with the same idempotency key reveals the true outcome without creating a duplicate charge.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Model Answer
A strong answer demonstrates understanding of distributed system consistency, idempotency patterns, and practical trade-offs between performance and correctness in transactional workflows.
Part 1: Architecture and Data Models
Component Separation
Separate read paths (browsing, search) from write paths (checkout, payment). The product catalog optimized for search does not need to be the same store consulted during checkout.
Product Service: Maintains the authoritative record for each SKU—base product information, variant attributes (size, color), current price, and available stock. This service answers "can I sell this SKU right now?" with real-time accuracy.
Search Index: A denormalized, eventually-consistent view of products optimized for full-text search, filtering, and sorting. Built from change events published by the Product Service. Tolerate seconds of staleness here because customers understand that cart additions don't guarantee availability.
Cart Service: Stores ephemeral cart records keyed by customer ID. Each cart line references a SKU, quantity, and the price/name at the time of addition. Carts do not reserve inventory—reservation happens only at checkout to avoid locking stock for abandoned carts.
Order Service: The source of truth for order state. Each order has a unique ID, customer ID, immutable line items (SKU, quantity, price snapshot), total amount, current state (pending, payment_authorized, confirmed, failed), and timestamps. Once an order is created, its line items never change—cancellations or modifications create new orders.
Payment Gateway Adapter: Wraps the external payment provider, abstracting idempotency key management, webhook verification, and status queries.
Data Models
Product Variant:
{
sku: "TSHIRT-BLU-M",
base_product_id: "TSHIRT-001",
attributes: {color: "blue", size: "M"},
price_cents: 2499,
stock_available: 47
}
Cart Entry:
{
customer_id: "cust_xyz",
sku: "TSHIRT-BLU-M",
quantity: 2,
price_cents_when_added: 2499,
added_at: "2025-01-15T10:30:00Z"
}
Order:
{
order_id: "ord_abc123",
customer_id: "cust_xyz",
state: "payment_authorized",
line_items: [
{sku: "TSHIRT-BLU-M", quantity: 2, price_cents: 2499}
],
total_cents: 4998,
idempotency_key: "req_def456",
payment_intent_id: "pi_ext789",
created_at: "2025-01-15T10:35:00Z"
}
Part 2: Checkout Correctness
Flow Overview
- Checkout Initiation: Customer submits cart with a client-generated idempotency key.
- Idempotency Check: If an order with this key exists, return the existing order (handle retries).
- Price and Availability Validation: Re-fetch current SKU data. If prices changed, inform the customer. If stock is insufficient for any line, reject the order immediately.
- Atomic Reservation: Within a database transaction, decrement
stock_availablefor each SKU and insert the order inpendingstate. This transaction either succeeds completely or rolls back—no partial reservations. - Payment Authorization: Call payment provider with order total and a provider idempotency key derived from the order ID. Provider returns a payment intent ID.
- State Transition: Update order to
payment_authorized, storing the payment intent ID. - Capture and Confirmation: After authorization, immediately capture the payment. On success, transition order to
confirmedand enqueue fulfillment. On failure, transition tofailed, release inventory, and notify customer.
Handling Concurrency
Stock Contention: Use database-level locks or compare-and-set operations on stock_available. If two customers race for the last unit, one transaction commits and the other fails due to insufficient stock.
Duplicate Requests: The idempotency key (provided by client or generated from cart hash + timestamp) ensures that retrying a checkout request finds the existing order instead of creating a duplicate. Store the key in a unique index on the Order table.
Payment Recovery
Scenario: Payment authorization succeeds, but the HTTP response is lost before we can update the order state.
Solution: On retry, the idempotency check finds an order in pending state with no payment intent. Before creating a new payment, query the payment provider using the derived idempotency key. If a successful payment intent exists, update the order to payment_authorized without charging again. If not, proceed with a new payment attempt.
Webhooks: Payment providers send asynchronous notifications. Each webhook carries a unique event ID. Store processed event IDs to ensure idempotency: if the same event arrives twice, ignore the duplicate. Use the webhook to drive state transitions (authorization confirmed, capture succeeded, payment failed), reconciling with the order's expected state.
Failure Modes
- Insufficient Stock: Reject order immediately, before any payment attempt.
- Price Change: Optionally show updated price and require customer confirmation; or proceed with the new price if within a tolerance threshold.
- Payment Declined: Transition order to
failed, release reserved inventory, and provide a clear error message. - Payment Timeout: If the provider does not respond, poll for status asynchronously; keep order in
pendingwith a reconciliation job to eventually mark it failed or confirmed.
Part 3: Scaling and Operations
Scaling Reads
Catalog Browsing: Serve from a replicated search index (Elasticsearch, Algolia, or similar). Cache product detail pages and listing pages in a CDN or application cache. Since this data does not participate in transactional decisions, eventual consistency is acceptable.
Cart Reads: Store carts in a fast key-value store (Redis, DynamoDB) partitioned by customer ID. Cart operations are lightweight and do not touch inventory.
Scaling Writes
Checkout: Route checkout requests to a horizontally scaled order service. Each request is independent, partitioned by customer or order ID. Use a transactional SQL database (Postgres with row-level locking) or a distributed transaction coordinator for the reservation step.
Hot SKU Contention: When a limited-edition item drops, many customers race to buy. Pessimistic locking on stock_available serializes these transactions, creating a bottleneck. Mitigations:
- Optimistic Concurrency Control: Use version numbers or compare-and-set; retry failed transactions with exponential backoff.
- Backpressure: Return "high demand, try again" errors early to shed load rather than queuing doomed requests.
- Pre-allocation: For scheduled releases, partition stock across multiple shards or timeslots to reduce contention.
Durable Background Work
After order confirmation, enqueue fulfillment tasks (notify warehouse, send confirmation email) in a durable queue (SQS, RabbitMQ). Decouple confirmation from downstream steps so checkout remains fast.
Reconciliation and Monitoring
Order State Reconciliation: Periodically query orders stuck in payment_authorized for more than a threshold (e.g., 5 minutes). Cross-check with the payment provider. If payment succeeded, transition to confirmed. If failed, release inventory and mark failed. Alert on orders that remain unresolved.
Inventory Audit: Compare sum of reserved stock (from confirmed orders) plus available stock against the expected total. Detect leaks where inventory was decremented but no order exists, or vice versa.
Payment-Order Consistency: Reconcile daily: fetch all captured payments from the provider and ensure a corresponding confirmed order exists. Flag discrepancies for manual review.
Trade-offs Summary
- Stale Catalog vs. Real-Time Checkout: Accept eventual consistency in search to scale reads, but enforce transactional correctness at checkout to prevent overselling.
- Reservation Timing: Not reserving on cart addition avoids locking stock for abandoned carts but allows cart items to become unavailable. Communicate this clearly in UX ("availability confirmed at checkout").
- Idempotency Overhead: Storing idempotency keys and checking them on every request adds latency and storage, but is essential for correctness under retries and webhooks.
- Hot SKU Bottleneck: Pessimistic locking guarantees correctness but limits throughput on contested items. Optimistic concurrency and backpressure improve scalability at the cost of complexity and customer retries.
Common Mistakes
- Reserving inventory in the cart: Leads to locked stock for abandoned sessions and denial-of-service risk.
- Skipping idempotency: Allows duplicate orders and double charges under retry.
- Ignoring payment provider query API: Causes lost payments when responses are missed; always re-query provider state before assuming failure.
- No order state machine: Leads to ambiguous or inconsistent order status and makes recovery impossible.
- Assuming synchronous payment confirmation: External services fail or timeout; design for asynchronous reconciliation from the start.
A strong answer explicitly names the invariants (one order per idempotency key, stock decremented exactly once per confirmed order, payment captured exactly once), explains how the design enforces them, and acknowledges where complexity or latency is unavoidable.