Design an inventory management system
medium 80 minCount goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.
Video lesson · Chapter 1 of 6
Make a prediction
See it run
Two counts for each line. Watch which one moves, and when.
Operations
Reserve an order
Plan both products, then hold both.
Step 1 of 7
Before
Plum: 6 in the cellar, 3 in the shed. Fig: 4. Nothing is held.
Step 1: Before
def reserve(self, order_id, wanted, seconds): with self._lock: picks = [] for sku, qty in wanted.items(): plan = self._policy.plan(qty, self._lines_of(sku)) if plan is None: raise OutOfStock(sku) picks.extend(plan) for pick in picks: self._lines[pick.sku, pick.place].hold(pick.qty) res = Reservation(next(self._ids), order_id, tuple(picks), self._now() + seconds) self._reservations[res.id] = res news = self._low_news(picks) self._tell(news) return res- Cost
- O(products × lines)
- Guarantee
- All or nothing
The upper half reads. The lower half writes.
In the real world
The same inventory doing real jobs. Pick one and step through it.
Five leave, four arrive.
Step 1 of 4
Seven in the cellar
Transfer T1 will carry five to the shed.
Step 1: Seven in the cellar
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Ask, then act
criticalAnother order may come between the question and the change.
Wrongif inventory.is_in_stock(sku, 1): inventory.decrement(sku, 1)Rightres = inventory.reserve(order_id, {sku: 1}, 900)Holding while planning
criticalWhen the third product is missing, two are held by nobody.
Wrongfor sku, qty in wanted.items(): line(sku).hold(qty) # may raise halfwayRightpicks = [plan(sku, qty) for ...] # may raisefor pick in picks: hold(pick) # cannotLowering available twice
criticalThe jar was subtracted when it was held and again when it left.
Wrongdef ship(self): self.on_hand -= qty # held staysRightdef ship(self): self.held -= qty self.on_hand -= qtyA listener under the lock
majorA slow mail server stops every sale.
Wrongwith self._lock: line.hold(qty) mailer.send(...)Rightwith self._lock: line.hold(qty) news = ...tell(news)A key made by joining text
majorab + c and a + bc become the same line.
Wronglines[sku + place]Rightlines[sku, place]Trusting the sweeper
majorIf it is late, an overdue promise still ships.
Wrongif res.status is Status.HELD: ship()Rightif res.status is Status.HELD and now < res.expires_at: ship()
Interview tips
Open with
- On hand, held, available.
- A line is product and place.
- Reserve is the hard verb.
Reject aloud
- Product is a key here.
- Order is an id.
- No Singleton.
Prove it
- Last jar, two orders.
- Half an order.
- Second scan.
Never
- A stored available.
- A hold without an end.
- Mail under the lock.