Design a shopping cart service. How would you handle inventory changes while items are already in users' carts?
How I frame it
Cart is intent to buy, not a stock reservation. Inventory can hit zero while item sits in cart for days. Validate at checkout reserve, not on every cart add.
Data model
carts(id, user_id, updated_at)cart_items(cart_id, sku, qty, price_snapshot, added_at)- Cart in Redis for speed; persist to DB on checkout or periodic flush.
Handling inventory changes
- On cart load: Batch availability check — mark items Unavailable / Only 2 left. Do not silently remove without UX message.
- Price snapshot: Store
price_at_add; at checkout show "Price updated ₹X → ₹Y" if changed. - Reserve at checkout: Atomic hold (flash-sale pattern) before payment — cart qty > available → block with clear error.
- No long-lived holds in cart: Prevents inventory locked by abandoned carts.
User added iPhone (stock 10) Monday Friday stock 0 → cart shows "Unavailable at checkout" Checkout → reserve() fails → suggest remove / notify-me
Walkthrough
User adds 2× headphones Monday (stock 50). Tuesday flash sale sells out. User opens cart Wednesday — batch check marks "Out of stock." User proceeds anyway → checkout calls reserve(sku, qty) → fails atomically → clear error with remove-item CTA. No payment captured, no oversell.
Weak answer
"Reserve inventory when item is added to cart." Abandoned carts lock stock for hours; flash sales die. "Remove unavailable items silently" — user confused at checkout with missing items they expected.
Follow-up questions
Merge cart on login across devices?
Union SKUs; re-validate availability on merge; higher qty wins or sum with cap at available stock message.
Promo price ends while in cart?
Checkout uses current price engine; show delta. Promo locked only if explicit voucher held with TTL.