AlgoViz

Design an inventory management system

medium 80 min

Count goods in several places, promise them to orders without ever promising too much, ship or let go, and explain every count.

Watch lesson4:28

Expiry

Promises that end by themselves

The point: expiry is decided by the clock when somebody asks, and cleaned up by a sweeper. The sweeper is housekeeping; correctness does not depend on it.

Two moments

Overdue, and swept

Who looksAt 899At 900At 903, sweeper was late
shipWorksRefused, gives backRefused
releaseWorksRefused, gives backRefused
availableCounts as heldStill counts as heldFree after the sweep
Between the end and the sweep the shop shows too few. That is the safe side: it never shows too many.

Structure

A heap, with lazy removal

Walking all promises each second is wasteful: most are not due. A heap keeps the next one on top. Shipped promises are not searched for in the heap. They are thrown away when they reach the top.

Python
import heapqclass Promises:    def __init__(self):        self.open = {}           # id -> end        self.heap = []           # (end, id), may hold ids that are closed already    def add(self, rid, end):        self.open[rid] = end        heapq.heappush(self.heap, (end, rid))    def extend(self, rid, end):        if rid not in self.open:            raise KeyError("closed already")        self.add(rid, end)       # the older entry stays in the heap and is ignored    def close(self, rid):        return self.open.pop(rid, None) is not None    def due(self, now, limit=100):        out = []        while self.heap and self.heap[0][0] <= now and len(out) < limit:            end, rid = heapq.heappop(self.heap)            if self.open.get(rid) == end:        # not shipped, and not extended                del self.open[rid]                out.append(rid)        return outp = Promises()p.add(1, 900); p.add(2, 300); p.add(3, 600)p.close(3)                       # shippedp.extend(2, 1200)                # the customer asked for more timeassert p.due(900) == [1]assert p.due(1199) == [] and p.due(1200) == [2]print("ok")
Push and pop cost O(log n). limit keeps each visit short, so that a thousand overdue promises do not hold the lock in one go.
Edit and run it in your browser

Race

Payment arrives in the last second

Money was taken and the jar is gone. The inventory was right; the order of steps in the shop was not.

How do you avoid taking money for a jar that is gone?

BreaksIgnore the end if the card was accepted
How
ship skips the check when paid.
Limit
The jar may be promised to somebody else. Held would go below zero or a second customer loses.
Choose when
Never.
WorksReserve again, or refund
How
Try a new reserve. If sold out, give the money back.
Limit
Sometimes a customer pays and gets an apology.
Choose when
Always as the last net.
StrongConfirm before the charge
How
A step start_payment(id) extends the promise while the card is asked, with a hard limit, for example five minutes.
Limit
One more state, and a card that hangs holds jars a little longer.
Choose when
When paying takes seconds. With the last net behind it.