Lesson 8 of 16
42. Design E-commerce Cart and Checkout (Amazon / Flipkart)

42.7 How do you reserve inventory?

3 min read+10 XP

reading stock and then subtracting oversells 150 of 100 phones; a conditional update sells exactly 100, with holds that expire.

Figure: check and subtract in one statement, and hold stock only while the shopper pays.

  • Never read, check, then subtract in separate steps: concurrent buyers all see the same stock. In the chapter's code, 150 buyers reading "100 left" all succeed: oversold by 50.
  • Use a conditional update (Chapter 17): UPDATE inventory SET available = available - 1 WHERE sku = ? AND available >= 1. One row updated means you got it. In the chapter's code, 150 concurrent buyers produce exactly 100 successes.
  • Hold, don't sell: a successful reservation is a 10-minute hold tied to the order. Paid orders confirm it; abandoned ones expire and go back on sale. In the chapter's code, 70 buyers pay and 30 walk away; the 30 holds expire and those phones are available again.
  • Spread hot stock: split a popular item's stock across warehouses or buckets (rows) so not every buyer locks the same row; pick a bucket by hash and fall back to others when it's empty.
  • Flash sales with far more buyers than stock need a queue or waiting room in front (Chapter 43).

Memory code: "Subtract only if enough, in one move, and let unpaid holds expire."