Skip to main content
Fintech & Payment Gateways

Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen)

Staff / Principal

Architect a mission-critical payment processing platform featuring idempotent charge capture, distributed Saga transactions, immutable.

Production Scale: 100M Transactions/Day • $10 Billion Volume • Zero Double Charges

Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen): Request Topology

5 Stages · 4 Sizing Benchmarks

Request traversal order for Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen) (Fintech & Payment Gateways) under target workload 100M Transactions/Day • $10 Billion Volume • Zero Double Charges:

Stage 1

Card Tokenization Vault (Isolated HSM)

Stage 2

Idempotency Layer (Redis Cluster)

Stage 3

Payment Orchestrator & Saga State Machine

Stage 4

Immutable Double-Entry Ledger (PostgreSQL / CockroachDB)

Functional Requirements

  • •Process credit card charges, ACH transfers, and refunds with zero double billing
  • •Enforce immutable double-entry ledger where sum(debits) === sum(credits) at all times
  • •Send real-time webhook event notifications with guaranteed at-least-once delivery

Non-Functional Requirements

  • •Strict ACID transaction consistency across financial accounts
  • •PCI-DSS Level 1 compliance (Zero raw card numbers stored in application databases)
  • •99.999% availability with zero silent transaction drops

Capacity & Scale Estimation (Back-of-the-Envelope Math)

Open Live Calculator
Transaction Volume100 Million charges / day (~1,200 TPS, 10k peak)
Daily Monetary Volume$10 Billion processed daily
Ledger Storage Growth~500 GB / month of immutable append-only records
Webhook Dispatch300 Million webhook payloads / day

Estimate Custom QPS & Storage Growth Live

Calculate bandwidth ingress, 80/20 RAM cache sizing, and multi-year storage growth using our interactive developer utility.

Launch Calculator →

System Topology & Core Architectural Components

[Merchant API Request (Idempotency Key)]
                    |
                    v
      [Idempotency & Rate Limit Filter]
                    |
                    v
    [Payment Orchestrator & State Machine]
                    |
       +------------+------------+
       |                         |
       v                         v
[External Payment Rails]   [Double-Entry Immutable Ledger]
(Stripe / Adyen / FedNow)  (PostgreSQL Strict Serializability / Raft)
                                 |
                                 v
                     [Two-Phase Commit (2PC) Engine]
                     (Accounts: Asset, Liability, Equity)

1Card Tokenization Vault (Isolated HSM)

Hardware Security Module (HSM) encrypting PANs with AES-256-GCM, returning non-sensitive surrogate tokens to the core app.

2Idempotency Layer (Redis Cluster)

Stores `Idempotency-Key` hash with lock state; duplicate client requests within 24h return cached responses immediately.

3Payment Orchestrator & Saga State Machine

Coordinates multi-step checkout workflow (Authorize -> Tokenize -> Acquire -> Settle -> Notify) with compensating transactions.

4Immutable Double-Entry Ledger (PostgreSQL / CockroachDB)

Append-only relational ledger enforcing zero row updates; every monetary transfer creates equal debits and credits.

5Webhook Retry Dispatcher (Kafka + Dead Letter Queue)

Dispatches HTTPS webhooks to merchant endpoints with exponential backoff retries over 72 hours.

Architectural Trade-Off Analysis & CAP Constraints

Trade-Off Decision Matrix

Engineering a resilient architecture for Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen) at a scale of 100M Transactions/Day • $10 Billion Volume • Zero Double Charges requires deliberate trade-offs across data consistency, replication latency, network partition tolerance, and storage economics:

DimensionSelected StrategyAlternative EvaluatedTrade-Off Rationale & Latency Impact
CAP Theorem PostureCP (Strict Consistency & Serializability over Availability)AP (Eventual Consistency with Asynchronous Reconciliation)Ledgers cannot tolerate duplicate spends, ghost balances, or split-brain ledger states under any circumstances. If consensus fails, writes reject.
Ledger Accounting ArchitectureImmutable Double-Entry Bookkeeping (Debits Equal Credits Must Balance to Zero)Single-Balance Mutable Row Updates (UPDATE balance = balance - X)Double-entry creates a tamper-evident audit trail with immutable balance records, satisfying financial banking audits and GAAP regulations.
Concurrency & Race Condition ControlPostgreSQL Row-Level Advisory Locks + Optimistic Version ColumnsGlobal Distributed Mutex across Distributed RedisDatabase advisory locks remain bound to the active database transaction boundary, eliminating lock loss during network partitions.
Idempotency Protection LayerStrict Idempotency Key Table with SHA-256 Payload Hash MatchingSimple Cache-Aside Key Check with 60-Second TTLGuarantees that network retries never charge a cardholder twice, even if retries arrive hours later with identical cryptographic keys.

Fault Tolerance, High Availability & Failure Mode Analysis

Operating at 100M Transactions/Day • $10 Billion Volume • Zero Double Charges demands proactive defenses against cascading outages. The blueprint specifies four critical failure modes and remediation protocols tailored to Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen):

1. Timeout from External Bank Rail During Fund Capture

Blast Radius: Payment status is indeterminate (bank may or may not have charged customer).

Remediation Protocol: Orchestrator places transaction into PENDING_CAPTURE and triggers automated idempotent status reconciler polling bank rail.

2. Database Master Failover Mid-Two-Phase Commit (2PC)

Blast Radius: Transaction state left in prepared state across ledger shards.

Remediation Protocol: Transaction manager queries active participants on recovery; transactions with all participants prepared commit, otherwise abort.

3. Concurrent Double-Spend Request on Same Account

Blast Radius: Simultaneous withdrawals attempting to breach available balance.

Remediation Protocol: Account balance queries acquire `SELECT id FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE;` locks in sorted account order, eliminating deadlocks while balances are derived from append-only journal rows.

4. Idempotency Store Redis Partition Failure

Blast Radius: Inability to verify if request was previously processed.

Remediation Protocol: System fails safe to durable PostgreSQL idempotency table; never executes unverified payment operations.

Production Algorithm Implementation: Strict Double-Entry Balanced Ledger Transaction (PostgreSQL Isolation)

typescript

High-scale distributed systems rely on atomic synchronization primitives to enforce SLA boundaries. Below is the production implementation for Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen):

import { PoolClient } from 'pg';

export interface LedgerEntry {
  accountId: string;
  amountCents: number; // Positive for Credit, Negative for Debit
}

export async function recordDoubleEntry(
  client: PoolClient,
  txId: string,
  entries: LedgerEntry[]
): Promise<void> {
  // Financial invariant: Total debits must equal total credits (sum must balance to 0)
  const netBalance = entries.reduce((acc, curr) => acc + curr.amountCents, 0);
  if (netBalance !== 0) {
    throw new Error(`Double-entry imbalance detected: Net sum ${netBalance} != 0`);
  }

  await client.query('BEGIN;');
  await client.query('SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;');

  try {
    // Acquire row-level locks in lexicographically sorted order to eliminate deadlocks
    const sortedAccountIds = Array.from(new Set(entries.map(e => e.accountId))).sort();
    await client.query(
      'SELECT id FROM accounts WHERE id = ANY($1) ORDER BY id FOR UPDATE;',
      [sortedAccountIds]
    );

    // Verify sufficient funds derived directly from append-only journal (no mutable balance column)
    for (const entry of entries) {
      if (entry.amountCents < 0) {
        const res = await client.query(
          'SELECT COALESCE(SUM(amount_cents), 0) AS balance FROM ledger_entries WHERE account_id = $1;',
          [entry.accountId]
        );
        const currentBalance = parseInt(res.rows[0].balance, 10);
        if (currentBalance + entry.amountCents < 0) {
          throw new Error(`Insufficient funds for account ${entry.accountId}: Current balance is ${currentBalance} cents`);
        }
      }
    }

    // Append immutable journal rows (sum of debits and credits equals 0)
    for (const entry of entries) {
      await client.query(
        `INSERT INTO ledger_entries (transaction_id, account_id, amount_cents, created_at)
         VALUES ($1, $2, $3, NOW());`,
        [txId, entry.accountId, entry.amountCents]
      );
    }

    await client.query('COMMIT;');
  } catch (error) {
    await client.query('ROLLBACK;');
    throw error;
  }
}

Design Distributed Payment Gateway & Immutable Ledger (Stripe / Adyen): Design Scope & Constraints Summary

This staff / principal blueprint balances 3 core functional workflows against 3 availability and latency constraints tailored for 100M Transactions/Day • $10 Billion Volume • Zero Double Charges. Review the FAQ trade-offs below to compare partitioning keys, replication topology, and failure isolation specific to Fintech & Payment Gateways.

Architectural FAQs & Interview Deep Dives

1How does an immutable double-entry ledger guarantee balanced books and detect silent accounting drift?

Database permissions revoke `UPDATE` and `DELETE` on ledger journal tables entirely. Every charge, refund, or fee inserts paired debit and credit rows summing to zero inside a single Serializable/Snapshot ACID transaction in PostgreSQL/CockroachDB, while automated T+1 reconciliation jobs cross-check ledger totals against card-network settlement files.

2Why isolate card tokenization inside an HSM vault separate from the payment orchestrator?

Encrypting Primary Account Numbers (PANs) with AES-256-GCM inside a dedicated Hardware Security Module enclave and returning non-sensitive surrogate tokens keeps raw card data out of application memory, Kafka queues, and analytics logs—shrinking PCI-DSS Level 1 compliance boundaries dramatically.

3How does the Saga state machine recover safely when an external card acquirer times out mid-capture?

Each Saga step checkpoints an explicit transition (`INITIATED`, `AUTH_PENDING`, `UNKNOWN_OUTCOME`, `CAPTURED`) before and after external network calls. On an ambiguous gateway timeout, the orchestrator avoids blind retries or immediate refunds, enqueuing an asynchronous reconciliation poll using the acquirer's correlation ID to resolve true settlement state.

4Why back the Redis `Idempotency-Key` cache with a persistent unique constraint in the transactional database?

Redis catches rapid client double-clicks in under a millisecond, but relying on volatile memory alone risks duplicate charges if a cache shard fails or evicts a key mid-flight. Enforcing a durable `UNIQUE (merchant_id, idempotency_key)` database lock alongside the Saga state record guarantees zero double billing across retries.