Almost every inventory bug starts the same way. A quantity column sits on the products table, and five different parts of the system add to it or subtract from it: sales, purchases, returns, transfers, the admin who "fixes" a number by hand. A month later the shelf says 14 and the screen says 11, and nobody can tell which of the five is wrong.

The fix is not more careful code around that column. It is to stop storing the number at all, and to store what happened to the stock instead.

The problem with a quantity column

A single number cannot answer the questions a business asks about stock:

  • Why is it 11? The column keeps no history, so there is nothing to read.
  • Who changed it, and when? Without a record, an honest mistake and a theft look the same.
  • What was it last Tuesday? Reports for a past date become guesses.
  • Is it right? Nothing to compare it with, so the only check is counting the shelf.

It also breaks under concurrency. Two cashiers sell the last item at the same moment, both read 1, both write 0, and one customer is told the item is in stock when it is not.

The ledger idea

Accountants solved this centuries ago: never change a balance, add an entry. Do the same for stock. Every change is a row in a movements table, with a signed quantity: positive when stock comes in, negative when it goes out.

CREATE TABLE stock_movements (
    id           BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    item_id      BIGINT UNSIGNED NOT NULL,
    warehouse_id BIGINT UNSIGNED NOT NULL,
    quantity     DECIMAL(14,3)   NOT NULL,  -- +in, -out
    reason       VARCHAR(30)     NOT NULL,  -- purchase, sale, transfer, damage, count...
    source_type  VARCHAR(40)     NOT NULL,  -- the document that caused it
    source_id    BIGINT UNSIGNED NOT NULL,
    reverses_id  BIGINT UNSIGNED NULL,      -- set when this row cancels another
    unit_cost    DECIMAL(14,4)   NULL,
    created_by   BIGINT UNSIGNED NULL,
    created_at   DATETIME        NOT NULL,
    INDEX (item_id, warehouse_id),
    INDEX (source_type, source_id)
);

The stock of an item in a warehouse is the sum of its rows:

SELECT item_id, warehouse_id, SUM(quantity) AS on_hand
FROM stock_movements
GROUP BY item_id, warehouse_id;

One rule keeps the design honest: no code updates or deletes a movement. A row, once written, is history.

Every business event is a movement

Once stock is a ledger, each thing the business does has an exact shape:

Event Movements
Purchase received +qty in the receiving warehouse
Sale -qty from the selling warehouse
Sales return +qty back in
Return to supplier -qty out
Transfer A to B -qty in A and +qty in B, in one transaction, sharing a transfer id
Damage or loss -qty, with a reason
Stock count ±difference, so the ledger matches the shelf
Opening balance +qty on the day you start

A transfer is the best test of the design. With a quantity column, it is two updates that can half-succeed. With a ledger, it is two rows written in one database transaction, and they either both exist or neither does.

Cancel and edit by reversing

A sale is cancelled. With a quantity column you would add the amount back and hope. With a ledger you write a new row that reverses the old one, pointing at it through reverses_id.

Editing a document works the same way: reverse the old movements, then write the new ones. The history now shows what was believed, what was corrected and when. When an auditor, a manager or you ask "why did this change?", the answer is in the table.

Reading stock fast

Summing a million rows on every product page is slow. Keep a second table with one row per item and warehouse, updated in the same transaction as the movement:

DB::transaction(function () use ($itemId, $warehouseId, $quantity, $saleLineId) {
    $balance = StockBalance::query()
        ->where('item_id', $itemId)
        ->where('warehouse_id', $warehouseId)
        ->lockForUpdate()
        ->firstOrFail();

    if ($balance->on_hand < $quantity) {
        throw new InsufficientStock($itemId, $warehouseId);
    }

    StockMovement::create([
        'item_id'      => $itemId,
        'warehouse_id' => $warehouseId,
        'quantity'     => -$quantity,
        'reason'       => 'sale',
        'source_type'  => 'sale_line',
        'source_id'    => $saleLineId,
    ]);

    $balance->decrement('on_hand', $quantity);
});

The lock is what fixes the two-cashiers problem: the second sale waits for the first, reads the true number, and is refused cleanly if nothing is left.

The balance is a cache, and the ledger is the truth. Check one against the other every night, and a drift shows up the day it happens, not at the year-end count:

SELECT b.item_id, b.warehouse_id, b.on_hand, SUM(m.quantity) AS ledger
FROM stock_balances b
JOIN stock_movements m USING (item_id, warehouse_id)
GROUP BY b.item_id, b.warehouse_id, b.on_hand
HAVING b.on_hand <> SUM(m.quantity);

If the query returns rows, rebuild those balances from the ledger. You can always do that, because the ledger lost nothing.

Decide what negative stock means

Can the system sell something it does not have? There is no universal answer, and it is a business decision, not a technical one:

  • Forbid it. The sale is refused. Safe, but a cashier who has the item in hand and a wrong system count is blocked.
  • Allow it, and flag it. The balance goes below zero and appears on an exceptions report. Good when receiving is often entered late.

Whichever you choose, put it in one place in the code, so that the product page, the cart and the till all behave the same way.

Reservations, cost and counts

Reservations. An order that is placed but not shipped should not be sellable twice. Keep a reserved quantity next to on_hand, and show available = on_hand - reserved.

Cost. Profit needs the cost of what was sold. Store unit_cost on the incoming movements and copy the cost onto the sale line when the sale happens. If you recalculate later from the current cost, last year's profit changes every time a supplier changes a price. Decide early between average cost and first-in-first-out, and write the rule down.

Counts. A stock count is not an edit. Record what was counted, compute the difference from the ledger, and write it as an adjustment movement with the reason "count" and the person who approved it. Repeated large adjustments on one item are a signal in themselves.

A checklist before you build

  • Stock is the sum of signed movements; nothing edits or deletes one.
  • Transfers, and anything with two sides, are written in one transaction.
  • Cancelling or editing a document writes reversing movements.
  • Reads use a balance table that is updated in the same transaction and checked against the ledger every night.
  • Concurrent sales take a row lock on the balance.
  • Negative stock has one written policy, applied in one place.
  • Cost is stored on movements and copied onto the sale line.
  • Counts, damage and corrections are movements with a reason and a person.

The short version

If your system can answer "why is it 11?" with a list of rows, you have a ledger. If it can only say "because that is what the column holds", you have a number that someone will eventually doubt. The ledger costs one extra table and a little discipline, and it buys you a system whose stock, reports and audits agree with each other.

If you are planning an inventory, POS or ERP system and want a second opinion on its design, tell us what you are building. A senior engineer reads every message.