Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 40 ยท Projects

Project: Inventory Reservation Service

Build an inventory service in Python with a stock ledger, time-limited reservations, an expiry sweep, and a deterministic simulation that shows how check-then-act overselling happens.

Two shoppers click "Buy" on the last item within the same second. Who gets it? In this project you will build the small service that answers that question correctly: an inventory service with an append-only stock ledger, time-limited reservations, an expiry sweep and a concurrency simulation that makes the classic overselling bug visible, then fixes it.

The concepts come from inventory tracking and reservations and overselling. Here you put them into one program. Python in the browser has no real parallel threads, so the simulation uses a tiny scheduler that interleaves two buyers step by step. The result is the same race that a database sees, but it is completely repeatable, which makes it easier to study.

The model

The service tracks three numbers per SKU, and only one of them is ever stored directly.

  • On hand is the sum of all ledger entries for the SKU: receipts add, sales and write-offs subtract. It is derived from the ledger, never overwritten, so you can always explain how you arrived at the number.
  • Reserved is the quantity held by reservations that are still active and not past their expiry time.
  • Available is on hand minus reserved. This is the only number the storefront may sell from.
stateDiagram-v2
  [*] --> active: reserve
  active --> committed: commit (sale)
  active --> released: release (cart cleared)
  active --> expired: sweep after TTL
  committed --> [*]
  released --> [*]
  expired --> [*]

A reservation holds stock for a short time and ends in exactly one of three ways.

A reservation is not a sale. It says, "this quantity is promised to this cart until this time". If payment succeeds, you commit it, which writes a negative ledger entry (a sale). If the customer abandons the cart, you release it. If nobody does anything, the sweep marks it expired, and the units become available again. Three rules keep the design honest:

  1. Every change to quantity is a ledger row with a reason; nothing edits a counter in place.
  2. Reservation state moves in one direction only, from active to a final state.
  3. Reserving must check availability and record the hold as one indivisible step.

Step 1: ledger, reservations and the sweep

The clock is injected rather than read from the machine, so the output is the same every time you run it.

Python The inventory service: ledger, reserve, commit, sweep

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Look at what each line of output proves. After the TTL passes, available returns to 1 even before the sweep runs, because reserved() ignores holds past their expiry. That makes the time rule self-enforcing. The sweep only tidies: it moves the record to its final state and gives you a count to log. A commit attempted after expiry is refused; the shop must re-check stock, and may need to tell the customer.

Choosing the TTL

A hold that is too short loses customers who are mid-payment; one that is too long lets bots lock up stock. Common practice is a few minutes after the customer enters checkout or starts payment, with a longer hold only for carts where stock is plentiful. Reserve at checkout, not at "add to cart" for popular items, and extend a hold when you know a payment is in progress, since a card that needs 3-D Secure takes longer.

Step 2: the race condition

The reserve method above looks safe, and in a single thread it is. But in a real web server, two requests run at the same time. The danger is any gap between reading the availability and writing the reservation. This is the check-then-act race: both buyers read "1 available", both decide it is fine, and both write.

The simulation below models each buyer as a Python generator. A yield marks a point where the scheduler may switch to the other buyer, as the operating system or database might. In the naive version, the gap sits between the check and the write. In the safe version, the check and the write happen with no yield between them: that is what a database transaction with a row lock, or a conditional update such as "decrement where stock >= qty", gives you.

Python Simulating two buyers racing for the last unit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

In the naive run, both buyers read 1, both pass the check, and stock ends at -1. In the safe run, whoever is scheduled first takes the unit, and the other is refused. The program did not become smarter; the gap disappeared.

Real-world versions of "no gap"

In production you choose one of these mechanisms (see isolation and locking for the database side):

  • Conditional update: UPDATE stock SET available = available - :qty WHERE sku = :sku AND available >= :qty, then check how many rows changed. One statement, atomic, no explicit lock.
  • Row lock: SELECT ... FOR UPDATE inside a transaction, then update. Safe; serializes buyers of one SKU.
  • Optimistic locking: read a version number, update WHERE version = :seen, retry if no row changed.
  • Single writer: funnel all reservations for a SKU through one queue or actor. Simple reasoning, a throughput ceiling.
  • Counters in Redis (for example an atomic decrement) for flash sales, with the database updated afterwards and a reconciliation job to repair drift.

Whatever you choose, test it by hammering it with concurrent requests. A race that shows up once in a million requests will show up during your biggest sale.

Extend it

  1. Add extend(rid, extra_seconds) that lengthens an active hold but refuses to extend an expired one.
  2. Add multiple warehouses: available(sku, location) and a rule that reserves from the nearest location with enough stock.
  3. Make reserve idempotent: a repeated call with the same owner and cart_id returns the existing reservation instead of a second one (see idempotency).
  4. Add a write_off(sku, qty, reason) that refuses to push on-hand below the reserved quantity.
  5. Add a reconciliation check that recomputes on_hand from the ledger and compares it with a stored count.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why is on-hand stock derived from a ledger instead of stored as one editable number?

    An append-only ledger records each movement. The current quantity is the sum, so you can trace any discrepancy to the entries that caused it.
  2. 2. What is the check-then-act race?

    When another request can run between the read and the write, both act on a stale read and the stock goes negative.
  3. 3. A reservation passes its TTL and nobody has run the sweep yet. What should available stock show?

    Ignoring overdue holds in the calculation makes the expiry rule enforce itself. The sweep only updates statuses and records the outcome.
  4. 4. Which of these closes the race gap in a SQL database?

    A conditional update performs the check and the write as one atomic statement, so two buyers cannot both succeed for the last unit.

Summary

  • Keep stock as an append-only ledger; compute on hand, reserved and available from it.
  • Reservations hold stock for a limited time and end as committed, released or expired.
  • Ignore overdue holds when calculating availability; use a sweep to update statuses and logs.
  • Overselling comes from a gap between check and write; remove the gap with a conditional update, a row lock, optimistic locking or a single writer.
  • Simulate and stress-test concurrency; do not trust code that merely looks safe.

The last project handles the messages that tell your shop a payment happened: Project: A Payment Webhook Handler.