Database Case StudyEvidence: Verified8 min read•November 3, 2026

The 38.60-Litre Inventory Black Hole: Why Asymmetric Deletion Handlers Leak Physical Warehouse Stock

A real-world engineering post-mortem from building a custom FMCG cold-chain distribution app: how a naive 5-line order deletion handler caused 69 physical units (38.60 Litres) of inventory to vanish into a phantom state during warehouse reconciliation, and how we engineered symmetrical lifecycle rollbacks and audit ledgers to fix it.

Ajay Thakkar
Ajay ThakkarAuthor
Full-Stack Developer & Software Architect
Editorial architectural diagram of 2FA bypass and edge proxy matcher remediation
Cover: Architectural schematic of Next.js 16 Edge Proxy matcher bypass and controller invariant guard.
⚡ Engineering Metrics & Invariant Profile
Vulnerability Class
Asymmetric Entity Lifecycle Deletion
Phantom Deficit
38.60 Litres across 69 Packaged Units
Database Invariant
Atomic MongoDB Multi-Document Rollback
Reconciliation Health
100% Symmetrical Stock Synchronization

01 · Why I Built a Custom App for My Everyday Sales Job

I didn't build this distribution engine as a weekend coding toy or a resume template. I built it because I was working a real, grueling everyday FMCG sales and distribution job—and standard legacy enterprise tools were bleeding hours out of my day.

Every single morning at 7:00 AM, I was in the trenches managing territory operations across 40+ supermarkets, retail parlors, and restaurant accounts. The operational reality of commercial cold-chain ice cream logistics is intensely fast-paced:

  • Ice cream is strictly temperature-controlled and stored at -20°C.
  • Stock exists in mixed packing formats: Impulse Sticks (12-pack boxes), Cups (12-pack boxes), Stickless bars (27-pack boxes), 500ml Tubs (individual pieces), and 1000ml Catering Tubs (individual pieces).
  • Every transaction requires dynamic bi-directional conversions between physical units (boxes/tubs) and total liquid volume (Litres) for corporate sales reporting and warehouse dispatch.

Legacy ERPs were painfully slow on mobile, and coordinating route deliveries over scattered WhatsApp messages was an invitation for chaos. So, I took matters into my own hands: I architected and built a custom, real-time sales control and warehouse management web application with Next.js, TypeScript, and MongoDB Atlas.

With one tap on my phone, I could log outlet orders, instantly check live warehouse inventory, calculate exact litrage weights, reserve stock, and track dispatch status.

For weeks, it felt like an operational superpower. Route dispatch times dropped by nearly 40%, and our order reconciliation was immaculate.

Until one Tuesday morning, when a routine order deletion exposed an invisible defect that shattered our inventory reality.


02 · Where Did 38.60 Litres of Stock Disappear?

A commercial retail client had placed an order for 69 assorted units of premium ice cream. The order was processed, packed into thermal insulated boxes with dry ice, and marked DISPATCHED on the platform.

Shortly after dispatch, the client called to cancel the shipment due to a freezer breakdown at their storefront. The delivery van turned back, and the insulated crates were wheeled straight back into our cold room.

To keep the platform clean, I opened the admin operations panel and clicked "Delete Order".

The UI showed a clean green toast: *"Order deleted successfully."* The order row vanished from the table. MongoDB reported a 200 OK. No error logs. No server crashes.

Three days later, during our scheduled end-of-week physical warehouse audit inside the -20°C freezer, our warehouse manager looked up from his clipboard with a furrowed brow:

> *"Ajay, the dashboard says we should have 291.81 Litres on the shelves. But our physical count is only 253.21 Litres. We are missing exactly 69 boxes and tubs. Where did 38.60 Litres of ice cream go?"*

Ice cream doesn't evaporate into thin air. Goods hadn't melted, and nobody had stolen 38 Litres of stock.

The physical items were sitting right there on the warehouse shelf. But on the screen, they were gone. The software had permanently wiped them from available inventory.

They had fallen into an inventory black hole.


03 · The Asymmetry of Entity Lifecycles in Cold-Chain Logistics

To understand how software causes physical inventory to vanish, look at how the inventory state machine was designed to progress:

codeSanitized Environment
[STAGE 1: ORDER PLACED]
   │
   ├──> physicalStock : Unchanged (still physically in warehouse)
   └──> reservedQty   : +Quantity (locked so others can't purchase)

[STAGE 2: ORDER DISPATCHED]
   │
   ├──> physicalStock : -Quantity (deducted as goods leave the depot)
   ├──> reservedQty   : Drops to 0 (hold is fulfilled)
   └──> dispatchedQty : Recorded on item records

When an order is created, goods are merely *reserved*. But when an order is *dispatched*, the physical goods leave the warehouse: physicalStock is decremented by $inc: { physical: -qty }, and reservedQty drops to 0.

Now, look at the naive deletion handler that was running in our /api/orders DELETE route:

typescriptSanitized Environment
// Flawed deletion route: only inspected unfulfilled reservations
export async function DELETE(req: Request) {
  const { orderId } = await req.json();
  const order = await Order.findById(orderId);

  // Bug: Only checks reservedQty, completely ignoring dispatchedQty!
  for (const item of order.items) {
    if (item.reservedQty > 0) {
      await Product.findByIdAndUpdate(item.productId, {
        $inc: { reservedQty: -item.reservedQty }
      });
    }
  }

  // Order document wiped permanently from MongoDB
  await Order.findByIdAndDelete(orderId);
}

The Chain Reaction Behind the Deficit

1. When the order was created, reservedQty was 69 units. 2. When the order was dispatched for delivery, the warehouse worker marked it DISPATCHED. The system subtracted 69 units from physicalStock and reset reservedQty to 0. 3. When the order was cancelled and deleted, the code executed: if (item.reservedQty > 0) 4. Because reservedQty was already 0, the condition 0 > 0 evaluated to false. 5. The loop silently exited without executing any database updates. 6. The Order document was permanently expunged via findByIdAndDelete(orderId).

The result was a catastrophic state divergence:

  • The database order record was gone forever.
  • The 69 physical items returned to the shelf were never credited back to physicalStock.
  • Available stock on the merchant platform remained permanently depressed by 38.60 Litres, preventing legitimate stores from ordering products that were physically sitting in the warehouse.


04 · Physical Warehouse Stock Audit (69 Units / 38.60 Litres)

When we cross-referenced the order history with physical crate manifests, we isolated the exact phantom deficit:

Product SKUPacking FormatMissing QtyUnit LitresTotal Volume Leaked
Almond Stick100ml Stick (Box of 12)1 Box1.20 L1.20 Litres
Berries & Cream100ml Stick (Box of 12)1 Box1.20 L1.20 Litres
Belgian Chocolate100ml Stick (Box of 12)1 Box1.20 L1.20 Litres
Premium Vanilla500ml Tub (Piece)12 Pieces0.50 L6.00 Litres
Cookies & Cream500ml Tub (Piece)12 Pieces0.50 L6.00 Litres
Double Chocolate500ml Tub (Piece)12 Pieces0.50 L6.00 Litres
Choco Brownie Delight500ml Tub (Piece)12 Pieces0.50 L6.00 Litres
Mango Sorbet500ml Tub (Piece)11 Pieces0.50 L5.50 Litres
Simply Strawberry500ml Tub (Piece)3 Pieces0.50 L1.50 Litres
Premium Vanilla1000ml Tub (Piece)2 Pieces1.00 L2.00 Litres
Double Chocolate1000ml Tub (Piece)2 Pieces1.00 L2.00 Litres
TOTAL LEAKED—69 Units—38.60 Litres

05 · Symmetrical State Rollbacks with MongoDB ACID Transactions

Fixing an asymmetric deletion bug requires adhering to a fundamental rule of domain modeling:

🔒 SECURITY NOTICE
The Symmetrical Lifecycle Invariant: A deletion or cancellation handler must mirror every state transition the entity has passed through during its lifetime—not just the initial stage.

If an entity can exist in multiple stages (PENDING $\to$ RESERVED $\to$ DISPATCHED $\to$ DELIVERED), rolling it back requires inspecting its exact terminal position and reversing whatever deltas were applied.

Production Rollback Implementation

typescriptSanitized Environment
// Symmetrical deletion handler with ACID transaction
// File: src/app/api/orders/route.ts

export async function DELETE(req: Request) {
  const { orderId } = await req.json();
  const session = await mongoose.startSession();

  try {
    await session.withTransaction(async () => {
      const order = await Order.findById(orderId).session(session);
      if (!order) {
        throw new Error('Order not found');
      }

      for (const item of order.items) {
        const stockUpdates: Record<string, number> = {};

        // 1. Roll back temporary reservations if order was pending
        if (item.reservedQty > 0) {
          stockUpdates.reserved = -item.reservedQty;
        }

        // 2. Restore physical warehouse stock if order was already dispatched
        if (item.dispatchedQty > 0) {
          stockUpdates.physical = item.dispatchedQty;
        }

        if (Object.keys(stockUpdates).length > 0) {
          await InventoryModel.findOneAndUpdate(
            { skuId: item.skuId },
            { $inc: stockUpdates },
            { session }
          );

          // 3. Write immutable audit ledger entry for warehouse transparency
          await InventoryLedgerModel.create(
            [
              {
                skuId: item.skuId,
                orderNo: order.orderNo,
                outlet: order.outletName,
                type: 'ADJUSTMENT',
                physicalDelta: item.dispatchedQty || 0,
                reservedDelta: -(item.reservedQty || 0),
                note: `Order ${order.orderNo} deleted: restored physical stock`,
              },
            ],
            { session }
          );
        }
      }

      // 4. Atomically delete the order document inside the same transaction
      await Order.findByIdAndDelete(orderId).session(session);
    });

    return NextResponse.json({ success: true, message: 'Order deleted and inventory restored' });
  } catch (error) {
    console.error('[ORDER_DELETE_ERROR]', error);
    return NextResponse.json({ error: 'Failed to delete order safely' }, { status: 500 });
  } finally {
    session.endSession();
  }
}


06 · Safeguarding Destructive Actions in the User Interface

A software bug is rarely just a backend code issue—it is often aided and abetted by an opaque user interface.

In our original UI, clicking the trash icon simply asked: *"Are you sure you want to delete this order?"* It gave the user zero visibility into the underlying state machine.

We updated our confirmation dialog with real-time operational context:

  • If the order is in PENDING status, the dialog warns: *"This will release reserved units back to general availability."*
  • If the order is in DISPATCHED status, the dialog highlights in amber:
"Warning: This order has already been dispatched. Deleting it will automatically credit physical goods back into warehouse inventory."

When the admin confirms, a success toast explicitly states: "Order deleted: physical goods restored to warehouse inventory."


07 · Architectural Lessons from the Warehouse Floor

Building software for your own daily operations teaches lessons no textbook can replicate:

1. Deletions Are Not Stateless

Hard-deleting a database row (findByIdAndDelete) does not erase the real-world physical events that occurred while that row existed. If goods moved, if money changed hands, or if locks were acquired, deleting the parent record without rolling back secondary effects causes irreversible data corruption.

2. Prefer Soft Deletes in Asset Management Systems

In high-stakes inventory or financial systems, hard document deletion is an anti-pattern. A superior architectural pattern is a soft transition: mark status: 'CANCELLED' and record a cancellationReason. This preserves historical audit trails while triggering state-reversal hooks automatically.

3. Audit Ledgers Are Your Black Box Flight Recorder

The introduction of an immutable inventory ledger transformed our debugging capability. By writing an immutable ledger event for every single delta (RESERVE, DISPATCH, RELEASE, ADJUSTMENT), stock counts can always be deterministically audited and reconstructed from day zero.

4. Real Software Is Forged in the Trenches

Anyone can build a neat CRUD app following an online tutorial. But it’s when you run that app under the heat of real everyday sales quotas, van dispatch deadlines, and freezing cold-room audits that you learn what true software reliability requires.

Tags:#Database State Machines#MongoDB Transactions#Inventory Systems#ACID Atomicity#FMCG Cold-Chain#Next.js 16#Software Reliability
← Back to Engineering Hub
Open to Contract & Full-Time Roles

Ready to build your next product?

Whether you need a high-scale SaaS platform, a bespoke e-commerce store, or a high-performance web app, I'm ready to collaborate.

© 2026 Ajay Thakkar. Built with Next.js, TypeScript & Tailwind CSS.