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

Retries

The same order asked twice

The point: a caller that got no answer will ask again. The order id is the key that turns the second request into a lookup.

Failure walk

Where the answer can be lost

Stopped hereStateThe caller repeats reserve(order-7)
Before the holdNothingA normal first call
After the hold, before the answerHeldMust find the first promise, not hold again
After the answerHeldA double click: same promise
After the promise expiredExpiredA decision: hold again, or say that it ended
After it shippedShippedSay shipped. Never hold again

Code

One key, one content

Python
class Conflict(Exception):    """The same key with another content."""class Desk:    def __init__(self, free):        self.free = dict(free)        self.by_order = {}              # order id -> (wanted, reservation)    def reserve(self, order_id, wanted):        wanted = dict(wanted)        seen = self.by_order.get(order_id)        if seen:            if seen[0] != wanted:                raise Conflict(order_id)            return seen[1]              # the same promise, whatever became of it        if any(self.free.get(sku, 0) < qty for sku, qty in wanted.items()):            return None                 # a refusal is not remembered        for sku, qty in wanted.items():            self.free[sku] -= qty        reservation = {"id": len(self.by_order) + 1, "status": "held"}        self.by_order[order_id] = (wanted, reservation)        return reservationdesk = Desk({"plum": 5})first = desk.reserve("order-7", {"plum": 2})again = desk.reserve("order-7", {"plum": 2})assert first is again and desk.free["plum"] == 3try:    desk.reserve("order-7", {"plum": 4})    raise AssertionError("should conflict")except Conflict:    passassert desk.reserve("order-8", {"plum": 9}) is Nonedesk.free["plum"] += 10                 # a deliveryassert desk.reserve("order-8", {"plum": 9}) is not Noneprint("ok")
Lookup and hold are in the same locked block in the real class. Otherwise two copies of the request both find nothing.
Edit and run it in your browser

Decisions

Four that must be said

QuestionAnswer hereReason
Is a refusal remembered?NoA delivery may come, and the customer may try again
Same key, other content?An errorGuessing which one is meant would hide a bug in the shop
Ship twice?NotHeld in our codeA caller that retries may prefer the first answer. Then return the shipped reservation when the status is already SHIPPED
How long are keys kept?As long as orders can be repeatedClosed promises can move to a file after some days
Between services the same idea is called an idempotency key.

Who makes the key?

BreaksThe inventory
How
A new number for each call
Limit
The caller never sees the number of a lost answer, so the repeat gets a new one.
Choose when
Never for this purpose.
WorksA hash of the content
How
Same customer, same jars, same key
Limit
A customer who really wants the same again tomorrow is refused.
Choose when
With a time window, for double clicks only.
StrongThe caller, before the first try
How
The order id, made when the basket is confirmed
Limit
Callers must keep it until they get an answer.
Choose when
Always.