Skip to content

An Append-Only Stock Ledger: How We Stopped Overselling

Inventory management system design without a quantity field: stock as a sum of immutable movements, derived stock status, a MongoDB checkout transaction that re-checks stock, and netted bulk adjustments that prevent overselling.

By Abdul Gaffar4 min read
Title card for "An Append-Only Stock Ledger: How We Stopped Overselling" by Abdul Gaffar

Every inventory system I've seen starts the same way: a product has a quantity field. You sell two, you subtract two. It's simple, and it works perfectly in the demo.

When I built the pharmacy module of Simple Green Solutions, I decided early not to do that. A pharmacy item in that system has no quantity field at all. Here's why, and what we did instead.

The problem with a quantity field

The usual update looks like this:

const item = await Item.findById(id);
item.quantity = item.quantity - sold;
await item.save();

Now imagine two things happening at the same moment: a staff member removes three damaged boxes, and a customer buys two online. Both read "10". One writes 7, the other writes 8. One update is lost, and the shelf no longer matches the screen.

There's a second problem that hurts later. When someone asks "why does the system say 6 when we have 9?", a quantity field has no answer. It only knows the current number, not how it got there.

There are ways to patch the first problem, like atomic increments or locks. They don't fix the second one.

Quantity as a sum of movements

Instead, every change in stock is recorded as a new, immutable row in a movement ledger:

  • Initial: the opening balance when a product is created
  • Add: stock received
  • Remove: written off, damaged, dispensed
  • Sold: decremented by a customer order
  • Adjustment: a count correction

Each row records who made it, when, and an optional note. The current quantity of an item is just the sum of its movements:

quantity = sum(movement.delta for this item)

Two staff members adjusting the same item at once each insert their own row. Nobody overwrites anybody. And a mistake is never edited away. It's corrected with another movement, so the full history stays intact.

Status is derived, never stored

Once quantity is a sum, storing "in stock" or "low stock" on the item makes no sense. It would go stale the moment a new movement arrives.

So status is calculated when it's read, from the current sum and the item's own thresholds:

if (qty <= 0)          return "NOT_AVAILABLE";
if (qty <= critical)   return "CRITICAL";
if (qty <= low)        return "LOW_STOCK";
return "IN_STOCK";

There's one function for this, and every screen uses it. A badge can't disagree with the number next to it, because they come from the same place.

Checkout that can't oversell

The storefront lets a customer buy from several pharmacies in one cart. At checkout the cart is split into one order per pharmacy, and the whole thing is written in a single MongoDB transaction.

The important detail is where the stock check happens:

  1. Before the transaction, we check stock and return a friendly message if something is short.
  2. Inside the transaction, we calculate the stock again. Another customer may have bought the last units in the meantime.
  3. Only then are the orders and the "sold" movements written, all together or not at all.

The first check is for the user's experience. The second one is for correctness. Skipping the second one is how most systems end up overselling during a busy hour.

Bulk adjustments: net first, then validate

Staff often adjust many items at once. A subtle case: a batch with −3 and −2 for the same item, when the item has 4. Each line looks fine on its own. Together they take the item to −1.

So the batch is netted per item first, and validated as a whole. Either the entire batch is valid and is written in one transaction, or nothing is written and the user is told which item would go negative. Half-applied batches are worse than failed ones, because nobody knows what actually happened.

The trade-off

This design isn't free. Reading a quantity means summing rows instead of reading one field. With the right compound index, that's a single indexed pass and fast enough for a pharmacy's inventory. If it ever becomes too slow, the usual next step is to add periodic snapshots (a stored balance at a point in time plus the movements after it), without giving up the ledger.

For a system where stock mistakes mean a patient turned away or a regulator asking questions, I'll take a slightly slower read for a number that is always explainable.

Where else this pattern fits

Anything where the history matters as much as the current value: account balances, customer credit ledgers like a shop's khata, loyalty points, leave balances. If someone will ever ask "how did we get to this number?", consider storing the movements and deriving the number.

All posts

Comments

    Have a project in mind?

    Whether it's an MVP, a dashboard, or a rescue mission on an existing codebase — let's talk about it.

    Prefer to talk first? Book a free 30-min call (opens in a new tab)