Design an Inventory System
medium 45 minCount 10 million products in 100 warehouses and never promise a unit twice.
See it run
Follow the three numbers of one product while people hold, pay, leave, deliver and count.
Operations
Hold and confirm
From checkout to a paid order. Eight mugs are on the shelf.
Step 1 of 8
Browse
on hand
8
held
0
allocated
0
available
8
The product page shows the number in Redis. It may be five seconds old.
Step 1: Browse
hold: UPDATE stock SET held = held + 2 WHERE on_hand - held - allocated >= 2 INSERT hold line (HELD, now + 15 min)pay: authorize the cardconfirm: HELD -> ALLOCATED held -= 2, allocated += 2pay: capture the money- Locks
- one row, about 2 ms
- Leaves
- a hold line
Look at the number of rows changed. Zero means sold out.
In the real world
The same design an inventory system doing real jobs. Pick one and step through it.
The bank answers at minute 16.
Step 1 of 5
Paying slowly
on hand
8
held
2
allocated
0
available
6
The bank asks the shopper for a code. Two mugs are held.
Step 1: Paying slowly
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Read, subtract, write
criticalTwo requests read the same number and both succeed.
Wrongn = select_count(sku)if n >= 1: update_count(sku, n - 1)RightUPDATE stock SET held = held + 1 WHERE sku = $1 AND on_hand - held - allocated >= 1A TTL that frees nothing
criticalThe hold key disappears, but the counter still includes it.
WrongINCRBY held:mug 2SET hold:789 2 EX 900Right-- state and count change togetherHELD -> EXPIRED, held = held - 2SKIP LOCKED for a buyer
majorIt skips the only row and answers sold out.
WrongSELECT * FROM stock WHERE sku = $1 FOR UPDATE SKIP LOCKEDRight-- wait for the row, then check againUPDATE stock ... WHERE ... >= $2Deciding from the cache
criticalThe cached number is seconds old.
Wrongif redis.get("mug") > 0: sell()Rightshow(redis.get("mug"))sell only if the UPDATE changed a rowEditing history
majorNobody can explain a difference any more.
WrongUPDATE movements SET quantity = 7RightINSERT movement (-1, 'count', 'broken')
Interview tips
Draw the row first
- On hand, held, allocated.
- Available is computed.
- Every step changes two numbers at most.
Give it an end
- 15 minutes at checkout.
- Only HELD can be confirmed or expired.
- The server's clock decides.
Size it
- 58 holds a second at peak: one primary.
- 35,000 reads on a sale day: cache.
- 20,000 updates: eight shards.
Expect to be wrong
- Count some shelves daily.
- Corrections are new lines.
- Shortages are handled early.