Full answer
text
carts(id, customer_id NULL, anon_token UNIQUE NULL, status, created_at, updated_at,
CHECK (customer_id IS NOT NULL OR anon_token IS NOT NULL))
cart_items(cart_id FK, product_id FK, qty CHECK (qty > 0), price_at_add_cents,
PRIMARY KEY (cart_id, product_id))- Adding the same product twice upserts the item and increases qty.
price_at_add_centslets the UI warn when the price changed; checkout uses the current price.- Merging on login: upsert each anonymous item into the customer cart, summing quantities, then delete the anonymous cart, all in one transaction.
- A partial unique index allows only one active cart per customer.
- Abandoned carts feed reminder emails; then retention removes them.
Stock is not reserved at add-to-cart time in most shops; reservation happens at checkout, which keeps carts cheap.
Key points
- Carts owned by a customer or anonymous token
- Upsert items by product
- Merge carts on login in one transaction
- One active cart per customer
- Expire abandoned carts
Common mistakes
- Storing carts only in browser storage
- Reserving stock when items are added
Follow-ups
- How would you handle a product that goes out of stock in a cart?
- How would you compute cart abandonment rate?
Tips
- Describe the merge step