Redis-backed inventory holds: a fast reservation path that stays correct
The database pattern for inventory holds is correct. A hold table plus conditional UPDATE statements will not oversell, however hard you push it. What it will do under a flash sale is turn every add-to-cart into a write against one stock row, and the most popular products become the most contended rows in your database. Reserves queue up behind each other, latency climbs, and the whole checkout feels slow at the exact moment you most want it fast.
This is what a cache is for. Put the available count in Redis, do the fast check-and-decrement there, and let MySQL stay the record of truth behind it. This article covers how to do that without reintroducing the oversell you just designed out. It builds on the companion article, Inventory holds in MySQL: reservation tables, conditional updates, and clearing expired holds, which sets up the hold table and the conditional updates.
What Redis actually does here
Redis is not the source of truth. MySQL is. Redis holds a fast, disposable copy of one number per item, the available count, so the common question, “is there any left”, gets answered in memory instead of as a row lock in the database. If Redis loses that number, you rebuild it from MySQL. Nothing important lives only in Redis.
The value you cache is availability, not on-hand:
available = on_hand - reserved
Store it under a predictable key so you can find it, rebuild it, and reason about it:
stock:available:{sku}holds the current available count as a plain integer.- An optional
stock:synced:{sku}marker records when the key was last rebuilt from the database, which helps when you are chasing drift.
Keep MySQL exactly as it was. Redis sits in front; it does not replace the hold table or the cleanup job.
The race that a naive cache brings back
The tempting first version reads the counter, checks it in PHP, and decrements:
// Do NOT do this
$left = (int) $redis->get("stock:available:$sku");
if ($left >= $qty) {
$redis->decrby("stock:available:$sku", $qty); // too late
}
This is the same oversell you removed from the database, moved into Redis. Two requests both read “3 left”, both decide yes, both decrement, and availability goes to minus one. The GET and the DECRBY are separate commands, and anything can happen between them. A bare DECRBY is atomic on its own, but a decrement that is allowed to go negative is not a guard, it is just a faster way to oversell.
Atomic reserve with a Lua script
Redis runs a Lua script as a single, uninterruptible step. Nothing else touches the key while the script runs. That lets you do the check and the decrement together, which is exactly the Redis version of a conditional UPDATE:
-- reserve.lua
-- KEYS[1] = stock:available:{sku}
-- ARGV[1] = quantity requested
local available = tonumber(redis.call('GET', KEYS[1]))
if available == nil then
return -1 -- key missing: caller must warm it from MySQL
end
local qty = tonumber(ARGV[1])
if available < qty then
return -2 -- not enough stock
end
return redis.call('DECRBY', KEYS[1], qty) -- >= 0: new available count
The three return values give the caller everything it needs. A value of zero or more is success and is the new count. Minus one means the key is cold and you need to load it from the database and retry. Minus two means genuinely out of stock. Loading the script and calling it from CodeIgniter 4 with phpredis:
<?php
namespace App\Libraries;
use Redis;
class StockCache
{
private const RESERVE_LUA = <<<'LUA'
local available = tonumber(redis.call('GET', KEYS[1]))
if available == nil then return -1 end
local qty = tonumber(ARGV[1])
if available < qty then return -2 end
return redis.call('DECRBY', KEYS[1], qty)
LUA;
public function __construct(private Redis $redis) {}
/** Returns new available count, or -1 (cold key) / -2 (out of stock). */
public function reserve(string $sku, int $qty): int
{
return (int) $this->redis->eval(
self::RESERVE_LUA,
["stock:available:{$sku}", $qty],
1 // number of KEYS
);
}
public function release(string $sku, int $qty): void
{
// Returning stock is a plain atomic increment.
$this->redis->incrBy("stock:available:{$sku}", $qty);
}
}
In production, load the script once with SCRIPT LOAD and call it by its SHA with EVALSHA, falling back to EVAL if Redis reports NOSCRIPT. The phpredis client can manage that for you, but the behaviour is the same: one atomic check-and-decrement per reserve.
Warming a cold key from MySQL
When the script returns minus one, the counter is not in Redis yet, maybe because the cache was flushed or the item has never been touched. Rebuild it from the database, then retry the reserve. Rebuild the value from the same truth MySQL already holds:
<?php
public function reserveWithWarm(string $sku, int $qty): int
{
$result = $this->stock->reserve($sku, $qty);
if ($result === -1) { // cold key
$this->warm($sku);
$result = $this->stock->reserve($sku, $qty);
}
return $result; // >= 0 ok, -2 out of stock
}
private function warm(string $sku): void
{
$row = $this->db->table('stock_items')
->select('id, on_hand, reserved')
->where('sku', $sku)
->get()
->getRowArray();
if ($row === null) {
return;
}
$available = max(0, (int) $row['on_hand'] - (int) $row['reserved']);
// SET only if absent, so we never stomp a live counter that another
// request warmed a millisecond earlier.
$this->redis->set("stock:available:{$sku}", $available, ['nx']);
}
The NX flag on the SET is the important part. Two requests can hit a cold key at once; the first warms it, and the second must not overwrite the now-live, already-decremented value with a stale read from MySQL. NX means “set only if it does not exist”, so the loser of that race leaves the live counter alone and simply retries.
Writing through to the hold table
Redis answers “is there room”. The database still records the actual hold, because that is the durable, auditable truth. So a reserve is two steps in order: decrement Redis, then write the hold row. Decide Redis first, because that is the fast gate and the thing that must stay consistent under load:
- Call the Lua reserve. If it returns minus two, stop and tell the shopper it is gone.
- On success, write the hold to MySQL with the same conditional
UPDATEfrom the companion article, inside a transaction. - If that database write fails, give the Redis count straight back with an
INCRBY, so a failed reserve does not leak availability.
<?php
public function placeHold(string $sku, int $itemId, string $ref, int $qty): bool
{
$available = $this->reserveWithWarm($sku, $qty);
if ($available < 0) {
return false; // out of stock, nothing taken
}
try {
$ok = $this->holds->reserve($itemId, $ref, $qty); // DB conditional UPDATE
if (! $ok) {
// DB and cache disagree; the cache was optimistic. Give it back.
$this->stock->release($sku, $qty);
return false;
}
return true;
} catch (\Throwable $e) {
$this->stock->release($sku, $qty); // never leak the decrement
throw $e;
}
}
You will notice the database reserve can still fail even after Redis said yes. That is fine and expected. Redis is an optimistic fast path; MySQL is the final word. When they disagree, the database wins and you hand the Redis count back. The reverse, Redis saying no when stock exists, only costs you a missed sale you can recover by warming the key, which is a far cheaper mistake than overselling.
Releasing and expiring, with Redis in the loop
Every path that returns stock to MySQL must also return it to Redis, or the counter drifts low and you under-sell. There are two such paths and both already exist from the companion article.
Cancel and confirm
- On release, after the database hold flips to
released, callINCRBYto put the quantity back in the Redis counter. - On confirm, the stock is sold, so
on_handdrops by the same amount asreserved. Availability does not change, so the Redis counter stays put. Do not increment on a confirm.
The cleanup job returns stock to Redis too
The scheduled job that expires overdue holds is the one place that reclaims stock without a shopper in the loop, so it must top the Redis counter back up as it goes. Add the INCRBY right after the database reclaim succeeds:
// Inside the cleanup command, after the hold flips to 'expired'
if ($db->affectedRows() === 1) {
$db->query(
'UPDATE stock_items
SET reserved = reserved - ?
WHERE id = ? AND reserved >= ?',
[$hold['quantity'], $hold['stock_item_id'], $hold['quantity']]
);
// Return the freed stock to the cache, if the key is live.
$redis->eval(
"if redis.call('EXISTS', KEYS[1]) == 1 then
return redis.call('INCRBY', KEYS[1], ARGV[1])
end
return -1",
["stock:available:{$sku}", $hold['quantity']],
1
);
}
The EXISTS check matters. If the counter is cold, do not create it from a partial increment, because an increment on a missing key would start it at just the returned quantity and lie about availability. Only top up a key that is already live. A cold key gets its correct value the next time a reserve warms it from MySQL.
Keeping Redis and MySQL in agreement
Caches drift. A process dies between the Redis decrement and the database write, a deploy flushes Redis, a bug skips an increment. You plan for drift rather than hope it away. Three habits keep it in check.
MySQL is always the source of truth
Any time you are unsure of a count, the answer is on_hand - reserved from the database, and reserved itself is the sum of active holds. Redis is always rebuildable from those. Never let the cache be the only place a number lives.
A reconciliation job
Run a slow, periodic sweep, every few minutes or at a quiet hour, that recomputes availability from MySQL and corrects the Redis counter for any item that has drifted. Correct toward the database, never the other way:
<?php
// holds:reconcile-cache (a second Spark command)
foreach ($this->activeSkus() as $sku) {
$row = $this->db->table('stock_items')
->select('on_hand, reserved')
->where('sku', $sku)->get()->getRowArray();
$truth = max(0, (int) $row['on_hand'] - (int) $row['reserved']);
$cached = $this->redis->get("stock:available:{$sku}");
if ($cached === false || (int) $cached !== $truth) {
// Overwrite: the database is right, the cache was wrong.
$this->redis->set("stock:available:{$sku}", $truth);
$this->redis->set("stock:synced:{$sku}", date('c'));
log_message('info', "Reconciled {$sku}: cache={$cached} -> {$truth}");
}
}
Log every correction. A steady trickle of tiny corrections is normal. A sudden burst of large ones is a signal that a code path is missing its increment or decrement, and the log points you straight at which SKUs.
A TTL as a safety net, used with care
You can put a long TTL on the counter keys, say an hour, so a forgotten or orphaned key eventually expires and gets rebuilt from MySQL on the next reserve. If you do, be deliberate: a counter that expires mid-sale and gets rebuilt is fine only because the rebuild reads the true reserved from the hold table. Never use a short TTL that expires a hot counter while holds are in flight unless the rebuild path is rock solid. When in doubt, lean on the reconciliation job instead of TTLs.
When Redis is down
Decide this before it happens, because it will. You have two honest options when the cache is unreachable, and the right one depends on the product:
- Fail closed: refuse new reserves and show a brief “please try again” message. Correct, never oversells, but it turns a Redis outage into a checkout outage.
- Fail open to the database: skip Redis and run the reserve against MySQL with the conditional
UPDATEalone. Slower under load, but it keeps selling and it still cannot oversell, because the database guard is always there.
Failing open to the database is usually the better call, precisely because you kept MySQL as the source of truth. The cache was only ever an accelerator. Pull it out and the system is slower, not wrong. That property is the whole reason to build it this way.
Testing the cached path
- Hammer a single SKU with concurrent reserves and assert the total reserved never exceeds on-hand. The Lua script is the thing under test.
- Kill the process between the Redis decrement and the database write, then run the reconciliation job and assert the counts converge.
- Flush Redis mid-test and assert that reserves keep working through the warm path, and that no key is ever created by a stray increment.
- Pull the Redis connection and assert your chosen fallback behaves: either a clean refusal or a correct database-only reserve.
The shape of the whole thing
Put together, a reserve flows like this: the Lua script checks and decrements availability in Redis in one atomic step; on success the hold is written to MySQL under a conditional UPDATE; releases and the expiry cleanup job return stock to both stores; and a reconciliation job quietly corrects any drift back toward the database. Redis gives you the speed. MySQL gives you the truth. The conditional updates on both sides give you the one thing a shop cannot do without, which is never selling what it does not have.