Custom Software Development

Inventory holds in MySQL: reservation tables, conditional updates, and clearing expired holds

Two shoppers open the last unit of a product at the same second. Both see it in stock, both click buy, and both orders go through. Now you owe one of them a refund and an apology. This is the oversell problem, and it is the reason inventory needs reservations rather than a plain stock count you decrement at checkout.

A reservation, or hold, is a short-lived claim on stock. When a shopper adds an item to the cart or starts checkout, you set aside the quantity for a few minutes. If they pay, the hold becomes a sale. If they wander off, the hold expires and the stock returns to the pool. This article covers the database side of that pattern: the hold table, the conditional UPDATE statements that make a reserve safe under load, and a scheduled job that clears expired holds. The examples use MySQL and CodeIgniter 4.

The model: on hand, reserved, available

Keep two numbers per stock item and derive the third. On-hand is the physical count. Reserved is the sum of active holds. Available is what a new shopper is allowed to take:

available = on_hand - reserved

Store on_hand and reserved on the stock row and never let reserved climb past on_hand. Availability is then a read, not a row you have to keep in step. Here is the stock table for a single-location store:

CREATE TABLE stock_items (
    id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    sku           VARCHAR(64)     NOT NULL,
    on_hand       INT UNSIGNED    NOT NULL DEFAULT 0,
    reserved      INT UNSIGNED    NOT NULL DEFAULT 0,
    updated_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP
                                  ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    UNIQUE KEY uq_sku (sku)
) ENGINE=InnoDB;

The UNSIGNED columns are a cheap safety net. If a buggy update ever tries to push reserved below zero, MySQL rejects it instead of silently wrapping, as long as you are not running in a loose SQL mode. Treat that as a backstop, not the main guard. The real guard is in the WHERE clause, which comes later.

The reservation (hold) table

Each active hold is a row. The row records what is held, how much, for whom, and when it expires:

CREATE TABLE stock_holds (
    id            BIGINT UNSIGNED NOT NULL AUTO_INCREMENT,
    stock_item_id BIGINT UNSIGNED NOT NULL,
    reference     VARCHAR(64)     NOT NULL,   -- cart id, order id, session key
    quantity      INT UNSIGNED    NOT NULL,
    status        ENUM('active','confirmed','released','expired')
                                  NOT NULL DEFAULT 'active',
    expires_at    DATETIME        NOT NULL,
    created_at    DATETIME        NOT NULL DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id),
    KEY idx_item_status (stock_item_id, status),
    KEY idx_expiry (status, expires_at),
    KEY idx_reference (reference)
) ENGINE=InnoDB;

What each column is for

  • stock_item_id ties the hold to the stock row it draws from.
  • reference is your handle for the hold: a cart id, a draft order id, or a session key. You use it to confirm or release the right hold later.
  • quantity is how much this hold claims.
  • status is the lifecycle. A hold starts active, then becomes confirmed on payment, released if the shopper cancels, or expired if the clock runs out.
  • expires_at is the moment the hold stops counting. Set it when you create the hold, for example fifteen minutes out.

The indexes that matter

  • idx_item_status answers “how much is actively held for this item”, which you need when you rebuild the reserved count.
  • idx_expiry is the one the cleanup job leans on. It lets the job find active, overdue holds without scanning the table.
  • idx_reference lets checkout and cancel find a hold by its cart or order id in one hit.

Keep the hold row even after it is confirmed, released, or expired. It is your audit trail. If a count ever looks wrong, the holds table tells you what happened and when. Prune old non-active rows on a slow schedule, not on the hot path.

Placing a hold with a conditional UPDATE

The unsafe version of a reserve is the one almost everyone writes first:

-- Do NOT do this
SELECT on_hand, reserved FROM stock_items WHERE id = 42;
-- app checks: on_hand - reserved >= qty ?
UPDATE stock_items SET reserved = reserved + :qty WHERE id = 42;

The gap between the SELECT and the UPDATE is where two requests both read “plenty left”, both decide yes, and both add to reserved. You have oversold. Wrapping it in a transaction does not fix it on its own, because the default isolation level still lets both reads see the same starting value.

The fix is to move the decision into the write. Let the database check and update in one statement, and put the availability test in the WHERE clause:

UPDATE stock_items
   SET reserved = reserved + :qty
 WHERE id = :id
   AND on_hand - reserved >= :qty;

This is the whole trick. The row is locked for the duration of the UPDATE, so the check and the change cannot be split. If the item does not have enough free stock, the WHERE clause matches nothing and the update changes zero rows. No negative stock is ever possible, because the condition that would create it is the condition that stops the write.

The result you act on is the affected-row count, not an exception. One row changed means the reserve succeeded. Zero rows changed means there was not enough stock. In CodeIgniter 4:

<?php

namespace App\Models;

use CodeIgniter\Database\BaseConnection;

class HoldService
{
    public function __construct(private BaseConnection $db) {}

    /**
     * Reserve $qty of a stock item for $reference.
     * Returns the hold id, or null if there was not enough stock.
     */
    public function reserve(int $itemId, string $reference, int $qty, int $ttlMinutes = 15): ?int
    {
        $this->db->transStart();

        // Atomic guard: only reserves when enough free stock exists.
        $this->db->query(
            'UPDATE stock_items
                SET reserved = reserved + ?
              WHERE id = ?
                AND on_hand - reserved >= ?',
            [$qty, $itemId, $qty]
        );

        if ($this->db->affectedRows() !== 1) {
            $this->db->transComplete();   // nothing changed
            return null;                  // caller shows "out of stock"
        }

        $this->db->table('stock_holds')->insert([
            'stock_item_id' => $itemId,
            'reference'     => $reference,
            'quantity'      => $qty,
            'status'        => 'active',
            'expires_at'    => date('Y-m-d H:i:s', time() + $ttlMinutes * 60),
        ]);
        $holdId = $this->db->insertID();

        $this->db->transComplete();

        return $this->db->transStatus() ? $holdId : null;
    }
}

Two things make this correct. The reserve and the hold insert sit in one transaction, so you never bump reserved without a matching hold row. And the guard lives in SQL, so concurrency is the database engine’s problem, which is exactly what it is good at. You are not holding a row lock across a round trip to PHP; the lock lasts only as long as the single UPDATE.

Rule of thumb: if a check decides whether a write is safe, do the check inside the write. A WHERE clause is a lock you do not have to manage.

Confirming, releasing, and extending holds

The same discipline covers the rest of the lifecycle. Every state change is a conditional UPDATE that only fires when the hold is still in the state you expect, so a double click or a retry cannot apply the same change twice.

Confirm at payment

When payment clears, the held stock becomes sold. Move it out of reserved and out of on_hand, and flip the hold to confirmed, but only if it is still active:

-- Flip the hold first; only an active hold can be confirmed.
UPDATE stock_holds
   SET status = 'confirmed'
 WHERE reference = :ref
   AND status = 'active';
-- affectedRows() === 1 means this request owns the confirmation.

-- Then settle the stock for that exact quantity.
UPDATE stock_items
   SET on_hand  = on_hand  - :qty,
       reserved = reserved - :qty
 WHERE id = :id;

Because the first statement only matches an active hold, a duplicate confirmation request changes zero rows and you skip the stock settlement. That idempotency is what saves you when a payment webhook is delivered twice, which it will be.

Release on cancel

If the shopper removes the item or abandons the cart, hand the stock back. Guard it the same way so a release can run only once:

UPDATE stock_holds
   SET status = 'released'
 WHERE reference = :ref
   AND status = 'active';
-- Only when a row actually flipped, return the quantity:

UPDATE stock_items
   SET reserved = reserved - :qty
 WHERE id = :id;

Run both inside one transaction and only touch stock_items when the hold flip changed a row. If you return stock without checking, a double cancel gives the shopper’s quantity back twice and now you have phantom stock that does not exist.

Extend a hold

If a shopper is still on the payment page as the clock runs down, push the expiry out rather than dropping and re-taking the stock:

UPDATE stock_holds
   SET expires_at = :new_expiry
 WHERE reference = :ref
   AND status = 'active';

Clearing expired holds: the scheduled job

Holds expire quietly. A shopper who closes the tab does not tell you. So something has to sweep the table, find holds whose expires_at has passed, mark them expired, and return their quantity to the pool. In CodeIgniter 4 that is a Spark command run on a schedule.

The command

The job works in batches and leans on the same conditional-update safety. Each hold it reclaims is flipped from active to expired first; only a hold that actually flipped gets its stock returned. That makes the job safe to run again if it is interrupted half way, and safe if two copies ever overlap.

<?php

namespace App\Commands;

use CodeIgniter\CLI\BaseCommand;
use CodeIgniter\CLI\CLI;
use Config\Database;

class ReleaseExpiredHolds extends BaseCommand
{
    protected $group       = 'Inventory';
    protected $name        = 'holds:release-expired';
    protected $description = 'Expire overdue stock holds and return their quantity to stock.';

    public function run(array $params): void
    {
        $db        = Database::connect();
        $batchSize = (int) ($params['batch'] ?? 500);
        $reclaimed = 0;

        while (true) {
            // Grab a batch of overdue, still-active holds.
            $due = $db->table('stock_holds')
                      ->select('id, stock_item_id, quantity')
                      ->where('status', 'active')
                      ->where('expires_at <', date('Y-m-d H:i:s'))
                      ->limit($batchSize)
                      ->get()
                      ->getResultArray();

            if ($due === []) {
                break;
            }

            foreach ($due as $hold) {
                $db->transStart();

                // Flip exactly one active hold. If another worker beat us
                // to it, affectedRows() is 0 and we return nothing.
                $db->query(
                    "UPDATE stock_holds
                        SET status = 'expired'
                      WHERE id = ?
                        AND status = 'active'",
                    [$hold['id']]
                );

                if ($db->affectedRows() === 1) {
                    $db->query(
                        'UPDATE stock_items
                            SET reserved = reserved - ?
                          WHERE id = ?
                            AND reserved >= ?',
                        [$hold['quantity'], $hold['stock_item_id'], $hold['quantity']]
                    );
                    $reclaimed++;
                }

                $db->transComplete();
            }

            if (count($due) < $batchSize) {
                break;
            }
        }

        CLI::write("Released {$reclaimed} expired hold(s).", 'green');
    }
}

A few choices in there are deliberate:

  • Batching keeps each transaction small. A sweep of fifty thousand dead holds does not become one giant lock that blocks live checkouts.
  • The flip-then-return order means a hold can only be reclaimed once. Run the command twice at the same time and the second run finds the rows already expired and does nothing.
  • The reserved >= ? guard on the stock update is a second belt. Even if a count has drifted, the job will not drive reserved negative.
  • Nothing is deleted. The hold row stays as expired for the audit trail.

Scheduling it

Run it every minute. A hold that expired a few seconds ago can wait up to a minute to be swept, which is fine because availability already treats it as gone the moment a shopper tries to reserve past it. CodeIgniter’s task scheduler, in app/Config/Tasks.php:

<?php

namespace Config;

use CodeIgniter\Tasks\Scheduler;

class Tasks extends \Config\BaseConfig
{
    public function init(Scheduler $schedule): void
    {
        $schedule->command('holds:release-expired')->everyMinute();
    }
}

That scheduler itself needs one real cron entry on the server to tick it over:

* * * * * cd /var/www/shop && php spark tasks:run >> /dev/null 2>&1

If you are not using the tasks package, skip it and call the command straight from cron:

* * * * * cd /var/www/shop && php spark holds:release-expired --batch=500 >> /dev/null 2>&1

A note on locking and isolation

People reach for SELECT ... FOR UPDATE when they think about stock, and there are cases for it, for example when one request has to read several rows and decide across them. But for a single-item reserve, the conditional UPDATE is simpler and usually faster. It takes the row lock for the shortest possible window, the duration of one statement, and it never holds a lock while your PHP code is thinking. Fewer locks held for less time means less chance of two requests deadlocking.

One operational detail: a deadlock can still happen when many updates hit overlapping rows, and InnoDB resolves it by killing one of the transactions. Treat a deadlock as a retryable event. Catch it, wait a few milliseconds, and try the reserve once more. It is rare, but under a flash sale it is not never.

Testing it before it bites you

  • Write a concurrency test that fires many reserves at a single unit at once and asserts that exactly one succeeds. If your test runner cannot do real parallelism, drive it with a few shell processes hitting the endpoint.
  • Test the double confirm and double release paths. Send the same confirm twice and assert the stock moved once.
  • Test the cleanup job for idempotency. Run it twice back to back over the same expired holds and assert the reserved count lands in the right place, not double-returned.
  • Add a reconciliation check you can run on demand: for each item, assert reserved equals the sum of quantity over its active holds. If they ever diverge, a conditional update somewhere is missing its guard.
-- Reconciliation query: every row here is a bug to investigate.
SELECT s.id, s.sku, s.reserved,
       COALESCE(SUM(h.quantity), 0) AS active_holds
  FROM stock_items s
  LEFT JOIN stock_holds h
    ON h.stock_item_id = s.id AND h.status = 'active'
 GROUP BY s.id, s.sku, s.reserved
HAVING s.reserved <> active_holds;

Where this gets you

With a hold table, conditional updates, and a one-minute cleanup job, you have an inventory system that will not oversell and that cleans up after shoppers who never finish. It is correct and it is honest: MySQL holds the truth, and every change to that truth is a guarded write.

It also has a ceiling. When traffic spikes, every add-to-cart becomes a write against the stock row, and the hottest products become the hottest rows. That is where a cache earns its place. The companion article, Redis-backed inventory holds: a fast reservation path that stays correct, puts Redis in front of this, so the stock check happens in memory while MySQL stays the source of truth.

Custom Software Development

Web Application Development on the LAMP Stack

Why I still build business systems on the LAMP stack (Linux, Apache, MySQL, PHP): what each part does, why it holds up, and how…

3 min read

Have a similar challenge?

Business systems, WordPress platforms, performance or infrastructure: tell me what you are working on.

Start a conversation