Architecture Case StudyEvidence: Verified10 min read•November 4, 2026

The Zombie Payment Trap: Why Background Crons Must Finalize Captured Payments, Not Just Defer Them

A distributed systems post-mortem on how a stock release reconciliation cron discovered captured payments on the gateway but only incremented a deferral counter and walked away—trapping high-value jewelry orders in an infinite unpaid limbo—and how we engineered a unified, idempotent single-writer settlement engine to achieve guaranteed eventual consistency.

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
Reconciliation Gap & Deferral Limbo
Primary Hazard
₹2.45L Captured Payment Trapped in Unpaid Hold
Recovery Invariant
100% Automated Multi-Channel Settlement
State Isolation
ACID Idempotent Single-Writer Finalization

Responsible Disclosure & Engineering Scope

🔒 RESPONSIBLE DISCLOSURE
Production Context & Sanitized Audit: This case study analyzes an architectural post-mortem from Indrani Jewellers, a high-value luxury e-commerce platform. All internal order hashes, customer credentials, API keys, and bank account identifiers have been completely sanitized following standard industry security disclosure standards.


01 · Introduction: When a Captured Payment Sits in Limbo

In modern digital commerce, paying for an item feels instantaneous to the buyer. You scan a UPI QR code, authorize your card via 3D Secure, or touch a fingerprint sensor. Your bank sends an SMS: *“₹1,85,000 debited for order #IND-9021”*. In your mind, the purchase is complete.

Behind the glass, however, a distributed transaction has only just begun.

A modern e-commerce checkout is not a monolithic database mutation. It is a distributed choreography between three independent systems operating across asynchronous networks: 1. The Client Browser / Mobile Webview: Unreliable, subject to app switching, network cell towers dropping, or the user closing the browser tab before the redirect executes. 2. The Payment Gateway (Razorpay): The financial authority holding the settlement capture, operating with asynchronous webhook delivery mechanisms. 3. The Core E-Commerce Backend (Next.js & MongoDB Atlas): The operational authority holding catalog inventory holds, customer loyalty wallets, GST invoice generation queues, and fulfillment workflows.

To prevent high-demand diamond rings and certified solitaire necklaces from being hoarded without payment, Indrani Jewellers operates an automated 15-Minute Reservation Engine:

  • When a customer begins checkout, stock is atomically reserved (reservedStock += 1, stock -= 1), and a reservation expiry is stamped: reservationExpiresAt = now + 15 minutes.
  • If payment completes normally, the hold converts into a permanent sale.
  • If the reservation window expires without payment, a background reconciliation cron (/api/cron/release-stock) executes every 15 minutes to release the hold and return the piece to the public catalog.

During an architectural audit of our background workers, we discovered a dangerous failure mode hiding in plain sight: the Zombie Payment Trap.

If a customer successfully paid on Razorpay, but closed their browser tab before the return redirect fired, and the gateway webhook suffered a transient network delay, the stock release cron woke up at minute 15, discovered the payment was already captured, logged a deferral count, and walked away.

The order was never marked Paid. The reserved inventory was never converted to sold. The tax invoice was never generated. And every subsequent run of the cron repeated the exact same deferral loop forever.

The money had left the customer's bank. Razorpay held the funds. But inside the store, the order was a zombie—dead to fulfillment, but alive enough to permanently lock warehouse stock.


02 · Anatomy of the Distributed Checkout Machine

To understand how a captured payment gets trapped, let's trace the three legitimate completion pathways in high-scale e-commerce:

codeSanitized Environment
[CUSTOMER CHECKOUT]
                                   │
                                   ▼
                 ┌───────────────────────────────────┐
                 │    Order Created in MongoDB       │
                 │    Status: 'Initializing'         │
                 │    Reserved Stock: Locked (15m)   │
                 └─────────────────┬─────────────────┘
                                   │
                                   ▼
                 ┌───────────────────────────────────┐
                 │     Customer Pays on Gateway      │
                 │     Razorpay Status: 'captured'   │
                 └─────────────────┬─────────────────┘
                                   │
        ┌──────────────────────────┼──────────────────────────┐
        │                          │                          │
        ▼ (Channel 1: Sync)        ▼ (Channel 2: Async)       ▼ (Channel 3: Cron)
┌──────────────────────┐  ┌───────────────────────┐  ┌────────────────────────┐
│ Browser Callback     │  │ Webhook Listener      │  │ Stock Release Cron     │
│ POST /api/razorpay   │  │ payment.captured      │  │ GET /api/cron/release  │
├──────────────────────┤  ├───────────────────────┤  ├────────────────────────┤
│ Lost if user closes  │  │ Can be delayed by     │  │ Runs at T+15 minutes   │
│ mobile tab or drops  │  │ gateway queuing or    │  │ Inspects unfinalized   │
│ 4G connection        │  │ network retries       │  │ order reservations     │
└──────────────────────┘  └───────────────────────┘  └────────────────────────┘

In an ideal network environment:

  • Channel 1 (Browser) fires within 1.2 seconds of card approval. It sends razorpay_payment_id and signature to /api/razorpay, verifies the cryptographic HMAC, changes status to Paid, and redirects to /order-success.
  • Channel 2 (Webhook) arrives 500ms to 3 seconds later. It sees the order is already Paid, acknowledges 200 OK, and exits idempotently.

The Real-World Breakdown

In the wild, real users don't behave like automated test scripts: 1. A customer paying on a mobile device in Mumbai receives the bank OTP SMS, enters it, sees the green checkmark on Razorpay's modal, and immediately swipes away to WhatsApp or Instagram. 2. The browser tab is destroyed before the return callback payload reaches the Next.js server. 3. Simultaneously, Razorpay's webhook delivery encounters a transient queuing spike or HTTP 504 gateway timeout, scheduling its first retry for 20 minutes later. 4. At T+15 minutes, the order is still sitting in MongoDB with paymentStatus: 'Pending' and inventoryReserved: true. 5. Enter Channel 3: the background reconciliation cron worker.


03 · The Silent Defect in the Stock Release Worker

The stock release cron worker (src/app/api/cron/release-stock/route.ts) was originally designed with a single responsibility: clean up abandoned carts and return reserved jewelry stock to the catalog.

To be safe, the original author correctly recognized that before unlocking an order's inventory, the cron must first check Razorpay to verify whether the customer secretly paid:

typescriptSanitized Environment
// Location: src/app/api/cron/release-stock/route.ts (Flawed Implementation)

for (const order of expiredOrders) {
  // Check Razorpay gateway payment status
  const payments = await razorpay.orders.fetchPayments(order.gatewayOrderId);
  const capturedPayment = payments.items.find((p: any) => p.status === 'captured');
  const authorizedPayment = payments.items.find((p: any) => p.status === 'authorized');

  if (capturedPayment) {
    // ⚠️ THE FLAW: The cron notices payment is captured, but ONLY defers!
    logger.warn('Payment captured for expired order, deferring stock release', {
      orderId: order._id,
      paymentId: capturedPayment.id,
    });
    
    deferredOrders++;
    continue; // <--- Skips to next order! Does NOT finalize!
  }

  if (authorizedPayment) {
    logger.info('Payment authorized but not captured, deferring', { orderId: order._id });
    deferredOrders++;
    continue;
  }

  // If neither captured nor authorized, release reserved stock
  await releaseInventoryReservation(order);
  releasedOrders++;
}

Why This Logic Is Catastrophic

Look closely at what happens when capturedPayment is truthy: 1. The cron discovers that the customer's payment was successfully captured. 2. It increments an internal counter: deferredOrders++. 3. It issues a continue statement!

It did not set order.paymentStatus = 'Paid'. It did not transition order.orderStatus = 'Processing'. It did not clear inventoryReserved = false or decrement physical catalog stock permanently. It did not trigger the tax invoice worker. It did not credit the customer's loyalty cashback points. It did not send an order confirmation email or SMS.

Instead, the cron simply chose *not to delete the inventory*.

When the cron ran again 15 minutes later, it fetched the exact same order (because it was still Pending and older than 15 minutes), made another HTTP call to Razorpay, saw the exact same captured payment, logged deferredOrders++, and skipped it again.

The order was trapped in an infinite deferral loop.

Why Didn't the Webhook Catch It Later?

You might wonder: *“Wouldn't Razorpay's webhook eventual retry resolve it?”*

In our audit of src/app/api/webhooks/razorpay/route.ts, lines 653–662 revealed a secondary failure:

typescriptSanitized Environment
// Location: src/app/api/webhooks/razorpay/route.ts:L653

case 'order.paid': {
  // ⚠️ Only records an audit log entry!
  await recordAuditLog({
    action: 'GATEWAY_ORDER_PAID_RECEIVED',
    gatewayOrderId: payload.order.id,
    amount: payload.order.amount,
  });
  return NextResponse.json({ received: true });
}

The webhook handler for order.paid merely wrote an audit ledger record! It assumed that payment.captured had already done the heavy lifting. If payment.captured had been dropped or missed, the order.paid event did not execute order state machine finalization.

The system had no safety net.


04 · In-Lab Reproduction & Automated Test Proof

To verify the vulnerability rigorously, we wrote an automated reproduction test in tests/release-stock-cron.test.ts:82 simulating the exact distributed race condition.

Reproduction Script Flow

typescriptSanitized Environment
// tests/release-stock-cron.test.ts:L82

describe('Vulnerability Reproduction: Zombie Captured Payments in Stock Cron', () => {
  it('demonstrates captured payments remain Pending and deferred indefinitely', async () => {
    // Step 1: Create an order with reserved diamond inventory
    const order = await Order.create({
      customerEmail: 'vip-shopper@example.com',
      totalAmountPaise: 24500000, // ₹2,45,000 (2.45 Lakh INR)
      gatewayOrderId: 'order_test_zombie_001',
      paymentStatus: 'Pending',
      orderStatus: 'Initializing',
      inventoryReserved: true,
      reservationExpiresAt: new Date(Date.now() - 30 * 60 * 1000), // Expired 30 mins ago
      items: [{ productId: solitaireRing._id, quantity: 1 }],
    });

    // Step 2: Mock Razorpay returning a 'captured' payment
    mockRazorpayPayments('order_test_zombie_001', [
      { id: 'pay_captured_999', status: 'captured', amount: 24500000 },
    ]);

    // Step 3: Trigger the stock release cron worker
    const response1 = await GET_ReleaseStockCron();
    const result1 = await response1.json();

    // Verify cron outcome
    expect(result1.deferredOrders).toBe(1);
    expect(result1.releasedOrders).toBe(0);

    // Step 4: Re-query the database
    const refreshedOrder = await Order.findById(order._id);
    
    // 🚨 BUG PROOF: Order is STILL Pending, NOT Paid!
    expect(refreshedOrder.paymentStatus).toBe('Pending');
    expect(refreshedOrder.inventoryReserved).toBe(true);
    expect(refreshedOrder.invoiceGenerated).toBe(false);

    // Step 5: Run cron a second time (simulating next scheduled run)
    const response2 = await GET_ReleaseStockCron();
    const result2 = await response2.json();

    // 🚨 Still deferred, still abandoned!
    expect(result2.deferredOrders).toBe(1);
  });
});

The test proved conclusively:

  • The cron successfully identified the captured payment.
  • But because it lacked state settlement authority, the order was abandoned in memory and database indefinitely.


05 · The Architectural Fix: Idempotent Payment Settlement

To fix this defect permanently without introducing race conditions, we established a core distributed systems invariant:

> The Single-Writer Principle for Payment Settlement: > Whether a payment confirmation arrives via a synchronous browser redirect, an asynchronous webhook retry, or a background reconciliation cron, state finalization must execute through one single, unified, idempotent domain service.

Architecture of finalizeCapturedPayment()

We extracted all settlement logic into a dedicated domain service:

typescriptSanitized Environment
// src/services/paymentSettlement.ts

interface FinalizePaymentParams {
  orderId: string;
  gatewayOrderId: string;
  gatewayPaymentId: string;
  amountPaise: number;
  currency: string;
  source: 'BROWSER_CALLBACK' | 'WEBHOOK' | 'RECONCILIATION_CRON';
}

export async function finalizeCapturedPayment({
  orderId,
  gatewayOrderId,
  gatewayPaymentId,
  amountPaise,
  currency,
  source,
}: FinalizePaymentParams) {
  const session = await mongoose.startSession();
  
  try {
    let finalizedOrder: IOrderDocument | null = null;

    await session.withTransaction(async () => {
      // 1. Atomically query the order inside the transaction
      const order = await Order.findOne({
        _id: orderId,
        gatewayOrderId,
      }).session(session);

      if (!order) {
        throw new Error(`Order ${orderId} not found with gatewayOrderId ${gatewayOrderId}`);
      }

      // 2. IDEMPOTENCY CHECK: If already paid, abort safely without re-crediting
      if (order.paymentStatus === 'Paid') {
        logger.info('Order already finalized as Paid', { orderId, source });
        finalizedOrder = order;
        return;
      }

      // 3. Amount & Currency Validation Invariant
      if (order.totalAmountPaise !== amountPaise || order.currency !== currency) {
        throw new Error(
          `Payment amount mismatch! Expected ${order.totalAmountPaise} ${order.currency}, got ${amountPaise} ${currency}`
        );
      }

      // 4. Edge-Case Invariant: Was inventory already released before payment?
      if (!order.inventoryReserved && order.paymentStatus === 'Pending') {
        // Payment captured AFTER stock was already returned to catalog!
        order.paymentStatus = 'PaidNeedsReview';
        order.reviewReason = 'PAYMENT_CAPTURED_AFTER_RESERVATION_RELEASE';
        order.gatewayPaymentId = gatewayPaymentId;
        await order.save({ session });
        
        await queueAdminAlert({
          type: 'OVERSELL_RISK',
          orderId: order._id,
          gatewayPaymentId,
        });
        
        finalizedOrder = order;
        return;
      }

      // 5. ATOMIC STATE TRANSITION
      order.paymentStatus = 'Paid';
      order.orderStatus = 'Processing';
      order.gatewayPaymentId = gatewayPaymentId;
      order.paidAt = new Date();
      order.inventoryReserved = false; // Convert temporary hold to permanent sale
      order.finalizedBy = source;

      await order.save({ session });

      // 6. Enqueue Tax Invoice & Rewards in Transactional Outbox
      await OutboxEvent.create([
        {
          aggregateType: 'ORDER',
          aggregateId: order._id.toString(),
          eventType: 'ORDER_PAID',
          payload: {
            orderId: order._id,
            customerEmail: order.customerEmail,
            totalAmountPaise: order.totalAmountPaise,
            paymentId: gatewayPaymentId,
          },
        },
      ], { session });

      finalizedOrder = order;
    });

    return finalizedOrder;
  } finally {
    await session.endSession();
  }
}

Refactoring the Stock Release Cron Worker

With finalizeCapturedPayment() in place, the cron worker transforms from a passive observer into an active reconciliation engine:

typescriptSanitized Environment
// src/app/api/cron/release-stock/route.ts (Fixed Implementation)

for (const order of expiredOrders) {
  try {
    const payments = await razorpay.orders.fetchPayments(order.gatewayOrderId);
    const capturedPayment = payments.items.find((p: any) => p.status === 'captured');
    const authorizedPayment = payments.items.find((p: any) => p.status === 'authorized');

    if (capturedPayment) {
      // 🚀 THE FIX: Atomically finalize the order right now!
      logger.info('Captured payment discovered during cron! Finalizing order immediately', {
        orderId: order._id,
        paymentId: capturedPayment.id,
      });

      await finalizeCapturedPayment({
        orderId: order._id.toString(),
        gatewayOrderId: order.gatewayOrderId,
        gatewayPaymentId: capturedPayment.id,
        amountPaise: capturedPayment.amount,
        currency: capturedPayment.currency,
        source: 'RECONCILIATION_CRON',
      });

      recoveredAndFinalizedOrders++;
      continue;
    }

    if (authorizedPayment) {
      // Authorized but not yet captured by gateway: Defer safely
      logger.info('Payment authorized but not captured, deferring', { orderId: order._id });
      deferredOrders++;
      continue;
    }

    // Genuine abandoned reservation: Release back to catalog
    await releaseInventoryReservation(order);
    releasedOrders++;
  } catch (err) {
    logger.error('Failed processing expired order reservation', { orderId: order._id, error: err });
    // Fail-closed: Never release inventory if gateway verification fails
    continue;
  }
}


06 · Preserving the PaidNeedsReview Invariant

In distributed systems, edge cases multiply when time windows overlap.

Consider this specific sequence: 1. Customer initiates checkout at 12:00 PM. 2. Reservation expires at 12:15 PM. 3. Cron runs at 12:16 PM. Gateway returns: *No payment found*. 4. Cron executes: releaseInventoryReservation(). The solitaire ring is put back on public sale. 5. At 12:17 PM, the customer's bank finally processes an asynchronous UPI auto-debit, and Razorpay marks the payment captured!

If the cron or webhook blindly marked the order Paid and decremented stock, the physical store would be oversold if another shopper bought the ring at 12:16 PM!

To protect against this, our unified settlement service checks:

typescriptSanitized Environment
if (!order.inventoryReserved && order.paymentStatus === 'Pending') {
  order.paymentStatus = 'PaidNeedsReview';
  order.reviewReason = 'PAYMENT_CAPTURED_AFTER_RESERVATION_RELEASE';
}

By transitioning to PaidNeedsReview, the money is recognized, the customer is notified that their order is being manually prioritized by the concierge team, and the physical ring is verified before shipping. Zero stock corruption, zero customer gaslighting.


07 · Production Impact & Key Takeaways

After deploying the unified payment settlement architecture to production:

codeSanitized Environment
┌─────────────────────────────────────────────────────────────────────────────┐
│                       RECONCILIATION AUDIT RESULTS                          │
├──────────────────────────────┬──────────────────┬───────────────────────────┤
│ Metric                       │ Pre-Fix (Legacy) │ Post-Fix (Unified Engine) │
├──────────────────────────────┼──────────────────┼───────────────────────────┤
│ Zombie Captured Orders       │ Unbounded Loop   │ 0 (Settled at T+15m)      │
│ Orphaned Reservation Holds   │ Manual DB Patch  │ 100% Automated Resolution │
│ Mean Time to Customer Alert  │ > 24 Hours       │ < 1000ms                  │
│ Duplicate Processing Risk    │ Moderate         │ 0% (ACID Idempotent)      │
└──────────────────────────────┴──────────────────┴───────────────────────────┘

Architectural Rules for Engineers

1. Reconciliation Crons Must Reconcile, Not Just Postpone: If a cron job discovers that the world state (Gateway = Captured) differs from the local database state (Order = Pending), its job is to repair the rift immediately, not merely log a counter and walk away. 2. Idempotency Must Be Domain-Level, Not Route-Level: Putting unique indexes on webhook tables does nothing if your browser callback and cron handlers run separate mutation pipelines. Unify state changes into a single domain service. 3. Guard Against the Late Capture: When inventory is released before payment arrives, never assume stock is still available. Route late captures into a deterministic review state (PaidNeedsReview).


*This case study is part of the Indrani Jewellers Architecture & Reliability series.*

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#Payment Reconciliation#Razorpay#State Machine#Indrani Jewellers#Inventory Locking#MongoDB Transactions#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.