The Double-Restock Ghost: How Orphaned Inventory Holds Corrupted Stock Counters on Checkout Failure
When multi-item checkout fails halfway through, a naive compensation loop restores item counters but leaves hold documents orphaned. 15 minutes later, the background sweeper treats those holds as expired and restocks the items a second time. The complete post-mortem and transactional fix for [LUMINA] Custom Ecommerce App.

01 · Introduction: The Mystery of Creeping Stock
In high-concurrency e-commerce systems, inventory count integrity is holy. If your database claims you have 3 units of an item in stock when your warehouse physically has zero, you have committed the cardinal sin of digital retail: overselling.
During high-traffic promotional periods for [LUMINA], our custom high-performance e-commerce platform, we began observing a bizarre, intermittent inventory discrepancy. Inventory counters were not dropping unexpectedly—they were creeping upward. A limited-edition product that had physically sold down to 2 units suddenly showed 4 available in the catalog 24 hours later. No warehouse restocks had occurred. No administrative manual adjustments had been entered into the database.
✓ Verified: In-Lab Repro
The phantom stock wasn't caused by a display glitch or caching layer staleness. Real, unfulfillable orders were being placed against phantom inventory units that did not physically exist.
When we audited the operational trace logs in src/modules/inventory/inventoryService.ts:L54-92, we discovered a terrifying trap born from the intersection of a partial compensation rollback and a well-intentioned background cleanup worker.
02 · Anatomy of the Multi-Item Reservation Flow
When a shopper proceeds to checkout with multiple items in [LUMINA], the commerce engine must guarantee that those items cannot be snatched by another shopper while the first user inputs payment details.
To solve this, the platform employs temporary Inventory Holds (typically valid for 10 to 15 minutes):
interface InventoryReservation {
_id: string;
orderId: string;
productId: string;
quantity: number;
status: 'HELD' | 'COMMITTED' | 'CANCELLED' | 'EXPIRED';
expiresAt: Date;
createdAt: Date;
}The checkout orchestration service executes a two-phase reservation pipeline:
1. Decrement Physical Stock: Deduct the requested quantity from the product document ($inc: { stock: -qty }).
2. Issue Hold Document: Insert an InventoryReservation record tagged with status: 'HELD' and an expiration timestamp 15 minutes into the future.
3. Payment Completion: Once payment settles via webhook, the holds are updated to COMMITTED.
Here was the initial implementation inside src/modules/inventory/inventoryService.ts:
// The Naive Sequential Reservation Service in [LUMINA]
export async function reserveInventoryForOrder(
orderId: string,
items: CartItem[]
): Promise<ReservationResult> {
const createdHolds: InventoryReservation[] = [];
try {
for (const item of items) {
// 1. Atomically decrement stock if sufficient
const product = await Product.findOneAndUpdate(
{ _id: item.productId, stock: { $gte: item.quantity } },
{ $inc: { stock: -item.quantity } },
{ new: true }
);
if (!product) {
throw new OutOfStockError(`Item ${item.productId} is out of stock`);
}
// 2. Record the hold document
const hold = await InventoryReservation.create({
orderId,
productId: item.productId,
quantity: item.quantity,
status: 'HELD',
expiresAt: new Date(Date.now() + 15 * 60 * 1000), // 15-minute TTL
});
createdHolds.push(hold);
}
return { success: true, holds: createdHolds };
} catch (error) {
// 3. Rollback loop on failure
await rollbackPartialHolds(createdHolds);
throw error;
}
}At first glance, this looks clean and defensive. It uses atomic conditional queries (stock: { $gte: item.quantity }) to prevent negative inventory, and wraps the loop in a try/catch with a rollback routine.
However, the defect lived in how the rollback was handled.
03 · The Flawed Rollback: Anatomy of a Partial Failure
Imagine a shopper attempting to checkout two products in a single cart on [LUMINA]: * Item A: Stock in DB = 5. Quantity requested = 1. * Item B: Stock in DB = 0 (Out of Stock). Quantity requested = 2.
Let's trace the loop execution step by step:
1. Iteration 1 (Item A):
* Query finds Item A (stock: 5 >= 1).
* Item A stock decremented from 5 to 4.
* Reservation record created: { productId: 'ItemA', status: 'HELD', expiresAt: +15m }.
* Pushed to createdHolds.
2. Iteration 2 (Item B):
* Query fails for Item B (stock: 0 < 2).
* Product.findOneAndUpdate returns null.
* Throws OutOfStockError('Item B is out of stock').
3. Catch Block: The Compensation Rollback:
The exception triggers rollbackPartialHolds(createdHolds).
Here is the exact code that was executing inside the rollback helper:
// The Flawed Rollback Helper
async function rollbackPartialHolds(holds: InventoryReservation[]) {
for (const hold of holds) {
// Restore physical stock counter
await Product.updateOne(
{ _id: hold.productId },
{ $inc: { stock: hold.quantity } }
);
// 🚨 FATAL DEFECT: The hold document in MongoDB is left in 'HELD' status!
}
}The rollback loop diligently executed $inc: { stock: +1 } for Item A. Item A's physical stock counter in MongoDB was restored from 4 back to 5.
The shopping cart returned an error to the user: *"Item B is out of stock."* The checkout was aborted.
Item A was back at 5. Everything appeared balanced. But hidden inside the InventoryReservation collection, an orphaned document was ticking like a time bomb.
04 · The 15-Minute Ghost: The Background Sweeper Trap
Like all production e-commerce architectures, [LUMINA] has an automated background worker designed to handle abandoned checkouts. If a user adds an item to cart, reserves stock, and abandons their session, that stock must be restored to the public catalog after 15 minutes.
Here was the cron worker running inside src/lib/queue/inventoryCleaner.ts:
// Sweeps expired holds every 15 minutes
export async function sweepExpiredHolds() {
const now = new Date();
// Find all holds that expired and are still marked HELD
const expiredHolds = await InventoryReservation.find({
status: 'HELD',
expiresAt: { $lt: now },
});
for (const hold of expiredHolds) {
// 1. Return the held quantity to inventory
await Product.updateOne(
{ _id: hold.productId },
{ $inc: { stock: hold.quantity } }
);
// 2. Mark the hold as EXPIRED
hold.status = 'EXPIRED';
await hold.save();
logger.info(`Restocked expired hold ${hold._id} for product ${hold.productId}`);
}
}Now examine the catastrophe when these two systems interact:
| Timeline | Action | Item A Physical Stock in DB | Item A Reservation Record Status |
|---|---|---|---|
| T+00:00 | Initial Baseline | 5 | *(None)* |
| T+00:01 | Item A reserved during checkout | 4 | HELD (expires at T+15:00) |
| T+00:02 | Item B fails out-of-stock; Rollback fires | 5 *(Restored via rollback)* | HELD (Left Orphaned!) |
| T+00:03 | User leaves site | 5 *(True inventory)* | HELD (Still in DB) |
| T+15:01 | Cleaner Worker Sweeps | 6 (🚨 INFLATED!) | EXPIRED |
Every single multi-item checkout failure silently created +1 phantom inventory unit for every item that preceded the out-of-stock item.
If 10 users attempted to buy a cart containing Item A and an out-of-stock item throughout a flash sale, Item A's stock counter would drift from 5 to 15.
05 · Reproduction: Simulating the Counter Drift
To verify the failure mode in a deterministic environment, we engineered a rigorous test script.
test('Orphaned hold causes double-restock drift in [LUMINA]', async () => {
// Setup: Product with initial stock of 10
const product = await Product.create({ name: 'Lumina Signature Desk', stock: 10 });
const outOfStockItem = await Product.create({ name: 'Sold Out Lamp', stock: 0 });
// Step 1: Attempt multi-item checkout that will fail on item 2
try {
await reserveInventoryForOrder('test_order_123', [
{ productId: product._id, quantity: 1 },
{ productId: outOfStockItem._id, quantity: 1 }, // Will fail!
]);
} catch (err) {
// Expected to fail
}
// Step 2: Immediate check — stock should be 10 (inline rollback succeeded)
const immediateProduct = await Product.findById(product._id);
expect(immediateProduct.stock).toBe(10); // ✓ Passes immediately
// Step 3: Fast-forward time by 16 minutes and run cleaner
jest.advanceTimersByTime(16 * 60 * 1000);
await sweepExpiredHolds();
// Step 4: Re-query product — verifies whether phantom stock was injected
const driftProduct = await Product.findById(product._id);
// 🚨 BEFORE FIX: driftProduct.stock was 11!
expect(driftProduct.stock).toBe(10);
});In the unpatched codebase, the assertion violently failed:
Expected: 10, Received: 11.
06 · The Architectural Solution: Two-Tier Defense
We resolved this bug in [LUMINA] using a dual-defense strategy: immediate atomic compensation in the catch block, backed by strict database state invariants.
Tier 1: Compensating Cancellation in the Rollback Loop
In the rollback handler, every reservation record created during the abortive attempt must transition toCANCELLED (or be deleted outright) before the function exits:// The Fortified Rollback Handler in [LUMINA]
async function rollbackPartialHolds(holds: InventoryReservation[]) {
for (const hold of holds) {
// 1. Mark hold as CANCELLED so background workers ignore it
await InventoryReservation.updateOne(
{ _id: hold._id, status: 'HELD' },
{ $set: { status: 'CANCELLED', cancelledAt: new Date() } }
);
// 2. Restore the physical inventory counter
await Product.updateOne(
{ _id: hold.productId },
{ $inc: { stock: hold.quantity } }
);
}
}By marking the hold CANCELLED *before* restocking, the query in the background sweeper ({ status: 'HELD', expiresAt: { $lt: now } }) will never select the record.
Tier 2: Transactional Isolation with MongoDB Sessions
While the compensating loop works, true high-integrity architectures avoid manual rollbacks entirely by leveraging MongoDB multi-document ACID transactions:// The Publication-Grade Transactional Reservation Service
export async function reserveInventoryTransactional(
orderId: string,
items: CartItem[]
): Promise<ReservationResult> {
const session = await mongoose.startSession();
session.startTransaction();
try {
const createdHolds: InventoryReservation[] = [];
for (const item of items) {
// 1. Atomic decrement within session
const product = await Product.findOneAndUpdate(
{ _id: item.productId, stock: { $gte: item.quantity } },
{ $inc: { stock: -item.quantity } },
{ session, new: true }
);
if (!product) {
throw new OutOfStockError(`Item ${item.productId} is out of stock`);
}
// 2. Hold document inserted within same session
const [hold] = await InventoryReservation.create(
[
{
orderId,
productId: item.productId,
quantity: item.quantity,
status: 'HELD',
expiresAt: new Date(Date.now() + 15 * 60 * 1000),
},
],
{ session }
);
createdHolds.push(hold);
}
await session.commitTransaction();
return { success: true, holds: createdHolds };
} catch (error) {
// 3. Atomically abort: all decrements and hold documents vanish!
await session.abortTransaction();
throw error;
} finally {
session.endSession();
}
}With transactions: * If item 2 fails, the entire transaction aborts. * The stock decrement for item 1 is cleanly rolled back by the database engine. * The reservation document for item 1 is never written to disk. * There are zero orphaned documents for the background cleaner to stumble upon.
07 · Automated CI Invariants & Safeguards
To prevent regression across all [LUMINA] e-commerce microservices, we deployed an automated CI test suite that validates inventory conservation:
1. Mass Checkout Stress Test: 50 simulated concurrent users checking out carts with intentionally mismatched stock availability.
2. Post-Execution Sweeper Run: Force-triggering the sweepExpiredHolds() worker.
3. Conservation Assertion: Total available stock + committed order units must precisely equal initial inventory:
$$\sum (\text{Current Stock}) + \sum (\text{Committed Units}) \equiv \text{Initial Stock}$$
✓ Verified: In-Lab Repro
Any variation ($> 0$ or $< 0$) immediately terminates the deployment pipeline and triggers a high-severity alert.
08 · Key Engineering Takeaways
1. Compensation Requires Symmetric State Transitions: If your creation flow mutates both counters and state records, your rollback handler must mutate both in reverse. Restoring the counter while leaving the state record orphaned creates an invisible split-brain.
2. Background Cleaners Are Double-Edged Swords: Cron jobs that blindly assume all records in state X arrived there through legitimate, un-aborted paths will inevitably act on ghost data. Always design workers with idempotency keys and state transition guards.
3. Prefer ACID Transactions Over Distributed Sagas When Feasible: If your entities live in the same MongoDB replica set, multi-document transactions eliminate hundreds of lines of fragile manual compensation logic.
4. Audit for "Upward Drift": In inventory and billing systems, monitoring tools typically alert on downward spikes (e.g. inventory hitting 0). Upward inventory drift is far more insidious because it looks like healthy stock right until your shipping team is forced to cancel an unfulfillable order.
[LUMINA] Custom Ecommerce App — Custom E-Commerce
A bespoke high-concurrency custom e-commerce application engineered with atomic inventory holds, real-time checkout reservation state machines, and headless performance.