Software Crafting

Preventing Checkout Downtime: Architecting a High-Availability Multi-Gateway Payment Router with Node.js, Stripe, and Razorpay

BBadal SinghPayments and Billing12 min read05 Apr 2026Updated 2026-11-07
Teal and amber light streams flowing across a dark grid between small glass cube nodes, with scattered glowing digits and letters

TL;DR: Prevent checkout downtime by building a multi-gateway payment router in Node.js that falls back from one gateway to the other when the primary has an infrastructure failure. By implementing the Adapter Pattern behind an idempotent PaymentProvider TypeScript interface, you decouple checkout from specific SDKs, normalize payloads across providers, and make retries safe.

Key Takeaways

  • Implement the Adapter Pattern to decouple your core checkout logic from tightly coupled Stripe or Razorpay SDKs.
  • Create a generic PaymentProvider TypeScript interface to normalize transaction inputs and standardize gateway responses.
  • Enforce all monetary values in their lowest denominations (e.g., cents for USD, paise for INR) within the abstraction layer to prevent conversion bugs during a fallback event.
  • Require an idempotencyKey in your PaymentIntentRequest contract to safely handle transaction retries and prevent duplicate charges across gateways.
  • Classify provider errors inside each adapter (for Stripe, StripeAPIError, StripeConnectionError and StripeRateLimitError are infrastructure failures; StripeCardError is not) and expose a retryable flag, so the router never falls back on a declined card.
  • Verify webhook signatures with each provider's helper and the raw request body before fulfilling any order.

Your marketing team has driven heavy traffic to a sale campaign. Users are adding items to their carts, reaching the checkout page, and then your payment gateway starts returning 5xx errors.

Every minute of failed checkout costs orders, raises support tickets, and erodes user trust. Relying entirely on a single payment provider like Stripe or Razorpay makes that provider a single point of failure (SPOF) for revenue. Both run highly available platforms, but API degradation, regional network issues, and delayed webhooks still happen in distributed systems.

A Payment Router reduces that risk. By building an idempotent abstraction layer in Node.js, you can route transactions based on geography or availability, and fall back to a secondary gateway when the primary has an infrastructure failure.

Let's break down how to design a multi-gateway architecture using Node.js, Stripe, and Razorpay that keeps checkout available through a single-provider outage. It cannot protect you from everything: if both providers or your own backend are down, checkout is still down.

The Hidden Cost of Tightly Coupled Payment Logic

Most early-stage applications tightly couple their business logic directly to a specific provider's SDK. You install the Stripe package, import it directly into your controllers, and map your database columns to Stripe's exact payload definitions.

The problem arises when an outage occurs. A standard tightly coupled implementation will crash your entire checkout pipeline when it encounters a gateway timeout like this:

{
  "error": {
    "message": "An unknown error occurred",
    "type": "api_error"
  }
}

Stripe returns this shape with a 5xx status for problems on its side, and the Node SDK surfaces it as a StripeAPIError. Network failures surface as StripeConnectionError without any response body at all.

When this happens, ripping out the SDK and hardcoding a replacement mid-incident is not realistic. A multi-gateway setup can look like premature optimization for a small store, so weigh the build and maintenance cost (two integrations, two reconciliation flows, two sets of fees) against what an hour of failed checkout costs you at peak.

To survive gateway degradation, we must decouple our application from specific providers by introducing a standardized interface.

Architecting an Idempotent Abstraction Layer

The foundation of a multi-gateway system is the Adapter Pattern. Instead of your checkout service talking directly to Stripe or Razorpay, it communicates with a generic PaymentProvider interface.

This abstraction standardizes the input (amount, currency, customer details) and normalizes the output (gateway transaction IDs, status, error codes).

Production Note: Both Stripe and Razorpay accept monetary values in their smallest currency units (cents for USD, paise for INR). Our abstraction layer enforces this standard across the board to prevent conversion bugs during a fallback event.

Here is how we define the core contract in TypeScript:

// types/payment.ts

export type Currency = 'USD' | 'INR' | 'EUR' | 'GBP';

export interface PaymentIntentRequest {
  amount: number; // Lowest denomination (cents/paise)
  currency: Currency;
  customerId?: string;
  orderId: string;
  metadata?: Record<string, string>;
  idempotencyKey: string;
}

export interface NormalizedPaymentResponse {
  success: boolean;
  transactionId: string | null;
  provider: 'STRIPE' | 'RAZORPAY';
  clientSecret?: string; // Used by frontend to complete payment
  errorMessage?: string;
  requiresAction: boolean;
  retryable: boolean; // true only for infrastructure failures (5xx, network, rate limit)
}

export interface PaymentProvider {
  getProviderName(): string;
  createPaymentIntent(request: PaymentIntentRequest): Promise<NormalizedPaymentResponse>;
  // rawBody must be the unparsed request body exactly as received
  verifyWebhookSignature(rawBody: Buffer, signature: string): boolean;
}

By coding against the PaymentProvider interface, your core e-commerce logic never knows or cares who is processing the payment.

Implementing the Stripe and Razorpay Adapters

Next, we implement concrete adapters for our gateways. Each adapter catches provider-specific errors and maps them to the normalized response, including whether the failure is safe to retry elsewhere. If you would rather have this layer built and reviewed by a team that integrates gateways regularly, see our API and payment gateway integration services.

First, let's implement the StripeAdapter:

// adapters/StripeAdapter.ts
import Stripe from 'stripe';
import { PaymentProvider, PaymentIntentRequest, NormalizedPaymentResponse } from '../types/payment';

const RETRYABLE_STRIPE_ERRORS = new Set([
  'StripeAPIError',
  'StripeConnectionError',
  'StripeRateLimitError',
]);

export class StripeAdapter implements PaymentProvider {
  private stripe: Stripe;

  constructor(
    apiKey: string,
    private webhookSecret: string,
  ) {
    // Omitting apiVersion uses the version pinned by the installed SDK release.
    // maxNetworkRetries lets the SDK retry safe failures with the same idempotency key.
    this.stripe = new Stripe(apiKey, { maxNetworkRetries: 2, timeout: 10_000 });
  }

  getProviderName(): string {
    return 'STRIPE';
  }

  async createPaymentIntent(req: PaymentIntentRequest): Promise<NormalizedPaymentResponse> {
    try {
      const intent = await this.stripe.paymentIntents.create(
        {
          amount: req.amount,
          currency: req.currency.toLowerCase(),
          metadata: { ...req.metadata, orderId: req.orderId },
        },
        {
          idempotencyKey: req.idempotencyKey,
        },
      );

      return {
        success: true,
        transactionId: intent.id,
        provider: 'STRIPE',
        clientSecret: intent.client_secret || undefined,
        requiresAction: intent.status === 'requires_action',
        retryable: false,
      };
    } catch (error: any) {
      // Declines and invalid requests are not retryable on another gateway
      return {
        success: false,
        transactionId: null,
        provider: 'STRIPE',
        requiresAction: false,
        retryable: RETRYABLE_STRIPE_ERRORS.has(error?.type),
        errorMessage: error?.message,
      };
    }
  }

  verifyWebhookSignature(rawBody: Buffer, signature: string): boolean {
    try {
      this.stripe.webhooks.constructEvent(rawBody, signature, this.webhookSecret);
      return true;
    } catch {
      return false;
    }
  }
}

Now, we build the equivalent RazorpayAdapter. Notice how we normalize Razorpay's order_id into our universal transactionId format so the frontend and database handle it identically.

// adapters/RazorpayAdapter.ts
import Razorpay from 'razorpay';
import { validateWebhookSignature } from 'razorpay/dist/utils/razorpay-utils';
import { PaymentProvider, PaymentIntentRequest, NormalizedPaymentResponse } from '../types/payment';

export class RazorpayAdapter implements PaymentProvider {
  private razorpay: Razorpay;

  constructor(
    keyId: string,
    keySecret: string,
    private webhookSecret: string,
  ) {
    this.razorpay = new Razorpay({ key_id: keyId, key_secret: keySecret });
  }

  getProviderName(): string {
    return 'RAZORPAY';
  }

  async createPaymentIntent(req: PaymentIntentRequest): Promise<NormalizedPaymentResponse> {
    try {
      const order = await this.razorpay.orders.create({
        amount: req.amount, // Also expects smallest unit (paise)
        currency: req.currency,
        receipt: req.orderId,
        notes: req.metadata,
      });

      return {
        success: true,
        transactionId: order.id, // Razorpay order ID acts as our internal intent ID
        provider: 'RAZORPAY',
        clientSecret: order.id, // Razorpay uses order ID on the client side
        requiresAction: true,
        retryable: false,
      };
    } catch (error: any) {
      // Razorpay rejects with { statusCode, error: { code, description } }
      const status = error?.statusCode;
      return {
        success: false,
        transactionId: null,
        provider: 'RAZORPAY',
        requiresAction: false,
        retryable: status === undefined || status === 429 || status >= 500,
        errorMessage: error?.error?.description || 'Razorpay API Error',
      };
    }
  }

  verifyWebhookSignature(rawBody: Buffer, signature: string): boolean {
    return validateWebhookSignature(rawBody.toString('utf8'), signature, this.webhookSecret);
  }
}

Designing the Payment Router and Fallback Logic

With our adapters ready, we need the component that decides where each transaction goes: the PaymentRouter.

The router dictates the flow of transactions. A common approach is Geographical Routing paired with Active-Passive Fallback. For example, you might route all INR transactions to Razorpay natively, and all international transactions to Stripe. If Stripe fails with a server error, the router falls back to Razorpay, provided your Razorpay account has international payments enabled for the currencies you sell in.

Warning: Only trigger a fallback on 5xx server errors, rate limits, or network timeouts. Stripe reports declines as StripeCardError with HTTP 402; falling back on a decline usually just gets the card declined again by the second gateway, and can look like card testing to fraud systems. Reserve fallbacks for infrastructure failures.

// services/PaymentRouter.ts
import { PaymentProvider, PaymentIntentRequest, NormalizedPaymentResponse } from '../types/payment';

export class PaymentRouter {
  private primaryProvider: PaymentProvider;
  private fallbackProvider: PaymentProvider;

  constructor(primary: PaymentProvider, fallback: PaymentProvider) {
    this.primaryProvider = primary;
    this.fallbackProvider = fallback;
  }

  async processCheckout(req: PaymentIntentRequest): Promise<NormalizedPaymentResponse> {
    console.log(`[Router] Attempting primary gateway: ${this.primaryProvider.getProviderName()}`);

    let response = await this.primaryProvider.createPaymentIntent(req);

    // Success, or a non-retryable error such as a decline: return immediately.
    // The adapter decides retryability from typed errors, not message strings.
    if (response.success || !response.retryable) {
      return response;
    }

    console.warn(
      `[Router] Primary gateway failed: ${response.errorMessage}. Initiating fallback to ${this.fallbackProvider.getProviderName()}`,
    );

    // Use a distinct key per provider so each gateway's idempotency store stays consistent
    const fallbackReq = { ...req, idempotencyKey: `${req.idempotencyKey}-fallback` };

    response = await this.fallbackProvider.createPaymentIntent(fallbackReq);

    if (!response.success) {
      console.error(`[Router] Fatal: Both primary and fallback gateways failed.`);
      // Alert engineering team via PagerDuty/Slack here
    }

    return response;
  }
}

Creating a Stripe PaymentIntent or a Razorpay order does not move money; the customer still has to confirm the payment on the client. That makes fallback at this step low risk. A timed-out primary request may still have created an intent, so record both provider IDs against the order and let only the one the client actually confirms be fulfilled.

Ensuring Data Consistency with Idempotency Keys

When a user clicks "Pay" and the primary gateway hangs for 10 seconds before timing out, the user is likely to click the button again. In a multi-gateway setup, the primary may eventually complete request #1 while the fallback handles request #2, leaving two live payment attempts for one order, and a real risk of charging twice if both get confirmed.

To prevent this, implement idempotency keys in your own API, derived from the order (for example checkout:<orderId>), not generated per click. Your server then processes each order's checkout once and returns the stored result to repeats. A Redis SET NX lock with a TTL is a simple way to do that for a single Redis primary. Back it with a unique constraint on the order's payment record in your database, because a Redis lock alone can be lost on failover.

Here is how we implement a Redis-backed idempotency lock in Node.js:

// services/IdempotencyService.ts
import Redis from 'ioredis';

const redis = new Redis(process.env.REDIS_URL!);

export async function withIdempotency<T>(
  key: string,
  ttlSeconds: number,
  operation: () => Promise<T>,
): Promise<T> {
  // 'NX' ensures the key is only set if it does not already exist.
  // 'EX' sets an expiration time to prevent permanent deadlocks.
  const redisKey = `idempotency:${key}`;
  const acquired = await redis.set(redisKey, 'LOCKED', 'EX', ttlSeconds, 'NX');

  if (!acquired) {
    const existing = await redis.get(redisKey);
    if (existing && existing !== 'LOCKED') {
      return JSON.parse(existing) as T; // Replay the stored result
    }
    throw new Error('A payment request with this idempotency key is already in progress.');
  }

  try {
    const result = await operation();
    // Store the result so repeated requests replay it instead of running again
    await redis.set(redisKey, JSON.stringify(result), 'EX', 86400); // Keep for 24h
    return result;
  } catch (error) {
    // Release the lock so the client can retry
    await redis.del(redisKey);
    throw error;
  }
}

In your Express controller, you would wrap the PaymentRouter.processCheckout call within this withIdempotency function. Because the router already returns a normalized response instead of throwing, a failed attempt is stored too; if you want failed attempts to be retryable, throw from the operation when retryable is true so the lock is released.

Normalizing Webhooks in a Multi-Gateway Setup

Initiating the payment is only half the work. Your backend must listen for webhooks to fulfill the order reliably. Because Stripe and Razorpay send entirely different webhook payloads to different endpoints, we need a unified Webhook Controller that normalizes incoming data before updating our database.

By sending all gateway webhooks through one fulfillment function, your database logic stays isolated from provider-specific payloads. Both providers sign their webhooks with HMAC-SHA256 over the raw body, so mount these routes with express.raw({ type: 'application/json' }) and verify before parsing. Both also retry deliveries, so fulfillment must be idempotent.

// controllers/WebhookController.ts
import { Request, Response } from 'express';
import { stripeAdapter, razorpayAdapter } from '../payments'; // configured adapter instances

interface NormalizedWebhookEvent {
  orderId: string;
  transactionId: string;
  status: 'SUCCESS' | 'FAILED';
  provider: string;
}

export const handleStripeWebhook = async (req: Request, res: Response) => {
  const signature = req.headers['stripe-signature'] as string;

  // req.body is a Buffer because the route uses express.raw()
  if (!stripeAdapter.verifyWebhookSignature(req.body, signature)) {
    return res.status(400).send('Invalid signature');
  }
  const event = JSON.parse(req.body.toString('utf8'));

  if (event.type === 'payment_intent.succeeded') {
    const intent = event.data.object;

    const normalizedEvent: NormalizedWebhookEvent = {
      orderId: intent.metadata.orderId,
      transactionId: intent.id,
      status: 'SUCCESS',
      provider: 'STRIPE',
    };

    await processOrderFulfillment(normalizedEvent);
  }

  res.status(200).send('Webhook Received');
};

export const handleRazorpayWebhook = async (req: Request, res: Response) => {
  const signature = req.headers['x-razorpay-signature'] as string;

  if (!razorpayAdapter.verifyWebhookSignature(req.body, signature)) {
    return res.status(400).send('Invalid signature');
  }
  const event = JSON.parse(req.body.toString('utf8'));

  if (event.event === 'order.paid') {
    const order = event.payload.order.entity;

    const normalizedEvent: NormalizedWebhookEvent = {
      orderId: order.receipt, // We mapped orderId to receipt during creation
      transactionId: order.id,
      status: 'SUCCESS',
      provider: 'RAZORPAY',
    };

    await processOrderFulfillment(normalizedEvent);
  }

  res.status(200).send('Webhook Received');
};

async function processOrderFulfillment(event: NormalizedWebhookEvent) {
  console.log(`[Fulfillment] Fulfilling order ${event.orderId} processed by ${event.provider}`);
  // Idempotent update, so duplicate deliveries are harmless:
  // UPDATE orders SET status = 'PAID', tx_id = $1 WHERE id = $2 AND status <> 'PAID'
}

By decoupling your webhook handlers from your fulfillment logic, you can safely swap, remove, or add new gateways (like PayPal or Adyen) in the future simply by writing a new adapter and standardizing its webhook events.

Protecting Your Checkout Flow

Relying on a single payment provider is a risk you should take deliberately, not by default. The Adapter pattern, error-aware routing, signed webhooks and idempotent fulfillment let you survive a single gateway's outage without double charging customers. Before relying on it, test the fallback path regularly in sandbox mode (for example by pointing the primary adapter at an unreachable host), and reconcile both providers' settlement reports against your orders table.

Sources

Available for Work

Need help building this in production?

SoftwareCrafting is a full-stack dev agency - we ship fast, scalable React, Next.js, Node.js, React Native & Flutter apps for global clients.

Get a Free Consultation

Frequently Asked Questions

Why shouldn't I just use the Stripe or Razorpay SDK directly in my controllers?

Tightly coupling your business logic to a single provider's SDK makes that provider a single point of failure (SPOF). If that gateway has an outage or API degradation, checkout fails with 5xx errors. An abstraction layer lets you route to another provider without rewriting your core e-commerce logic.

What design pattern is best for building a multi-gateway payment router?

The Adapter Pattern is the most effective approach for architecting multi-gateway payment systems in Node.js. It allows your checkout service to communicate with a generic PaymentProvider interface rather than provider-specific SDKs. This standardizes inputs (like amount and currency) and normalizes outputs (like transaction IDs and status codes) across different gateways.

How do I handle currency formatting when falling back between Stripe and Razorpay?

Both Stripe and Razorpay require monetary values to be passed in their smallest currency units, such as cents for USD or paise for INR. Your abstraction layer must enforce this lowest-denomination standard globally to prevent conversion bugs during a fallback. Watch for zero-decimal currencies such as JPY, which Stripe expects in whole units.

Why is an idempotency key required in the payment abstraction interface?

An idempotency key prevents duplicate charges if a network request times out and your system automatically retries the payment creation. Each provider uses it to return the original result for a repeated request instead of creating a second one. It does not deduplicate across providers, which is why your own API also needs an order-level idempotency check. It is a critical safeguard for maintaining transactional integrity in distributed, high-availability systems.

Is building a custom payment routing system worth the upfront development cost?

It depends on volume. Compare the build and ongoing cost (a second integration, reconciliation, and fees) with the revenue an hour of checkout downtime would cost at your peak. High-volume stores and businesses with event-driven traffic spikes usually justify it; small stores often do not.

How does the payment abstraction layer handle different provider error codes?

The concrete adapters (such as StripeAdapter) catch provider-specific errors and map them to a standardized NormalizedPaymentResponse. This means your core e-commerce logic only evaluates a standard success boolean, a retryable flag and a generic errorMessage. As a result, your application doesn't need to parse unique, deeply nested gateway error structures like Stripe's api_error object.

About the author

Badal Singh

Co-founder of SoftwareCrafting

Badal Singh is the Co-founder of SoftwareCrafting in Delhi and writes technical guides about web and mobile development, backend security, cloud infrastructure, DevOps, and developer tooling.

Writes about Next.js, React, Node.js, PostgreSQL, React Native, Flutter.

View author profile

Last updated: 2026-11-07