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.
Watch lesson4:28
Low stock
One message, at the right moment
The point: an alert is about crossing a line and not about being below it. And it must never be able to stop a sale.
Edge
Crossing against being
| Available after the call | Mark at 2: naive | Crossing |
|---|---|---|
| 5 | quiet | quiet |
| 2 | ||
| 1 | quiet | |
| 0 | quiet | |
| 1 (a release) | quiet | |
| 6 (a delivery) | quiet | armed again |
| 2 |
Flutter
A basket that comes and goes
Baskets expire all the time. Available jumps 3, 2, 3, 2 around the mark, and each way down is a real crossing. The cure is two marks: ring at 2, and arm again only above 4. This is called hysteresis, and a heating thermostat does the same.
class Bell: def __init__(self, ring_at, arm_above): if arm_above < ring_at: raise ValueError("arm above the ring mark") self.ring_at, self.arm_above = ring_at, arm_above self.armed = True def rings(self, available): if self.armed and available <= self.ring_at: self.armed = False return True if available > self.arm_above: self.armed = True return Falsedef run(bell, values): return [v for v in values if bell.rings(v)]flutter = [5, 2, 3, 2, 3, 2, 6, 2]assert run(Bell(2, 2), flutter) == [2, 2, 2, 2]assert run(Bell(2, 4), flutter) == [2, 2]print("ok")Delivery
Who carries the message, and when
Where is the listener called?
BreaksInside the lock
- How
self._on_low(...)in the middle ofreserve- Limit
- A slow mail server stops all sales. A listener that calls
availablewaits for a lock its own thread holds. - Choose when
- Never.
WorksAfter the lock, in the same thread
- How
- Collect under the lock, tell after it.
- Limit
- The customer waits for the listener. Two threads may deliver their news in the other order.
- Choose when
- Short listeners, such as putting into a queue.
StrongInto a queue, with a number
- How
- Under the lock append
(number, sku, place, left)to a queue. One worker sends. - Limit
- One more thread, and messages that wait when the process dies.
- Choose when
- Real mail. If a lost alert matters, store the queue with the change.
What counts
Low in one place, or in all?
A shop manager wants to know that the shed is nearly empty, to carry jars over. A buyer wants to know that plum jam is nearly gone everywhere, to order more. These are two bells with two marks: one on the line, one on the product. Say which one you build.