Architecture Case StudyEvidence: Verified9 min read•November 2, 2026

The Fail-Open Trap: How Payment Gateway Timeouts and 100-Hop DB Transactions Oversold Diamond Inventory

An in-depth post-mortem on how a fail-open catch block and a 100-network-hop MongoDB transaction during gateway outages caused high-value diamond inventory reservations to be prematurely cancelled and oversold, and how we engineered fail-closed invariants and per-order micro-transactions to solve 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
Fail-Open State Transition & Monolithic Lock
Primary Hazard
Oversold ₹1.85L Solitaire Inventory
Batch Latency
Reduced from 14.8s to 320ms
Resiliency Standard
100% Fail-Closed Under Gateway Outage

Responsible Disclosure & Engineering Scope

🔒 RESPONSIBLE DISCLOSURE
Production Context & Sanitized Data: This case study analyzes an architectural post-mortem from Indrani Jewellers, a high-end luxury fine jewelry e-commerce platform. All customer identifiers, gateway secrets, and ledger transactions cited here have been sanitized according to standard responsible engineering disclosure practices.


01 · Introduction: The Phantom Inventory Crisis

In high-end luxury e-commerce—where a single diamond solitaire necklace or bespoke wedding band sells for ₹1,50,000 to ₹5,00,000+ ($2,000 - $6,000+)—inventory is strictly physical, unique, and strictly non-fungible. If two customers purchase the exact same certified diamond at the same time, the second customer cannot simply be shipped an identical substitute from a warehouse shelf.

To prevent stock hoarding while shoppers complete complex multi-step mobile UPI or credit card verifications, Indrani Jewellers uses an automated 15-Minute Temporary Reservation Engine:

1. When a shopper clicks *"Proceed to Payment"*, the system locks the diamond item and marks inventoryReserved: true with a TTL timestamp (reservationExpiresAt: +15 minutes). 2. If the customer completes payment, the hold converts into permanent ownership. 3. If the 15-minute window expires without payment, an automated scheduled reconciliation worker (GET /api/cron/release-stock) unlocks the reservation and restores the item to the public showcase.

✓ Verified: In-Lab Repro

During a festive peak traffic evening, our operations team was hit with a nightmare scenario: a rare 2.0-carat solitaire diamond ring was bought and paid for by Customer A, yet within 4 minutes, the exact same ring was purchased and authorized by Customer B.

Both customers received bank SMS debit confirmations. Both held valid order IDs. But the physical showcase held only one ring.

When we audited the background reconciliation worker, we uncovered not one, but two compounding architectural flaws: 1. The Fail-Open Exception Handler: A transient HTTP timeout from the Razorpay API during payment status checks caused the cron's catch block to swallow the network error and fall straight down into the stock release routine, stripping inventory holds from customers who had already paid. 2. The 100-Network-Hop MongoDB ACID Transaction: The cron worker opened a single monolithic database transaction wrapped around up to 100 sequential external HTTPS API calls, triggering MongoDB's 60-second transactionLifetimeLimitSeconds aborts and cascading write conflicts.


02 · Anatomy of the Reservation Lifecycle

To understand how the failure occurred, consider the distributed state machine that governs high-value checkout reservations:

codeSanitized Environment
[CUSTOMER CHECKOUT]
                │
                ▼
      ┌───────────────────┐
      │  Order Created    │
      │  Reserved: TRUE   │
      │  TTL: 15 Minutes  │
      └─────────┬─────────┘
                │
         ┌──────┴──────────────────────────────────────┐
         │                                             │
         ▼ (Path A: Success)                           ▼ (Path B: Inactivity)
┌─────────────────────────┐                 ┌─────────────────────────────────┐
│ Razorpay Payment Succeeded│                │ 15 Minutes Expire Unpaid        │
│ Order Status -> 'Paid'  │                 │ Cron Worker Checks Order Status │
│ Inventory -> Permanent  │                 └────────────────┬────────────────┘
└─────────────────────────┘                                  │
                                                             ▼
                                             ┌────────────────────────────────┐
                                             │ Check Gateway Payment Status   │
                                             │ GET /orders/{id}/payments      │
                                             └───────────────┬────────────────┘
                                                             │
                                        ┌────────────────────┴────────────────┐
                                        ▼ (Gateway Error / Timeout)           ▼ (Confirmed Unpaid)
                         ┌─────────────────────────────┐        ┌─────────────────────────────┐
                         │ 🚨 THE FAIL-OPEN BUG        │        │ Safe Release:               │
                         │ Error caught & ignored      │        │ Inventory Restored to Stock │
                         │ Release routine executes!   │        │ Order Status -> 'Expired'   │
                         └─────────────────────────────┘        └─────────────────────────────┘

The safety invariant of any temporary reservation system can be expressed mathematically:

$$\text{ReleaseStock}(\text{order}) \iff \text{PaymentStatus}(\text{order}) \neq \text{'Captured'} \land \text{GatewayReachable}(\text{order}) = \text{TRUE}$$

If $\text{GatewayReachable} = \text{FALSE}$, the system must never assume the customer did not pay. In distributed systems, network partitions and gateway timeouts represent an *unknown state*, never a negative state.


03 · Deep-Dive: The Twin Architectural Traps

Trap 1: The Fail-Open catch Block (src/app/api/cron/release-stock/route.ts:L69)

Before our audit and hardening, the background stock release cron executed the following logic when inspecting expired orders:

typescriptSanitized Environment
// ❌ VULNERABLE PRODUCTION PATTERN: Fail-Open Invariant Violation
for (const order of expiredOrders) {
  if (order.gatewayOrderId && /^order_[A-Za-z0-9]+$/.test(order.gatewayOrderId)) {
    try {
      const razorpay = new Razorpay({ key_id, key_secret });
      const payments = await razorpay.orders.fetchPayments(order.gatewayOrderId);
      
      const activePayment = payments?.items?.find(
        (p) => p.status === 'captured' || p.status === 'authorized'
      );
      
      if (activePayment) {
        console.log(`[CRON] Order ${order._id} has live payment. Preserving stock.`);
        continue; // Correctly preserved
      }
    } catch (rzpErr) {
      // 🚨 CRITICAL FLAW: Swallows the network error and DOES NOT continue!
      console.error(`[CRON] Gateway check failed for order ${order._id}:`, rzpErr);
    }
  }

  // 💥 DISASTER: Executes whether the gateway check succeeded or timed out!
  const released = await releaseOrderReservation({
    orderId: order._id,
    terminalStatus: 'Expired',
    reason: 'Reservation timeout (15 min unpaid)',
  });
}

Why This Failed in Production:

1. At T = 0min: Customer A initiated a checkout for a ₹1,85,000 diamond solitaire ring. 2. At T = 14min 30s: Customer A approved the UPI prompt on PhonePe. Razorpay captured the funds, but high network latency delayed the webhook delivery to the merchant server. 3. At T = 15min 01s: The scheduled cron fired. It identified Customer A's order as expired (reservationExpiresAt < new Date()). 4. The cron called razorpay.orders.fetchPayments(gatewayOrderId). Due to a transient upstream gateway glitch, the request timed out with a 504 Gateway Timeout. 5. The catch (rzpErr) block executed, logged the error, and fell straight through to releaseOrderReservation(). 6. The diamond solitaire ring's reserved flag was wiped to 0, making it immediately visible on the public website. 7. At T = 16min: Customer B purchased the ring and paid immediately. 8. At T = 16min 30s: Customer A's delayed webhook finally arrived and stamped Customer A's order as Paid.

Result: One physical diamond ring was simultaneously owned by two customers, directly caused by a 3-line missing continue statement.


Trap 2: The 100-Network-Hop MongoDB ACID Transaction

The second flaw was even more insidious because it looked like "good engineering" on the surface:

typescriptSanitized Environment
// ❌ ANTI-PATTERN: Wrapping 100 External Network Requests Inside a Database Transaction
const session = await mongoose.startSession();
session.startTransaction();

try {
  const expiredOrders = await OrderModel.find({ ... }).limit(100).session(session);

  for (const order of expiredOrders) {
    // 🚨 100 EXTERNAL HTTPS NETWORK REQUESTS INSIDE AN ACTIVE ACID TRANSACTION!
    const payments = await razorpay.orders.fetchPayments(order.gatewayOrderId);
    
    if (!hasActivePayment(payments)) {
      await releaseOrderReservation({ orderId: order._id, session });
    }
  }

  await session.commitTransaction();
} catch (error) {
  await session.abortTransaction();
}

The Violations:

1. Network I/O in ACID Transactions: Database transactions are designed for microsecond in-memory ledger consistency. External HTTP calls cross the public internet, subject to DNS lookups, TCP handshakes, TLS negotiation, and external rate limits. 2. MongoDB transactionLifetimeLimitSeconds: By default, MongoDB enforces a hard 60-second ceiling on any open multi-document transaction. If 100 orders each take 650ms to query Razorpay, the loop takes 65 seconds, causing MongoDB to violently abort the transaction with TransientTransactionError. 3. Lock Contention & Write Conflicts: Holding open write snapshots on the Order collection for over a minute blocked real-time customer checkouts and webhooks, producing cascades of error code 112 (WriteConflict).


04 · The Remediation: Engineering Fail-Closed Reliability

To permanently solve both vulnerabilities, we re-architected the stock release engine around two non-negotiable principles:

🔒 SECURITY NOTICE
Core Distributed Systems Invariants: 1. Fail-Closed by Default: If an external authority's status cannot be verified with certainty, preserve all customer holds and defer action. 2. Zero Network Calls in Database Transactions: Never perform HTTP/network I/O inside an active ACID database session.

The Fortified Implementation

typescriptSanitized Environment
// 🔒 SECURE PRODUCTION IMPLEMENTATION
// File: src/app/api/cron/release-stock/route.ts

const MAX_RELEASE_ATTEMPTS = 3;

// Helper: Detect transient database write conflicts eligible for retry
function isTransientDatabaseError(error: unknown) {
  const candidate = error as { errorLabels?: string[]; code?: number; message?: string };
  return Boolean(
    candidate?.errorLabels?.includes('TransientTransactionError')
    || candidate?.code === 112
    || /write conflict|temporarily unavailable/i.test(String(candidate?.message || ''))
  );
}

// Atomic per-order micro-transaction with exponential backoff
async function releaseExpiredOrder(orderId: mongoose.Types.ObjectId | string) {
  for (let attempt = 1; attempt <= MAX_RELEASE_ATTEMPTS; attempt++) {
    const session = await mongoose.startSession();
    session.startTransaction();
    try {
      const released = await releaseOrderReservation({
        orderId,
        terminalStatus: 'Expired',
        reason: 'Reservation timeout (15 min unpaid)',
        session,
      });
      await session.commitTransaction();
      return released;
    } catch (error) {
      if (session.inTransaction?.()) await session.abortTransaction();
      if (!isTransientDatabaseError(error) || attempt === MAX_RELEASE_ATTEMPTS) throw error;
      await new Promise((resolve) => setTimeout(resolve, 100 * attempt));
    } finally {
      session.endSession();
    }
  }
  return false;
}

export async function GET(req: Request) {
  // 1. Authenticate cron trigger
  const authHeader = req.headers.get('authorization');
  if (!process.env.CRON_SECRET || authHeader !== `Bearer ${process.env.CRON_SECRET}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  await connectToDatabase();

  const batchSize = Math.max(1, Math.min(Number(process.env.RELEASE_STOCK_BATCH_SIZE || 100), 250));

  // 2. Fetch candidate expired orders (LEAN READ, NO TRANSACTION OPEN)
  const expiredOrders = await OrderModel.find({
    paymentStatus: { $in: ['Initializing', 'Pending'] },
    reservationExpiresAt: { $lt: new Date() },
    inventoryReserved: true,
    stockReleased: { $ne: true },
  })
    .select('_id gatewayOrderId items')
    .sort({ reservationExpiresAt: 1 })
    .limit(batchSize)
    .lean();

  let releasedOrders = 0;
  let deferredOrders = 0;

  // 3. Process each order independently OUTSIDE any global transaction
  for (const order of expiredOrders) {
    const gatewayOrderId = String(order.gatewayOrderId || '');

    if (/^order_[A-Za-z0-9]+$/.test(gatewayOrderId)) {
      if (!razorpay) {
        deferredOrders++;
        console.error(`[CRON] Gateway credentials missing. Deferring order ${order._id}.`);
        continue; // 🔒 FAIL-CLOSED: Defer when credentials unavailable
      }

      try {
        // Network I/O occurs purely in memory, zero database locks held
        const payments = await razorpay.orders.fetchPayments(gatewayOrderId);
        const activePayment = payments?.items?.find(
          (p: { status: string }) => p.status === 'captured' || p.status === 'authorized'
        );

        if (activePayment) {
          deferredOrders++;
          console.log(`[CRON] Preserving order ${order._id}; gateway status is ${activePayment.status}.`);
          continue; // 🔒 Customer paid: NEVER release inventory
        }
      } catch (error) {
        // 🔒 FAIL-CLOSED GUARANTEE: If gateway blips, DEFER AND RETRY NEXT CYCLE
        deferredOrders++;
        console.error(`[CRON] Gateway check failed for order ${order._id}; release deferred.`, error);
        continue; // 🛡️ CRITICAL FIX: Abort release and preserve stock hold!
      }
    }

    // 4. Execute atomic micro-transaction ONLY for confirmed unpaid orders
    const released = await releaseExpiredOrder(order._id);
    if (released) releasedOrders++;
  }

  return NextResponse.json({
    success: true,
    releasedOrders,
    deferredOrders,
    totalEvaluated: expiredOrders.length,
  });
}


05 · Resiliency & Chaos Verification

To verify that the new implementation is immune to gateway failures and network jitter, we engineered a dedicated test harness simulating gateway latency and total API outage:

Test ScenarioGateway ConditionInjected FaultVulnerable Engine ResultHardened Engine Result
Normal Unpaid200 OK (0 Payments)NoneOrder Released ✅Order Released ✅
Captured Payment200 OK (Status: captured)NoneOrder Preserved ✅Order Preserved ✅
Gateway 504 Timeout504 Gateway Timeout100% Drops🚨 Oversold Stock🔒 Deferred (0 Releases)
Network ETIMEDOUTSocket Hang Up3000ms Latency🚨 Oversold Stock🔒 Deferred (0 Releases)
Rate Limited (429)429 Too Many RequestsHTTP 429🚨 Oversold Stock🔒 Deferred (0 Releases)
Batch Concurrency (100)Normal Network100 Orders🚨 DB Transaction Abort⚡ 320ms Clean Batch
✓ Verified: In-Lab Repro

Performance Metrics Comparison

  • Monolithic Transaction Batch Duration: ~14,800ms (frequent 60s timeout aborts under load).
  • Decoupled Micro-Transaction Batch Duration: ~320ms total database holding time.
  • Fail-Open Error Rate: Reduced from 100% of gateway exceptions to 0.00%.


06 · Key Architectural Lessons

1. Fail-Closed Is Non-Negotiable in Asset Systems

When your software manages physical inventory, tickets, real estate, or money, unknown equals preserved. Never allow a catch block to fall through into destructive or state-mutating actions. If you cannot reach the source of truth, abort and retry.

2. Network Calls Do Not Belong in Database Transactions

An ACID transaction should encompass only memory and disk operations under the database engine's direct control. Introducing third-party HTTP calls into a database transaction surrenders your system's stability to external networks.

3. Replace Monolithic Batch Transactions with Micro-Transactions

Wrapping an entire batch of 100 independent entities in one giant transaction creates an all-or-nothing vulnerability: a single transient write conflict on order #99 rolls back all 98 successfully processed orders. Decouple batch processing into independent, atomic micro-transactions per entity.

4. Background Workers Must Be Self-Healing

A reliable reconciliation cron is idempotent and patient. By deferring ambiguous orders to the subsequent cycle, transient network blips resolve themselves naturally without human intervention or broken inventory invariants.

Connected Production System

Indrani Jewells — Luxury E-Commerce

An elegant high-end jewelry storefront built with high-trust buying workflows, rich product zoom galleries, curated bridal collection showcases, and custom order consultation requests.

Tags:#Distributed Systems#MongoDB Transactions#Razorpay#Fail-Open Invariant#Inventory Locking#Indrani Jewellers#Next.js 16#Reliability Engineering
← 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.