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
Implementation
The code, in the order to write it
The point: write the guarded line first. When two counts cannot go wrong, the rest is bookkeeping.
First half
Small things that keep a rule
Records and the guarded line
What has to be remembered: what moved, what was promised, and how a promise ended.
import itertoolsfrom dataclasses import dataclassfrom enum import Enumfrom threading import Lockfrom typing import Callable, Mapping, Protocolclass OutOfStock(Exception): """Not enough is available. Nothing was held."""class NotHeld(Exception): """The reservation is unknown, finished or expired."""class Kind(Enum): RECEIVED = "received" SHIPPED = "shipped" COUNTED = "counted"class Status(Enum): HELD = "held" SHIPPED = "shipped" RELEASED = "released" EXPIRED = "expired"@dataclass(frozen=True)class Movement: seq: int kind: Kind sku: str place: str change: int ref: str@dataclass(frozen=True)class Pick: sku: str place: str qty: int@dataclassclass Reservation: id: int order_id: str picks: tuple[Pick, ...] expires_at: int status: Status = Status.HELDLines 8 to 13
Two failures with names. A caller can show "sold out" for one and "your basket has expired" for the other. A plain ValueError would mix them with programming mistakes.
Why it is built this way
- A movement has
ref(an order, a delivery note), because the first question about a wrong count is always "why?". - Time is a plain number of seconds here, handed in from outside.
Second half
The coordinator
Inventory: the verbs
The coordinator owns the lines, the promises and the diary. What can vary is handed in.
LowStock = Callable[[str, str, int], None]class Inventory: def __init__(self, policy: PickPolicy, now: Callable[[], int], on_low: LowStock) -> None: self._policy = policy self._now = now self._on_low = on_low self._lines: dict[tuple[str, str], StockLine] = {} self._reservations: dict[int, Reservation] = {} self._movements: list[Movement] = [] self._ids = itertools.count(1) self._lock = Lock() def add_line(self, sku: str, place: str, low_at: int = 0) -> None: with self._lock: if (sku, place) in self._lines: raise ValueError("this product is already kept in this place") self._lines[sku, place] = StockLine(sku, place, low_at) def receive(self, sku: str, place: str, qty: int, ref: str) -> None: with self._lock: line = self._lines[sku, place] line.add(qty) self._write(Kind.RECEIVED, line, qty, ref) line.became_low() def available(self, sku: str) -> int: with self._lock: return sum(x.available for x in self._lines.values() if x.sku == sku) def _write(self, kind: Kind, line: StockLine, change: int, ref: str) -> None: seq = len(self._movements) + 1 self._movements.append(Movement(seq, kind, line.sku, line.place, change, ref))Lines 5 to 8
Policy, clock and listener come from outside. A test can stand at any second and read every alert.
Why it is built this way
availablewalks all lines. An index by product is the first thing to add for many products.- No global instance: two shops in one test are two objects.
Languages
What differs, and why
| Python | Java | C++ | TypeScript | |
|---|---|---|---|---|
| No plan | None | Optional | std::optional | null |
| Key of a line | Tuple | Record LineKey | std::pair | JSON of the two names |
| Policy must not write | By convention | By convention | const StockLine* | Private fields |
| Lock | Lock | ReentrantLock | std::mutex | Not needed without await |
| Reservation given out | The object itself | Status is read only | A copy | The object itself |
sku + place would make ab + c and a + bc the same line. Use a pair.Python and TypeScript hand out the live reservation. A caller could change its status. If that worries the interviewer, return a frozen copy, as the C++ version does.