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

In a database

When memory is not enough

The point: two processes do not share a lock. The condition has to travel to where the number is.

Statement

Check and change in one update

Python
import sqlite3db = sqlite3.connect(":memory:")db.executescript("""CREATE TABLE line (  sku TEXT, place TEXT,  on_hand INT NOT NULL CHECK (on_hand >= 0),  held INT NOT NULL CHECK (held >= 0),  PRIMARY KEY (sku, place),  CHECK (held <= on_hand));CREATE TABLE promise (order_id TEXT PRIMARY KEY, status TEXT NOT NULL);CREATE TABLE pick (order_id TEXT, sku TEXT, place TEXT, qty INT);INSERT INTO line VALUES ('plum','cellar',6,0), ('fig','cellar',4,0);""")def reserve(order_id, picks):    try:        with db:                                             # commit, or roll back on an exception            db.execute("INSERT INTO promise VALUES (?, 'held')", (order_id,))            for sku, place, qty in sorted(picks):            # one order of locking for everybody                done = db.execute(                    "UPDATE line SET held = held + ? WHERE sku=? AND place=? AND on_hand - held >= ?",                    (qty, sku, place, qty))                if done.rowcount != 1:                    raise LookupError(sku)                db.execute("INSERT INTO pick VALUES (?,?,?,?)", (order_id, sku, place, qty))        return True    except LookupError:        return Falseassert reserve("a", [("plum", "cellar", 2), ("fig", "cellar", 1)])assert not reserve("b", [("fig", "cellar", 1), ("plum", "cellar", 9)])assert db.execute("SELECT sku, held FROM line ORDER BY sku").fetchall() == [("fig", 1), ("plum", 2)]try:    reserve("a", [("plum", "cellar", 1)])except sqlite3.IntegrityError:    print("order a exists already")
rowcount is the answer. Reading first and updating later would be the same race as before, only slower.
Edit and run it in your browser

Ship

One ending, with a condition

SQL
BEGIN;UPDATE promise SET status = 'shipped' WHERE order_id = 'a' AND status = 'held';-- 1 row: we are the one who ships. 0 rows: shipped, released or expired already.UPDATE line SET on_hand = on_hand - 2, held = held - 2 WHERE sku = 'plum' AND place = 'cellar';INSERT INTO movement (kind, sku, place, change, ref) VALUES ('shipped', 'plum', 'cellar', -2, 'a');COMMIT;
The status update comes first. It locks the row of the promise, so the sweeper and the packer cannot both win.

Compare

Three ways to be safe

WayHowGood whenCost
Conditional updateThe condition is in WHEREThe change is a sumShort row lock
Row lock firstSELECT ... FOR UPDATE, then decide in codeThe decision needs several rowsLocks held while code thinks
Version numberWHERE version = 17, try again on 0 rowsConflicts are rareMany retries on a hot row
PostgreSQL advises to take locks on several objects in a consistent order, which is what the sort does. Levels of isolation are on isolation levels.

Failure walk

Stop it at every line

StoppedAfter the restart
Before commitRolled back. The caller repeats with the same order id
After commit, before the answerThe insert fails on the key: look up the promise and return it
Between status and movementCannot be seen: one transaction
After commit, before the alertLost, unless the alert is a row in the same transaction that a worker sends

The plan came from a policy in code. Is it still true in the database?

BreaksAssume so
How
Update without a condition
Limit
Held above on hand, or an error from the check at best.
Choose when
Never.
WorksLock all lines of the product, then plan
How
FOR UPDATE on the rows, plan in code, update.
Limit
All orders for one product wait for each other while code runs.
Choose when
Few places, moderate traffic.
StrongPlan on a read, update with the condition, plan again on failure
How
The condition decides. Two or three tries.
Limit
A bound and a fallback are needed.
Choose when
The default.