← Journal
Performance8 min · 2026-05-02· 5-phase teardown

Real-time inventory: killing an N+1 across a nationwide retail network

Stock views were minutes stale and reconciliation ran nightly. The instinct was to blame the servers. The actual culprit was the query layer — N+1 fan-out, unindexed joins on the hot path, and a non-idempotent sync doing the same work twice. No new hardware.

01

Issue

The problem, framed precisely.

Inventory that lags sales makes confident, wrong decisions

Across OCB's branch network, stock views ran minutes behind reality and reconciliation happened nightly rather than live. Inventory data that lags sales is worse than none: it doesn't stop decisions, it makes people confident about wrong ones — reorder the thing you just sold out of, or sit on dead stock the numbers say is moving.

minutesstock-view staleness
nightlyreconciliation cadence
N+1root-cause pattern
$0hardware added
02

Hypothesis

What I believed was true, and why.

It's the query layer, not the box

The reflexive diagnosis in retail IT is 'the server is too slow — buy a bigger one.' My hypothesis was the opposite: the hardware was fine and the query layer was asking the database to do the same work thousands of times per page. Specifically I expected three culprits — a per-item lookup fanning out into an N+1, joins hitting unindexed columns on the hot path, and a sync job re-reading rows it had just written.

“Most performance wins aren't a bigger machine — they're a query that stops asking the database to do the same work a thousand times.”

03

Strategy

The approach and the trade-offs weighed.

Measure first, then collapse, index, and make idempotent

The discipline is: never optimize on instinct. Pull EXPLAIN ANALYZE on the hot queries and let the plan name the villain before touching code. Then three moves, in order of leverage:

  • Collapse the N+1 into a single set-based query — one round trip instead of one-per-row.
  • Add exactly the indexes the access patterns need — no speculative indexes that only tax writes.
  • Make the sync idempotent, so a retry stops doubling work and reconciliation can run continuously instead of once nightly.

Order matters: fixing the N+1 first shrinks the row counts the indexes then serve, and idempotency last means the now-fast sync can run often without compounding. Doing them out of order wastes an index on a query you're about to delete.

04

Implementation

How it was actually built.

One join to replace a thousand lookups

The N+1 was the classic shape: fetch the outlets, then loop and query stock per outlet. At 40 outlets that's 41 round trips for one dashboard render.

-- Before: 1 + N queries (one per outlet) \u2014 the N+1.
SELECT id, name FROM outlets WHERE region = $1;
-- then, in application code, per outlet:
SELECT sku, qty FROM stock WHERE outlet_id = $outletId;

-- After: one set-based query, joined and aggregated in the DB.
SELECT o.id, o.name, s.sku, s.qty
FROM   outlets o
JOIN   stock  s ON s.outlet_id = o.id
WHERE  o.region = $1
ORDER  BY o.id, s.sku;

Then the indexes the plan actually asked for — the join key and the hot filter, not a scattershot of hopeful ones:

-- Postgres does NOT auto-index foreign keys; the join was seq-scanning.
CREATE INDEX idx_stock_outlet ON stock (outlet_id);
CREATE INDEX idx_outlets_region ON outlets (region);
-- Verified against EXPLAIN ANALYZE: seq scan \u2192 index scan, sort dropped.

Finally, idempotency. The sync had been re-reading and re-applying rows it had already processed, so a retry after a network blip doubled quantities. An upsert keyed on a natural identity made retries safe, which in turn let reconciliation move from nightly batch to continuous:

-- Idempotent sync: a retry converges instead of doubling.
INSERT INTO stock (outlet_id, sku, qty, synced_at)
VALUES ($1, $2, $3, now())
ON CONFLICT (outlet_id, sku)
DO UPDATE SET qty = EXCLUDED.qty, synced_at = now();
05

Summary

Outcome, evidence, and what I'd change.

Real-time inventory on the same hardware

The dashboard that took 41 round trips took one; the joins that seq-scanned used indexes; the sync that doubled on retry converged. Stock tracking moved from minutes-stale-nightly to effectively real-time across every store — on exactly the same infrastructure that was previously blamed for the lag.

The transferable lesson isn't the specific SQL — it's the sequence. Measure before you touch anything, fix the algorithmic shape (N+1) before the physical layer (indexes), and make writes idempotent so 'run it more often' becomes safe rather than dangerous. The honest caveat: this class of win has a ceiling. Query surgery buys you an order of magnitude on the same box; past that you're into partitioning, read replicas, or a different storage model — and the discipline then is knowing which problem you actually have before you spend on the wrong fix.

Written by Ridha Fahmi Junaidi · AI Implementation Lead · AI Integration Engineer

Next
Ronda: letting coding agents run their own board over MCP→