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
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.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;Compare
Three ways to be safe
| Way | How | Good when | Cost |
|---|---|---|---|
| Conditional update | The condition is in WHERE | The change is a sum | Short row lock |
| Row lock first | SELECT ... FOR UPDATE, then decide in code | The decision needs several rows | Locks held while code thinks |
| Version number | WHERE version = 17, try again on 0 rows | Conflicts are rare | Many retries on a hot row |
Failure walk
Stop it at every line
| Stopped | After the restart |
|---|---|
| Before commit | Rolled back. The caller repeats with the same order id |
| After commit, before the answer | The insert fails on the key: look up the promise and return it |
| Between status and movement | Cannot be seen: one transaction |
| After commit, before the alert | Lost, 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 UPDATEon 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.