Build a Shopping Cart Backend for Meal Ordering
System DesignModel answerLast updated
Design a scalable, highly available cart service for a meal-ordering app, covering APIs, storage, price drift handling, concurrent edits across devices, and consistency trade-offs.
Scenario
You are building the backend that manages a customer's cart on a large meal-ordering marketplace. A customer browses a restaurant, collects dishes (with options such as sizes, toppings or special notes), and later checks out. Customers often start on a phone and continue on a laptop, and the service must keep working during the dinner rush.
What the service must do
- Let a customer add dishes to a cart, including chosen options.
- Let them change quantities or remove dishes.
- Return the cart on demand, with computed totals and an indication of whether the restaurant and each dish can currently be ordered.
- Keep the cart saved so it appears on any device the customer signs in from.
Quality goals
- Fast reads and writes.
- Editing keeps working even when some neighbouring internal services are slow or overloaded.
- Prices shown must follow what the restaurant's menu service currently reports.
What to deliver
- A high-level architecture, described or sketched.
- An API design covering add, update, remove and get.
- A storage schema listing the stored fields.
- A plan for stale data, for example a dish whose price changes or which becomes unavailable after being added.
- A discussion of strong versus eventual consistency and where each fits.
State your traffic assumptions explicitly and explain how they shape your choices.
Hints
Hint 1
Estimate the scale first (daily carts, mutations per cart, peak multiplier, bytes per cart). The data volume turns out small, so the hard parts are latency, availability and correctness rather than storage size.
Hint 2
Think of the cart as a draft and the order as a binding contract. Which operations can tolerate slightly stale prices, and which must recompute authoritatively?
Hint 3
Separate the concurrency problems: duplicate requests from one device, simultaneous adds from different devices, and conflicting edits to the same line each need a different mechanism.
Hint 4
Decide what happens when the pricing or menu dependency is down. Edits should still succeed, reads should degrade gracefully, and only checkout should refuse to proceed.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
1. Assumptions and scale
State numbers up front so the design is grounded:
- About 30M daily active users, about 10M orders per day, and many abandoned carts, so roughly 25M carts touched per day.
- About 10 mutations per cart gives about 250M writes per day, around 3K writes/s on average and about 15K/s at a 5x dinner peak.
- Every mutation re-renders the cart, so reads run 2-3x writes: roughly 40K reads/s at peak.
- A cart is 2-4 KB, so about 100 GB of active data. Storage is not the challenge.
- Targets: p99 under 100 ms for writes and under 200 ms for reads (which include repricing).
- Scope: one restaurant per cart; carts expire after about 7 days idle. Multi-restaurant carts are a follow-up.
Guiding principle: the cart is a draft, the order is the contract. Browsing can show slightly stale prices; checkout cannot.
2. API design
All endpoints are scoped to the authenticated user, taken from the token rather than the URL.
GET /v1/cart
-> { cart_id, version, restaurant, lines[], subtotal, fees, total,
warnings[], pricing_status: "live" | "estimated" }
POST /v1/cart/items (Idempotency-Key header)
body: { restaurant_id, menu_item_id, quantity, customizations[], notes }
PATCH /v1/cart/items/{line_id} (If-Match: version)
body: { quantity, customizations? }
-> 200 full cart | 409 with current cart
DELETE /v1/cart/items/{line_id} (If-Match: version)
POST /v1/cart/checkout-quote
-> { quote_id, expires_at, authoritative totals, changes[] }
Choices to call out:
- Mutations return the full cart, so clients never compute totals.
- Idempotency keys make retries and double taps safe.
- Version checks (
If-Match) prevent lost updates when two devices edit the same cart.
3. Data model
Cart access is always by user, with high churn and no cross-user joins or transactions. A key-value or wide-column store (DynamoDB, Cassandra) fits better than a relational database. Redis is fast but a weaker system of record; use it only as an optional cache, since the primary store already gives single-digit-millisecond reads.
One partition per user, one item per row:
| Key | Fields |
|---|---|
user_id / META | cart_id, restaurant_id, version, status, updated_at, ttl |
user_id / LINE#<line_id> | menu_item_id, quantity, customizations (option IDs only), notes, snapshot_unit_price, menu_version, added_at |
user_id / IDEM#<key> | response_hash, ttl (~24h) |
Rules:
line_id = hash(menu_item_id + sorted customizations), so identical configured dishes merge into one line.- Store IDs and a price snapshot, never a copy of the menu. Names and images are hydrated from a menu cache at read time.
- A TTL attribute removes abandoned carts automatically.
4. Architecture
Client -> API Gateway (auth, rate limit)
-> Cart Service (stateless, autoscaled)
|- Cart Store (home-region strong reads)
|- Menu/Pricing Service (short-TTL local cache)
|- Availability Service
|- Promotions Service (best effort)
Event bus: menu.updated, item.availability -> cache invalidation, client push
Checkout Service -> authoritative pricing -> creates order
The Cart Service owns only cart state. Pricing logic lives in the Pricing service so the cart and checkout compute prices identically.
Read path: load the partition in one query, batch-fetch current prices and availability, compute totals, diff against snapshots, and emit warnings[].
5. Stale data and price drift
Three tiers:
- On add: validate that the dish exists, options are legal, and the restaurant is open. Save a price snapshot and the menu version.
- On view: reprice using a menu cache with a 30-60 s TTL, also invalidated by
menu.updatedevents. Annotate lines withPRICE_CHANGED(old and new price),UNAVAILABLE(greyed out, excluded from total) orOPTION_REMOVED. Never silently delete lines. - At checkout: bypass caches and reprice authoritatively, issuing a short-lived
quote_id. If the total differs from what the user last saw, return the changes and require reconfirmation. Never charge a price the customer did not see.
Graceful degradation: if Pricing is slow or down, writes still succeed because they touch only the cart store. GET falls back to snapshot prices with pricing_status: "estimated". Checkout fails closed.
6. Concurrency
Three separate problems, three fixes:
- Retries and double taps: the idempotency key. The first request writes the
IDEM#row and the line in one transaction; a replay returns the stored response. - Simultaneous adds from different devices: both should succeed. Different items are different rows and cannot conflict. For the same line, use an atomic increment rather than read-modify-write, and bump
META.versionin the same transaction. - Conflicting edits (one device sets quantity 3, another deletes the line): optimistic concurrency with a conditional write on
version. On failure return 409 with the current cart so the client re-renders. Avoid locks, which hurt latency and availability.
Push a "cart changed" event over the existing socket or push channel so other devices refresh quickly.
7. Consistency trade-offs
| Data | Choice | Reason |
|---|---|---|
| Cart contents | Strong within the home region (strong reads, conditional writes) | Users must see their own edits immediately |
| Cross-region replica | Asynchronous | Used for failover; a few seconds of lag is acceptable, and it avoids cross-region write latency |
| Menu prices and availability in the cart view | Eventual (cache plus events) | Keeps reads fast and tolerates dependency outages |
| Checkout totals | Strong, authoritative | Money is involved; correctness beats latency |
The trade-off is explicit: favour availability and latency for the draft, favour correctness for the contract.
8. Common mistakes
- Storing full menu copies in the cart, which goes stale and bloats rows.
- Recomputing prices on the client.
- Using locks or a relational multi-row transaction for every edit.
- Failing cart reads when the pricing service is down.
- Silently dropping unavailable items instead of telling the user.
- Skipping idempotency, which creates duplicate lines on flaky mobile networks.
- Trusting cached prices at checkout.
9. Follow-ups
- Multi-restaurant carts: key lines by restaurant and quote each group separately.
- Guest carts: key by device ID, then merge into the user cart on login, summing quantities for matching
line_ids. - Group orders: a shared cart with per-participant line ownership and the same versioning scheme.