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.

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:
[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 recordsWhen 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:
// 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 SKU | Packing Format | Missing Qty | Unit Litres | Total Volume Leaked |
|---|---|---|---|---|
| Almond Stick | 100ml Stick (Box of 12) | 1 Box | 1.20 L | 1.20 Litres |
| Berries & Cream | 100ml Stick (Box of 12) | 1 Box | 1.20 L | 1.20 Litres |
| Belgian Chocolate | 100ml Stick (Box of 12) | 1 Box | 1.20 L | 1.20 Litres |
| Premium Vanilla | 500ml Tub (Piece) | 12 Pieces | 0.50 L | 6.00 Litres |
| Cookies & Cream | 500ml Tub (Piece) | 12 Pieces | 0.50 L | 6.00 Litres |
| Double Chocolate | 500ml Tub (Piece) | 12 Pieces | 0.50 L | 6.00 Litres |
| Choco Brownie Delight | 500ml Tub (Piece) | 12 Pieces | 0.50 L | 6.00 Litres |
| Mango Sorbet | 500ml Tub (Piece) | 11 Pieces | 0.50 L | 5.50 Litres |
| Simply Strawberry | 500ml Tub (Piece) | 3 Pieces | 0.50 L | 1.50 Litres |
| Premium Vanilla | 1000ml Tub (Piece) | 2 Pieces | 1.00 L | 2.00 Litres |
| Double Chocolate | 1000ml Tub (Piece) | 2 Pieces | 1.00 L | 2.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:
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
// 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
PENDINGstatus, the dialog warns: *"This will release reserved units back to general availability."* - If the order is in
DISPATCHEDstatus, the dialog highlights in amber:
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: markstatus: '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.