Skip to content
AccountancyPath

Accounting for DevelopersModule 4: Production financial systemsAdvanced4 min read

Implementing Inventory Costing (FIFO and Average) in Code

Implement FIFO cost-layer queues and moving weighted average inventory costing in SQL and TypeScript, handling returns, negative stock and balanced COGS entries.

Lesson 12 of 16
Course outline (16 lessons)

Before this lesson:Journal and General Ledger Database DesignInventory and Cost of Goods Sold (COGS)

Counting how many units sit in your warehouse is easy (+100, −120). Knowing what those units cost is where commerce bugs hide. When supplier prices change between purchase orders, two identical items on the shelf carry different unit costs—and your ledger needs exact Cost of Goods Sold (COGS) every time one ships.

Two standard costing algorithms in software

Under perpetual inventory tracking, every sale posts two balanced journal entries: one for revenue (Dr Cash/AR / Cr Revenue) and one for cost (Dr COGS / Cr Inventory). How you compute that second entry depends on the costing method:

  • FIFO (First-In, First-Out): consumes the oldest purchase cost layers first, like a queue. Requires an inventory_layers table.
  • Moving Weighted Average: blends all on-hand units into one average cost after each purchase receipt. Requires only current qty_on_hand and total_value_minor per SKU/warehouse.
Formula · Moving weighted average unit cost

new_avg_cost = (current_inventory_value + receipt_value) ÷ (current_qty + receipt_qty)

current_inventory_value
carrying balance of Inventory in minor units before the receipt
receipt_value
landed cost (purchase price + freight/duties) of the incoming batch
current_qty, receipt_qty
integer unit counts on hand and newly received

FIFO cost-layer schema

Model each purchase receipt as a cost layer and record every consumption in an append-only audit table so returns and audits know the exact cost of every shipped unit:

CREATE TABLE inventory_layers (
  id              uuid PRIMARY KEY,
  sku_id          uuid NOT NULL,
  warehouse_id    uuid NOT NULL,
  received_at     timestamptz NOT NULL,
  qty_initial     integer NOT NULL CHECK (qty_initial > 0),
  qty_remaining   integer NOT NULL CHECK (qty_remaining >= 0),
  unit_cost_minor bigint NOT NULL CHECK (unit_cost_minor >= 0),
  currency        char(3) NOT NULL
);

CREATE INDEX inventory_layers_fifo_idx
  ON inventory_layers (sku_id, warehouse_id, received_at, id)
  WHERE qty_remaining > 0;

CREATE TABLE inventory_consumptions (
  id                uuid PRIMARY KEY,
  layer_id          uuid NOT NULL REFERENCES inventory_layers(id),
  shipment_id       uuid NOT NULL,
  qty_consumed      integer NOT NULL CHECK (qty_consumed > 0),
  cost_minor        bigint NOT NULL,
  journal_entry_id  uuid NOT NULL REFERENCES journal_entries(id)
);

Concurrency-safe FIFO consumption in TypeScript

Inside the shipment transaction, acquire a lock on open layers (SELECT ... FROM inventory_layers WHERE sku_id = $1 AND qty_remaining > 0 ORDER BY received_at ASC, id ASC FOR UPDATE) so two simultaneous orders never consume the same units:

interface CostLayer {
  id: string;
  qtyRemaining: number;
  unitCostMinor: bigint;
}

function consumeFifo(layers: CostLayer[], qtyNeeded: number) {
  let remaining = qtyNeeded;
  let totalCogsMinor = 0n;
  const picks: { layerId: string; qty: number; costMinor: bigint }[] = [];

  for (const layer of layers) {
    if (remaining === 0) break;
    const take = Math.min(layer.qtyRemaining, remaining);
    const costMinor = BigInt(take) * layer.unitCostMinor;
    picks.push({ layerId: layer.id, qty: take, costMinor });
    totalCogsMinor += costMinor;
    remaining -= take;
  }

  if (remaining > 0) {
    throw new Error(`Insufficient stock: short by ${remaining} units`);
  }
  return { totalCogsMinor, picks };
}

For moving weighted average, compute cogsMinor = round_half_up(totalValueMinor * qtySold / qtyOnHand). When qtySold === qtyOnHand, set cogsMinor = totalValueMinor directly so zero-quantity stock never carries a leftover rounding penny!

Customer returns and negative-stock race conditions

  • Customer returns (restocked items): query inventory_consumptions for the original shipment to find the exact unit cost that left inventory (most-recent consumed layer first for partial returns), create a new restock layer at that unit cost, and post Dr Inventory / Cr COGS alongside the sales return entry.
  • Negative-stock race conditions: in real warehouses, staff sometimes scan an outbound shipment before receiving the inbound PO in software. If business operations forbid blocking shipments, record a stock_shortage row at a provisional cost (such as last PO cost) and run a reconciliation trigger when the delayed purchase layer is posted to book the exact Dr/Cr Inventory / COGS variance.
Worked example

Pinecrest Gear (fictional) — FIFO vs Moving Average for SKU PACK-40L

Pinecrest Gear records two May purchases of hiking packs, then sells 120 units at $45 each ($5,400 revenue):

  • 1 May purchase: 100 units @ $20.00 = $2,000.00
  • 8 May purchase: 60 units @ $24.00 = $1,440.00 (total pool: 160 units = $3,440.00)
Method COGS (120 units sold) Ending Inventory (40 units) Total accounted
FIFO (100 × $20) + (20 × $24) = $2,480 40 × $24 = $960 $3,440
Moving Average ($3,440 ÷ 160 = $21.50) 120 × $21.50 = $2,580 40 × $21.50 = $860 $3,440

Under FIFO, the 12 May sale posts both revenue and cost entries:

12 May (a): Record sales revenue
AccountDebit (Dr)Credit (Cr)
Accounts Receivable$5,400
Product Revenue$5,400
Total✓ Balanced$5,400$5,400
12 May (b): Record FIFO COGS
AccountDebit (Dr)Credit (Cr)
Cost of Goods Sold$2,480
Inventory$2,480
Total✓ Balanced$2,480$2,480

18 May — Customer returns 10 undamaged units: Pinecrest reverses $450 revenue (10 × $45) and restores 10 units at the $24 cost layer ($240):

18 May: Customer return (revenue and FIFO restock)
AccountDebit (Dr)Credit (Cr)
Sales Returns and Allowances$450
Inventory$240
Accounts Receivable$450
Cost of Goods Sold$240
Total✓ Balanced$690$690

Real-world application

E-commerce backends, fulfilment ERPs and retail POS platforms reconcile SUM(qty_remaining × unit_cost_minor) from inventory_layers against the general ledger’s Inventory asset account every month-end. Because both tables update in one atomic database transaction, gross margin reports stay accurate SKU by SKU without manual spreadsheet cost rolls.

Recap

  • Perpetual inventory posts two balanced entries on every sale: revenue/receivable and COGS/inventory.
  • Implement FIFO with row-locked inventory_layers ordered by (received_at, id) plus an inventory_consumptions audit table; implement moving weighted average by updating total value and quantity on each receipt.
  • Clear exact remaining value when stock hits zero, restore returns at their original consumed cost, and handle negative stock explicitly with locks or variance adjustments.

Active recall

Quick check · Test yourself

Work out each answer in your head first, then reveal the explanation and mark whether you got it right.

  1. 1A store buys 100 units at $20 ($2,000) and then 60 units at $24 ($1,440), and sells 120 units. Compare COGS and ending inventory under FIFO vs moving weighted average.

    Show worked answer

    Under FIFO, COGS = (100 × $20) + (20 × $24) = $2,480 and ending inventory = 40 × $24 = $960. Under moving weighted average, average cost = $3,440 ÷ 160 = $21.50/unit, so COGS = 120 × $21.50 = $2,580 and ending inventory = 40 × $21.50 = $860. Both methods account for all $3,440.

  2. 2Why must FIFO consumption lock layer rows with SELECT ... FOR UPDATE?

    Show worked answer

    Without row locking, two concurrent checkout requests can read the same oldest layer's qty_remaining at once, over-consume it, and post incorrect COGS—creating a mismatch between the inventory subledger and the general ledger.

  3. 3What happens in a FIFO engine when a warehouse ships a sale before the supplier's purchase receipt is entered (negative stock)?

    Show worked answer

    There is no cost layer to consume yet. Either block shipment until receipt is posted, or post provisional COGS at the latest known cost and automatically post a balanced cost-variance entry once the actual purchase layer arrives.

Key terms in this lesson

Lesson 12 of 16 · Accounting for Developers

Finished this lesson?

Mark it complete to track your progress through the course. Progress is saved in this browser only.

Previous lesson: Subscription Billing and Revenue Recognition Schedules

Subject GuideAccounting Systems & Personal Finance

Mei-Ling Chen(陈美玲)

Turns accounting invariants into clean code—and everyday personal money clarity.

  • Double-Entry Ledger Engineering
  • SQL Schemas & Financial APIs
  • Multi-Currency & Billing Code

More lessons with Mei-Ling

Published:

Educational content only—not accounting, tax, legal or investment advice. See our editorial policy or report an error via our corrections policy.

Search