Ch.75: System Design: Build an Amazon-Style Inventory Service
Outline
- 0:00 What inventory can promise
- 0:42 Follow a checkout request
- 1:22 Requirements and duplicate receipts
- 2:05 On hand versus available
- 3:31 Allocate across warehouses
- 4:31 Commit or release a hold
- 5:26 Shipping reduces two quantities
- 6:18 Returns and inspection
- 7:08 Counts and newer movements
- 8:29 Replay a shipment report
- 9:26 Two buyers and one stock owner
- 10:47 The whole service and final totals
Transcript
0:00 An inventory service tells a store what stock it can promise to an order. We'll design its core, from warehouse records through checkout, shipment and return. For example, our retailer records 15 chargers across two warehouses. Can checkout sell 15? No. Some already have a customer waiting for them; others are awaiting inspection. Counting them as sellable is the mistake: promising stock we can't supply. The storefront asks what's available. Checkout asks us to reserve stock for an order. Warehouse software reports what arrived or left.
0:30 Those callers need different answers from the same stock. The quantities and architecture are our exercise choices; the public sources are in the description. We'll follow seven chargers through the system. Before following those chargers, trace checkout's request. It enters the inventory API and reaches this product's stock owner, the only place allowed to change its quantities. The owner records which warehouse supplies the order. Why can't checkout just use the number on the storefront? That's a browsing view, which can lag.
0:58 Checkout needs the owner's current decision. Warehouse reports enter the same owner through the API, so a shipment and a reservation meet at one authority. What's the path back to the storefront if the service restarts after changing stock? Save the availability-update task with the change. After recovery, the dispatcher reads the pending update. Browsing catches up without redoing the allocation. We'll return to this map after the order. Next, look at this separate receipt. Two chargers arrived. The warehouse sends the report again. How do we keep that repeated report from adding two more chargers?
1:32 Record that receipt once. Functional requirements are what callers can ask us to do: accept warehouse arrivals, shipments, returns, inspections and counts. Checkout can reserve, commit or release stock. The storefront gets availability. Non-functional requirements set operating constraints on those actions: keep changes durable, transactions bounded, and duplicate or stale reports safe. Never allocate more than the recorded sellable stock. Yeah, recorded. We can make the database agree with itself while the shelf is still wrong.
1:58 A transaction can't supply a missing warehouse observation; the service must keep the discrepancy visible. Let's separate those stock promises. On hand is the recorded physical total. Held is temporarily reserved for checkout. Committed belongs to accepted, unshipped orders. Unavailable is stock excluded from sale. Take the West row: 10 on hand. Subtract three committed and one unavailable, with nothing held, and six are available. Those boxes don't all make the same promise. At East, one of the five recorded units is unavailable, leaving four to sell.
2:30 Across both locations, 15 on hand gives us 10 available. Available is derived, not another independently writable counter. My first thought was to include those three chargers coming into West. They're already on the truck. Can they help this checkout? Not under our promise. Incoming stays outside on hand until received. We aren't taking an order for stock that hasn't arrived. Ah, I was about to sell the truck's contents before it reached the warehouse. When it does arrive, what keeps a damaged delivery from becoming sellable?
3:03 Receiving adds the arrived units to on hand. Under our policy, anything needing inspection also enters unavailable. Both rise together, so those units add no available stock yet. That keeps physical possession separate from permission to sell. And our temporary hold is an extra category for this design, rather than an exact copy of a vendor's schema. Yes. Shopify's public inventory states ground the available, committed and unavailable distinctions. We'll keep our own hold category explicit as the order moves.
3:30 Now take a request for seven chargers that permits splitting. West has six available and East has four. Can either warehouse supply all seven? Neither can. We need six from West and one from East. If our policy required one warehouse, we'd reject this request despite 10 available across the network. Put this product's location rows under one transactional owner. Lock the selected rows in a consistent order, recheck eligibility and quantity, then save the allocation with held 6 and 1. Suppose East's recheck fails after West's tentative change.
4:04 The buyer asked for seven. What happens to West's six? Roll back the whole transaction. Checkout gets a complete allocation or failure. It doesn't get six with a success label. Both warehouses' rows must fit within that owner's transaction. And does that row stay locked while somebody types their card details? No. Release the database locks when this short transaction ends. The saved hold keeps those units reserved afterward; we don't keep the transaction open while waiting for payment or warehouse work.
4:31 So the row lock is gone, but the hold remains. If checkout abandons it, what should happen to those 7 units? In that alternative branch, release its six West units and one East unit. Held returns to 0; available returns to 6 and 4. On hand stays 10 and 5. No boxes moved. Back on our successful order, commit converts those seven held units into committed. West reaches nine committed, including three for earlier orders. East reaches one. Available stays 0 and 3. We accepted that order. I'd hate to turn its harmless retry into a rejection.
5:06 If checkout retries after the hold's deadline, which check comes first? Look up the saved commit first and compare its payload. We stored its identity, payload and result together. A matching retry gets that accepted result, even after the deadline. Reject changed payloads. Only a new commit needs an active, unexpired hold. Next, West ships six chargers and East ships one. Finishing an order sounds as though it should free an allocation. Does West gain six available? No, because those six boxes left.
5:37 Reduce on hand and committed together. Removing only the commitment would offer stock the warehouse no longer has. Working West's row, 10 physical units become four, and nine commitments become three. Its inspection unit leaves none available. East's physical total becomes four, with no commitments and three still available. Right. Shipping satisfies the promise; it doesn't replenish the shelf. The two downward arrows explain why available stays unchanged. What about a box for an earlier order, marked picked, meaning collected for that order, but still sitting in the warehouse?
6:09 Keep picked units inside committed until shipment. Picking records work progress; it creates no extra stock claim. Subtracting picked as well would count the same charger twice. Next, these two returned chargers enter West's inspection area. Our policy receives them into unavailable until inspection. West reaches six physical units. Three remain committed to earlier orders; three are unavailable, leaving zero to sell. Even if the customer already got a refund? Yes. Giving money back doesn't inspect the charger.
6:35 Receipt, refund and resale eligibility are separate decisions. Inspection now approves one of these two returns. Oh, one more charger is sellable, but the physical total is still six. Unavailable falls to two while available rises to one. The other return stays unavailable. That's our conservative inspection policy; another retailer could handle unopened goods differently. Whatever the policy, its eligibility change needs a recorded transition. And a repeated receipt mustn't add those same two chargers again.
7:03 After checking the shelf, we'll replay West's earlier shipment report against the newer stock. Next, check that returned stock against the shelf. A coordinated count finds five where West's book says six. Correct on hand to five, consuming its one available unit. Earlier commitments stay recorded; East keeps three available. A count never cancels an order. So West's five cover three committed units and two unavailable ones. That leaves zero available for another order. But what if somebody ships a box while that count report is on its way?
7:36 Take a separate stale-count test, not another step in our order. Reset on hand to six at revision seven. A shipment leaves five and advances the row to revision eight. Okay, the old count then asks to set six, conditional on revision seven. Reject it against eight. Accepting that overwrite would put the shipped box back into our records. Does that also prove nobody moved a box during the count? No. Coordinate the physical counting with movements, or reconcile movements around it. After this conflict, our service requests a fresh coordinated count.
8:10 Updating the old report's revision isn't a fresh observation. That retry worries me. We'd be changing the report, not recounting the boxes. Exactly. We need a new shelf observation. Our main trace still ends at West five, with none available. The revision test never shipped another charger from that order. Now West's earlier 6-unit shipment report arrives again. How do we avoid subtracting six a second time? It already has a saved result. Return that outcome, leaving current stock alone: West's on-hand quantity stays five and its committed quantity stays three.
8:45 Those later returns and the count still happened. That saved report is for this product at West, shipping six against this allocation. Its full payload must match. Reusing the warehouse's event identity with seven must be rejected. But a new report has no saved result. What do we check before accepting it? For a new event, we check authorization and the remaining allocation, then save its identity, stock change and dispatcher task together in one transaction. So there's no gap where stock changed but we forgot to save its browsing update.
9:17 Right. Replay recorded changes to rebuild that browsing view. Even when retries work, a scanner can report the wrong boxes. Fixing that needs new physical evidence. Now consider a separate checkout race: one available charger, two requests for one. Both saw the same cached badge. The first transaction saves its hold. What does the second get? It waits, rechecks current stock and finds 0. But if the waiting queue is full, we never reach that stock decision. I think Busy tells the operator what actually happened. Calling it Out of stock would imply we checked.
9:50 I'd keep both outcomes visible to the operator. More copies serving browsing reads won't shorten that stock owner's queue. Partition products across owners, keeping each product's warehouse rows together. A warehouse engineer might ask: could West and East write independently to relieve that queue? It could distribute location writes. But allocating seven would then need coordination between two owners, with failures between them. We chose one owner to keep that allocation atomic, so a popular product can fill its queue.
10:19 Suppose a basket also has another product on a different owner. Does our complete-allocation guarantee cover both? No. Checkout coordinates those separate reservations and exposes pending or partial outcomes. Our atomic unit covers one product's warehouse rows, rather than every independent stock owner in a basket. And even a valid allocation doesn't promise tomorrow's delivery. Our seven chargers needed two warehouses. Recheck eligible locations for allocation; estimate delivery separately. Now return from that race to our order.
10:47 Finally, return to the original map. Scanner reports pass through the inventory API to the product owner. Checkout asks that owner for a current allocation. Browsing reads the published availability view. The dispatcher carries saved changes outward. Rebuilding that view repairs published availability; a coordinated warehouse count corrects records against the shelf. Those are different repair jobs. Our worked order leaves nine on hand in the network, with three available. There are three earlier commitments, plus 3 units excluded from sale.
11:16 All seven chargers in the illustrated order shipped. So those nine remaining chargers still don't mean nine new sales. 15 was a physical total, never a promise that checkout could sell 15. Right. We can replay every message and still need somebody to count the chargers. Thanks for listening to Learning Podcasts.