DEV Community

Cover image for Real-Time Inventory Updates Without Overloading Your Database
Andrii B.
Andrii B.

Posted on AI-assisted

Real-Time Inventory Updates Without Overloading Your Database

Here's a sentence from the design notes of Magento's Multi-Source Inventory, the module that decides whether a Magento store can sell you something:

"Reservation creation is append-only operation, so there are no checks and blocking operations (locks) needed."

And here's the title of a commit that landed in the same codebase, the magento/inventory repository, on February 6, 2026:

ACP2E-4509: Magento allows overselling when multiple customers place orders concurrently
Enter fullscreen mode Exit fullscreen mode

That commit adds a MySQL named lock per SKU around order placement. The lock-free design got a lock.

That's not a dunk on Magento. It's the most honest summary of inventory engineering you'll find: you can move the contention, shrink it, split it, or push it into a faster store, but "don't sell more than you have" is an invariant, and somewhere, something has to check it one buyer at a time. The whole game is making that "one at a time" window as short and as narrow as possible.

First, where the contention actually comes from. Then four patterns, in the order I'd reach for them.

Why one row becomes the bottleneck

Picture the naive schema. One row per SKU, one integer:

CREATE TABLE stock (
  sku_id   bigint PRIMARY KEY,
  on_hand  integer NOT NULL CHECK (on_hand >= 0)
);
Enter fullscreen mode Exit fullscreen mode

Every checkout for that SKU runs UPDATE stock SET on_hand = on_hand - 1 WHERE sku_id = 42. An UPDATE takes a row-level lock, and that lock is held until the transaction commits or rolls back. Not until the statement finishes. Until the transaction ends.

That distinction is the entire problem. If your checkout transaction decrements stock first, then inserts the order, writes order items, calls a tax service, and commits, the stock row stays locked for all of it. Every other buyer of that SKU queues behind you.

You can do the arithmetic without a benchmark. Throughput on a single hot row is capped at roughly one transaction per lock hold time. Hold the lock for 50ms and you've capped that SKU at around 20 checkouts per second, no matter how many cores or replicas you throw at the database. More app servers just make the queue longer.

The Postgres docs describe exactly what the queued transactions are doing. In Read Committed, when an UPDATE finds its target row already being changed by someone else, "the would-be updater will wait for the first updating transaction to commit or roll back." They're not spinning, they're parked. Your connection pool fills up with parked transactions, and suddenly requests for unrelated products start timing out because there are no connections left. A hot SKU becomes a site-wide outage.

There's a second, quieter cost. Postgres doesn't update in place: every UPDATE writes a new row version. A popular counter decremented thousands of times an hour is a dead-tuple factory. Postgres softens this with heap-only tuple (HOT) updates, which skip index maintenance, but only when two conditions hold: the update "does not modify any columns referenced by the table's indexes," and there's free space on the same page.

Warning
That first HOT condition is a real footgun for stock tables. Someone adds an index on on_hand so the "in stock only" filter is fast, and now every single decrement touches that index and stops qualifying as a HOT update. If you need to filter by availability, index a boolean that flips rarely, not the counter that changes on every sale. You can watch the ratio in pg_stat_all_tables (n_tup_upd versus n_tup_hot_upd).

Pattern 1: shrink the lock, don't remove it

Before any clever architecture, fix the two mistakes that cause most inventory contention in practice.

The first mistake is read-then-write:

checkout.ts (broken)

const { rows } = await client.query(
  "SELECT on_hand FROM stock WHERE sku_id = $1",
  [skuId],
);
if (rows[0].on_hand < qty) throw new OutOfStockError(skuId);
await client.query(
  "UPDATE stock SET on_hand = $2 WHERE sku_id = $1",
  [skuId, rows[0].on_hand - qty],
);
Enter fullscreen mode Exit fullscreen mode

This compiles, passes every single-user test, and oversells under load. Two buyers read on_hand = 1, both pass the check, both write 0. You sold two units and recorded one. It's the textbook lost update, and the CHECK (on_hand >= 0) constraint doesn't save you because neither write goes negative.

The fix is one statement that checks and decrements together:

UPDATE stock
SET on_hand = on_hand - $2
WHERE sku_id = $1
  AND on_hand >= $2
RETURNING on_hand;
Enter fullscreen mode Exit fullscreen mode

Zero rows back means out of stock. One row back means you got it. The reason this is safe under concurrency is a detail of Read Committed that most people never read: when the waiting transaction finally gets the row, Postgres doesn't blindly apply its update. Straight from the docs: "The search condition of the command (the WHERE clause) is re-evaluated to see if the updated version of the row still matches the search condition." So if the first buyer took the last unit, the second buyer's on_hand >= $2 is re-checked against the new value, fails, and the update affects zero rows. No oversell, and you didn't need an explicit lock or an application-side check to get there.

(If you run checkout under Repeatable Read instead, the second transaction gets ERROR: could not serialize access due to concurrent update and you have to retry. Works, but it's noisier.)

The second mistake is lock placement. Move the stock decrement to the end of the transaction, right before COMMIT:

checkout.ts

await client.query("BEGIN");
try {
  const orderId = await insertOrder(client, cart);      // no stock lock held yet
  await insertOrderItems(client, orderId, cart.items);  // still no stock lock

  // Lock stock rows last, in a stable order, so two carts
  // with the same SKUs can't deadlock each other.
  const items = [...cart.items].sort((a, b) => a.skuId - b.skuId);
  for (const item of items) {
    const res = await client.query(
      `UPDATE stock SET on_hand = on_hand - $2
       WHERE sku_id = $1 AND on_hand >= $2
       RETURNING on_hand`,
      [item.skuId, item.qty],
    );
    if (res.rowCount === 0) throw new OutOfStockError(item.skuId);
  }

  await client.query("COMMIT"); // stock locks released here
} catch (err) {
  await client.query("ROLLBACK");
  throw err;
}
Enter fullscreen mode Exit fullscreen mode

The lock window is now "a few updates plus a commit" instead of "the whole checkout." The sort matters too: the Postgres docs call acquiring locks "in a consistent order" the best defense against deadlocks, and a multi-item cart is exactly where you'd otherwise get one.

And never, ever hold a stock lock across a network call to a payment provider. If you need to authorize payment before committing to stock, that's a reservation problem, which is the next pattern.

Honestly, this is where most shops should stop. A conditional decrement at the end of a short transaction handles a surprising amount of traffic, and it keeps one source of truth. Everything below is for when a specific SKU is hot enough that even a short lock queues up, or when your business needs "held but not yet sold" as a real state.

Pattern 2: reservations instead of decrements

A reservation ledger stops treating stock as one mutable number. Instead, you keep the physical count in one place and write every sales event as an append-only row:

CREATE TABLE stock_reservation (
  id          bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
  sku_id      bigint  NOT NULL,
  qty         integer NOT NULL,   -- negative = hold, positive = release
  event_type  text    NOT NULL,   -- 'order_placed', 'order_canceled', 'shipment_created'
  order_id    bigint,
  created_at  timestamptz NOT NULL DEFAULT now()
);

CREATE INDEX stock_reservation_sku_idx ON stock_reservation (sku_id);
Enter fullscreen mode Exit fullscreen mode

Salable quantity becomes a sum:

SELECT s.on_hand + COALESCE(SUM(r.qty), 0) AS salable
FROM stock s
LEFT JOIN stock_reservation r ON r.sku_id = s.sku_id
WHERE s.sku_id = $1
GROUP BY s.on_hand;
Enter fullscreen mode Exit fullscreen mode

An order inserts -3. A cancellation inserts +3. A shipment inserts +3 and, at the same time, the warehouse process actually decrements on_hand. Once an order reaches a final state, its reservations sum to zero and can be cleaned up.

If this smells like event sourcing, it is, just scoped to one number. (If you want the parts of that pattern that bite at scale, I wrote about them in Event Sourcing: The Parts That Are Genuinely Hard.)

Magento MSI is the real-world version

This isn't a whiteboard idea. It's exactly how Magento's Multi-Source Inventory works, and the source is public. The table from InventoryReservations/etc/db_schema.xml:

db_schema.xml

<table name="inventory_reservation" resource="default" engine="innodb">
    <column xsi:type="int" name="reservation_id" unsigned="true" nullable="false" identity="true"/>
    <column xsi:type="int" name="stock_id" unsigned="true" nullable="false" identity="false"/>
    <column xsi:type="varchar" name="sku" nullable="false" length="64"/>
    <column xsi:type="decimal" name="quantity" scale="4" precision="10" unsigned="false" nullable="false"
            default="0"/>
    <column xsi:type="varchar" name="metadata" nullable="true" length="255"/>
    ...
</table>
Enter fullscreen mode Exit fullscreen mode

The metadata column carries the business event as JSON, like {"event_type":"order_placed","object_type":"order","object_id":"8"}. The MSI wiki spells out the formula: salable quantity is the StockItem quantity (an indexed aggregate across all physical sources) plus all reservations for that SKU on that stock. Adobe's docs give the worked example: 55 units on hand, -15 in outstanding reservations, so you can sell up to 40.

The design makes real sense for Magento specifically. At order placement, the system doesn't yet know which warehouse will fulfill the order, so it can't decrement a specific source. And the StockItem quantity is an index value, read-only by design. The reservation is the only thing it can write.

The ledger needs housekeeping, and MSI ships it. A cron job, inventory_cleanup_reservations, runs on 0 0 * * * (daily at midnight) and removes reservation sets that net to zero. And because ledgers drift when an order gets stuck or a compensation never fires, there are two CLI commands for exactly that:

bin/magento inventory:reservation:list-inconsistencies
bin/magento inventory:reservation:create-compensations
Enter fullscreen mode Exit fullscreen mode

The gotcha: append-only doesn't mean race-free

Back to that opening quote. Appending a row really doesn't need a lock. Two inserts into inventory_reservation never block each other. That's the write-contention win, and it's real.

But the decision to append is a read. "Salable is 25, the customer wants 10, go ahead" is a check-then-act sequence, and two concurrent checkouts can both read 25, both decide yes, and both append. With one unit left, that's an oversell. The ledger moved the contention off the stock row and, along the way, removed the thing that was serializing the check.

The February 2026 fix is small and telling. InventorySales/Model/ResourceModel/AcquireInventoryLock.php takes a MySQL user-level lock per SKU and stock:

AcquireInventoryLock.php (excerpt)

private const LOCK_TIMEOUT = 10;

private function getLockName(string $sku, int $stockId): string
{
    return sprintf('inv_lock_%d_%s', $stockId, md5($sku));
}
Enter fullscreen mode Exit fullscreen mode

A plugin named inventory_lock_during_place_order wraps CartManagementInterface::placeOrder(), calls GET_LOCK(name, 10) for every SKU in the cart, runs the original order placement, and releases the locks in a finally block. If it can't get a lock within ten seconds, the customer sees "Could not acquire inventory lock for SKU: %1. Please try again."

A few details worth stealing from it:

  • The md5 isn't decoration. MySQL enforces a 64-character maximum on lock names, and the sku column in inventory_reservation is itself 64 characters wide. Hashing keeps the name at a fixed, safe length.
  • GET_LOCK is session-scoped, not transaction-scoped. The MySQL docs are explicit: these locks "are not released when transactions commit or roll back." That's why the release lives in a finally, and why the class also releases everything in its destructor. Forget that, and a pooled connection walks away still holding a lock on your best-selling SKU.
  • The lock is per SKU, not global. Buyers of different products never wait on each other. The serialization is exactly as wide as the invariant.

If your Magento store runs a release line that predates this change, your checkout has the race. Check whether your version includes it before you assume MSI protects you under concurrency.

Doing the same thing in Postgres

Postgres has a cleaner primitive for this: transaction-level advisory locks. pg_advisory_xact_lock(key1 integer, key2 integer) takes an exclusive lock on an arbitrary pair of numbers, and it's released automatically at the end of the transaction. The docs note there's "no explicit unlock operation," which means there's no finally to forget.

reserve.sql

BEGIN;

-- Namespace 1001 = "inventory". One lock per SKU; lock SKUs in ascending order.
SELECT pg_advisory_xact_lock(1001, $1::integer);

SELECT s.on_hand + COALESCE(SUM(r.qty), 0) AS salable
FROM stock s
LEFT JOIN stock_reservation r ON r.sku_id = s.sku_id
WHERE s.sku_id = $1
GROUP BY s.on_hand;

-- application checks salable >= requested, then:
INSERT INTO stock_reservation (sku_id, qty, event_type, order_id)
VALUES ($1, -$2::integer, 'order_placed', $3);

COMMIT;  -- advisory lock released here
Enter fullscreen mode Exit fullscreen mode

Two reasons to prefer the _xact_ variant over session-level pg_advisory_lock. First, it can't leak. Second, it survives connection poolers: PgBouncer's feature matrix lists session-level advisory locks as supported in session pooling and "Never" in transaction pooling, because in transaction mode your next statement may run on a different server connection. A transaction-scoped lock lives and dies inside one transaction, so the pooler never splits it.

If you'd rather fail fast than queue during a spike, pg_try_advisory_xact_lock returns false immediately instead of waiting. Pair it with a short retry and you get backpressure instead of a pile of parked connections.

So is the ledger actually better than the conditional UPDATE? For raw throughput on one SKU, not really. You still serialize the check per SKU, and now the check includes a SUM. What the ledger buys you is different:

  • Checkout never writes the physical stock row, so warehouse imports and stock syncs stop fighting checkout for the same lock.
  • "Held but not sold" is a first-class state, so you can authorize payment without holding a database lock across a network call.
  • Every change has a reason attached. When the count is wrong, you can find out why.

Pick it for those reasons, not because someone told you append-only is lock-free.

Side-by-side diagram: direct decrement, where three checkouts contend for one locked stock row and two wait until COMMIT, versus a reservation ledger with a per-SKU check lock and append-only order_placed and shipment_created rows

Pattern 3: split the hot row into slots

Sometimes one SKU is so hot that even a millisecond-scale lock queues. Think a limited sneaker drop or a concert-ticket-style launch where thousands of buyers hit the same product in the same second. The fix is to stop having one row.

Split the stock for that SKU across N rows, called slots:

CREATE TABLE stock_slot (
  sku_id   bigint  NOT NULL,
  slot_no  smallint NOT NULL,
  qty      integer NOT NULL CHECK (qty >= 0),
  PRIMARY KEY (sku_id, slot_no)
);

-- 1,000 units spread across 10 slots of 100
INSERT INTO stock_slot (sku_id, slot_no, qty)
SELECT 42, g, 100 FROM generate_series(1, 10) AS g;
Enter fullscreen mode Exit fullscreen mode

Each buyer grabs whichever slot isn't busy, using SKIP LOCKED:

take-from-slot.sql

WITH slot AS (
  SELECT sku_id, slot_no
  FROM stock_slot
  WHERE sku_id = $1 AND qty >= $2
  ORDER BY random()
  LIMIT 1
  FOR UPDATE SKIP LOCKED
)
UPDATE stock_slot s
SET qty = s.qty - $2
FROM slot
WHERE s.sku_id = slot.sku_id AND s.slot_no = slot.slot_no
RETURNING s.slot_no, s.qty;
Enter fullscreen mode Exit fullscreen mode

Ten slots means up to ten buyers decrementing the same SKU concurrently instead of one. ORDER BY random() spreads buyers so they don't all try slot 1 first. And SKIP LOCKED means a buyer who hits a busy slot steps over it instead of waiting. I covered what SKIP LOCKED does and doesn't guarantee in Locking in PostgreSQL: What SELECT FOR UPDATE Actually Blocks, so I won't repeat the lock-mode details here. The short version: it gives you "an inconsistent view of the data" on purpose, which is exactly what you want when any slot will do.

This isn't a Postgres-only trick. Google's Firestore docs recommend the same shape, which they call distributed counters, because "you can't update a single document at an unlimited rate." Their summary of the tradeoff is as clean as it gets: "a distributed counter with 10 shards can handle 10x as many writes as a traditional counter," and reading the total means reading all 10 shards.

That's the first cost. Total stock is now SUM(qty) across slots. The others are sneakier:

  1. False "sold out." If every slot with enough stock is locked right now, the CTE returns nothing and your code says out of stock, while there's plenty left. On zero rows, retry once without SKIP LOCKED (a normal FOR UPDATE that waits) before telling the buyer no.
  2. Quantity bigger than any slot. A buyer wants 5, and ten slots have 3 each. There's 30 in stock but no single slot can serve it. You either take from multiple slots in one transaction (lock them in slot_no order), or cap per-order quantity during drops, which most drops do anyway.
  3. Slot starvation near the end. As slots drain unevenly, you get a few slots with stock and many at zero, and contention climbs back toward the single-row case. A rebalancing job can move stock between slots, or you accept that the last few units sell a bit slower.

Slots are a tool for a known-hot SKU during a known window. Don't slot your whole catalog. The long tail of products never sees two buyers in the same second, and you'd be paying the SUM tax on every product page for nothing.

Diagram of SKU 42 with 1,000 units split into ten slots of qty 100, eight buyers decrementing different slots while two locked slots are stepped over with SKIP LOCKED, plus notes total = SUM(qty) and retry with plain FOR UPDATE when all slots are locked

Pattern 4: Redis as a gate, not the ledger

The most common advice for flash sales is "put the stock in Redis." It works, and it's also where teams get hurt, because they quietly make Redis the source of truth for something that has to be correct.

Start with why Redis is attractive. DECRBY is O(1) and atomic, and a Lua script lets you do check-and-decrement as one step. Per the Redis docs, "Redis guarantees the script's atomic execution. While executing the script, all server activities are blocked during its entire runtime." No other command can interleave between your GET and your DECRBY.

Plain DECRBY isn't enough on its own, for two reasons from its docs. It happily goes negative. And "if the key does not exist, it is initialized with a value of 0 before performing the operation," so a key that expired or was never loaded turns into -1 on the first sale. Use a script:

reserve.lua

local current = redis.call('GET', KEYS[1])
if not current then
  return -2                 -- not loaded: caller falls back to the database
end
local want = tonumber(ARGV[1])
if tonumber(current) < want then
  return -1                 -- not enough stock
end
return redis.call('DECRBY', KEYS[1], want)
Enter fullscreen mode Exit fullscreen mode

gate.ts

import Redis from "ioredis";
import { readFileSync } from "node:fs";

const redis = new Redis();
redis.defineCommand("reserveStock", {
  numberOfKeys: 1,
  lua: readFileSync("./reserve.lua", "utf8"),
});

export async function tryAdmit(skuId: number, qty: number): Promise<"admit" | "reject" | "fallback"> {
  const res: number = await (redis as any).reserveStock(`stock:${skuId}`, qty);
  if (res === -2) return "fallback";
  if (res === -1) return "reject";
  return "admit";
}
Enter fullscreen mode Exit fullscreen mode

Note the key goes in through KEYS, not built inside the script. The Redis docs are firm that "all names of keys that a script accesses must be explicitly provided as input key arguments," which is what lets the script run correctly on Redis Cluster.

Now the part that matters. Redis replication is asynchronous by default, and the docs don't sugarcoat it: even WAIT "does not turn a set of Redis instances into a CP system with strong consistency: acknowledged writes can still be lost during a failover." So picture a failover mid-drop. The replica that gets promoted is missing the last few hundred decrements. Your Redis counter now says there's more stock than there is.

If Redis is the source of truth, you just oversold. If Redis is a gate in front of the database, nothing bad happens:

checkout.ts

const gate = await tryAdmit(skuId, qty);
if (gate === "reject") throw new OutOfStockError(skuId);

// "admit" or "fallback": the database still has the final word.
try {
  await placeOrderWithConditionalDecrement(skuId, qty); // Pattern 1
} catch (err) {
  if (gate === "admit") await redis.incrby(`stock:${skuId}`, qty); // give the gate its unit back
  throw err;
}
Enter fullscreen mode Exit fullscreen mode

Redis turns away the herd, which is its real job during a spike: when a drop sells out in the first minute, the next hundred thousand requests should cost a Redis round-trip, not a database transaction. The conditional UPDATE from Pattern 1 still enforces "never below zero." The two can disagree, and every disagreement is safe:

  • Redis says yes, the database says no: the buyer gets "sold out" one step later than ideal. Correct outcome.
  • Redis says no, the database has stock: you undersold. Annoying, recoverable, and a reconciliation job fixes it.

That's the design choice I'd defend in any review: never let the fast store be the only thing that can say yes. Let it say no cheaply, and let the durable store say the final yes.

Reconciliation is part of the design

Every pattern above can drift. Ledgers accumulate orphaned holds from orders that got stuck. Slots get out of balance. The Redis gate loses writes on failover, or your incrby compensation never runs because the process died between the two calls. Magento shipping list-inconsistencies and create-compensations as first-class CLI commands is an admission that drift is normal, not a bug you fix once.

For the Redis gate, the naive fix is a cron that reads the database and SETs the key. Be careful: that races with in-flight checkouts. Between your SELECT and your SET, a buyer may decrement both, and you overwrite Redis with a stale, higher number. Since the database still guards the invariant, the worst case is a few extra requests reaching the database, but it's cleaner to reconcile in a way that tolerates the race:

  • Rebuild the key when the sale window closes, or when the SKU is quiet.
  • Or only ever move the Redis number down automatically, toward the database value, and alert a human when it's lower than the database by more than some threshold. Undersell gets a human; oversell can't happen.

For a reservation ledger, the useful query is "holds that should have been released by now":

stale-holds.sql

SELECT r.order_id, r.sku_id, SUM(r.qty) AS open_qty, MIN(r.created_at) AS since
FROM stock_reservation r
GROUP BY r.order_id, r.sku_id
HAVING SUM(r.qty) <> 0
   AND MIN(r.created_at) < now() - interval '2 days'
ORDER BY since;
Enter fullscreen mode Exit fullscreen mode

Each row is an order whose reservations haven't netted to zero after two days (pick a threshold that matches your fulfillment times). Some are real backorders. Some are canceled orders whose +qty compensation never got written. Either way, you want to see them before a customer does.

Picking the right pattern

Situation Pattern What it costs
Normal catalog, occasional concurrency Conditional UPDATE ... WHERE on_hand >= $n, last in a short transaction Nothing new. One source of truth. Start here.
Need "held but not shipped," multi-warehouse, payment auth before commit Reservation ledger + per-SKU transaction-level advisory lock A SUM on every availability check, a cleanup job, drift handling
One known-hot SKU during a launch Sharded slots with SKIP LOCKED SUM for totals, false sold-outs, quantity-per-slot limits
Traffic spike far beyond what the database should see Redis gate in front of the conditional UPDATE A second store, a compensation path, reconciliation

Notice what's missing from the table: "move inventory to Redis and stop worrying." Every row still has the database making the final call. The patterns only change how many requests reach it and how long each one holds the lock.

If you remember one thing from the Magento story, make it this: removing a lock from a write path is only safe if nothing was relying on that lock to serialize a decision. The MSI ledger removed the contention on the stock row, which was a real win. It also removed the serialization of the check, and it took a commit literally titled "allows overselling" to put that part back. When you redesign your own inventory path, find the check first, decide exactly how narrow its lock can be, and then optimize everything around it.


Originally published at andriiboyko.com.

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The Magento framing is the strongest part — especially that the February 2026 fix put a lock back into a design whose whole pitch was lock-free. One detail in Pattern 3 I would push on: the fix for "quantity bigger than any slot" — fill the rest from the lowest slot_no — turns one checkout into a buyer that locks several slots at once. In Pattern 2 you lock SKUs in ascending order, which is exactly the habit that keeps two checkouts from deadlocking each other. Does the multi-slot fill follow the same rule, locking slots in ascending slot_no order? The single-slot CTE deliberately picks ORDER BY random(), so a fill that reuses that random pick could lock slots in opposite orders for two buyers at the same time — right when the drop is hottest. Is deterministic slot ordering part of the design, or would that need a retry-on-deadlock wrapper in practice?