Architecting a Fault-Tolerant Payment Gateway Service
System DesignModel answerLast updated
Design an enterprise-grade payment gateway that guarantees at-most-once execution, handles ambiguous network timeouts, and maintains an auditable, immutable ledger.
Architecting a Fault-Tolerant Payment Gateway Service
Design a backend payment processing infrastructure for a high-volume merchant platform. Your system receives payment requests from merchant applications, coordinates transaction execution with downstream third-party payment service providers (PSPs), handles asynchronous status webhooks, and provides exact financial status visibility.
The primary engineering goal is absolute safety: the system must never double-charge a user, must remain consistent despite arbitrary network drops or crashes, and must maintain an immutable audit trail of every state transition.
Core Architecture Requirements
- API & Data Layer: Define key API contracts, idempotency handling, exact money representations, and a data model capable of tracking state history.
- Execution & Failure Handling: Detail how requests interact with external PSPs under failure scenarios (e.g., connection drops mid-request). Address out-of-order callbacks and asynchronous status webhooks.
- Data Integrity & Reconciliation: Explain the out-of-band mechanisms used to resolve ambiguous payment states and verify platform balances against external PSP records.
- Operational Controls & Resilience: Outline partitioning strategy, rate limiting/circuit breaking, and testing strategies for distributed invariants.
Key Considerations
- Network calls to PSPs are inherently unreliable and non-atomic. A timeout does not mean the transaction was rejected.
- Clients will retry aggressively on failure.
- Webhooks from third parties may arrive out of order, be duplicated, or fail entirely.
Hints
Hint 1
Think carefully about how to represent monetary amounts to prevent floating-point inaccuracies.
Hint 2
Distinguish between payment intent, client idempotency keys, and downstream PSP idempotency keys.
Hint 3
What pattern prevents dual-write issues between your database and your messaging queue?
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
High-Level Architecture Overview
A resilient payment processing system must treat every step of the payment lifecycle as potentially failing. Below is the end-to-end component flow:
┌─────────────────┐
│ Merchant Client │
└────────┬────────┘
│ 1. POST /v1/payments (Idempotency-Key)
▼
┌───────────────────────┐
│ API Gateway & │
│ Authentication Layer │
└───────────┬───────────┘
│ 2. Route request
▼
┌───────────────────────┐ ┌─────────────────────────┐
│ Payment Engine (API) ├─────►│ Idempotency Store (Redis│
└───────────┬───────────┘ │ w/ persistent backup) │
│ 3. Write Intent & │ │
│ Outbox Event └─────────────────────────┘
▼
┌───────────────────────┐
│ Payment DB (Postgres) │
│ (Payments, Ledger, │
│ Outbox Tables) │
└───────────┬───────────┘
│ 4. Read Outbox
▼
┌───────────────────────┐ ┌─────────────────────────┐
│ Payment Orchestrator ├─────►│ External PSP Gateway │
│ / Worker Pool │ │ (Stripe / Adyen / etc)│
└───────────┬───────────┘ └────────────┬────────────┘
▲ │
│ 5. Asynchronous Webhooks │
└───────────────────────────────┘
(Signed Payloads)
1. API, Data Representation & State Machine
API Design
The gateway exposes RESTful APIs requiring client-provided idempotency keys in request headers.
Create Payment Request
POST /v1/payments
Headers: Idempotency-Key: ik_merchant_abc12345
{
"merchant_id": "mer_88921",
"amount": 4999,
"currency": "USD",
"payment_method": {
"type": "card",
"token": "tok_visa_4444"
},
"capture_method": "automatic"
}
Response (201 Created / 200 OK)
{
"payment_id": "pay_01HGBX56R",
"status": "PROCESSING",
"amount": 4999,
"currency": "USD",
"created_at": "2023-11-15T10:00:00Z"
}
Exact Money Representation
Floating-point numbers (float, double) must never be used for money due to binary IEEE-754 precision issues (e.g., 0.1 + 0.2 = 0.30000000000000004).
- Store amounts as integers in minor currency units (e.g., cents for USD/EUR:
$49.99$\rightarrow$4999). - For currencies without sub-units (e.g., JPY), minor unit standard multiplier is 1. For three-decimal currencies (e.g., BHD), multiply by 1000.
- Pair every amount strictly with an ISO 4217 3-letter currency code (
USD,EUR,GBP).
State Machine Design
A payment moves through strict, monotonic state transitions:
[ CREATED ] ──► [ PROCESSING ] ──┬──► [ SUCCEEDED ] ──► [ REFUNDED ]
│
├──► [ FAILED ]
│
└──► [ UNKNOWN_TIMEOUT ]
│
▼ (Reconciliation)
[ SUCCEEDED / FAILED ]
CREATED: Initial payment entity saved in database; intent established.PROCESSING: Authorization request sent to external PSP.UNKNOWN_TIMEOUT: PSP call timed out or failed with network error. State is unresolved.SUCCEEDED: PSP confirmed capture/authorization.FAILED: Hard rejection from PSP (e.g., insufficient funds, fraudulent card).REFUNDED: Post-success reversal.
Database Schema (Relational PostgreSQL)
-- Main Payments Table
CREATE TABLE payments (
id VARCHAR(64) PRIMARY KEY,
merchant_id VARCHAR(64) NOT NULL,
idempotency_key VARCHAR(128) NOT NULL,
amount BIGINT NOT NULL,
currency VARCHAR(3) NOT NULL,
status VARCHAR(32) NOT NULL,
psp_reference VARCHAR(128),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uk_merchant_idempotency UNIQUE (merchant_id, idempotency_key)
);
-- Append-Only Payment State Transition History (Audit Log)
CREATE TABLE payment_events (
id BIGSERIAL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL REFERENCES payments(id),
from_status VARCHAR(32),
to_status VARCHAR(32) NOT NULL,
reason TEXT,
payload JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
-- Transactional Outbox for Messages
CREATE TABLE payment_outbox (
id BIGSERIAL PRIMARY KEY,
payment_id VARCHAR(64) NOT NULL,
event_type VARCHAR(64) NOT NULL,
payload JSONB NOT NULL,
processed BOOLEAN DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
2. PSP Integration & Handling Ambiguity
Transactional Outbox Pattern
Directly sending HTTP calls to a PSP within the database transaction creates long locks and consistency risks if the database crashes after the PSP call succeeds.
- The API service writes the
CREATEDpayment record and an entry intopayment_outboxinside a single ACID database transaction. - A separate worker process polls the
payment_outbox(or tailing via CDC/Debezium) and executes the HTTP call to the PSP. - Upon receiving a response, the worker updates the payment status and writes a
payment_eventsrecord.
Idempotency Execution Flow
- Client to Gateway: The
(merchant_id, idempotency_key)tuple is cached in Redis with a status ofIN_FLIGHT. If duplicate requests arrive simultaneously, they block or receive a429 Conflict / Request in Progress. - Gateway to PSP: When sending a request to the external PSP, the worker generates a deterministic PSP idempotency key linked to our
payment_idand retry attempt (e.g.,ik_pay_01HGBX56R_att1).
Handling Timeouts & Ambiguity
If the connection to the PSP times out:
- Do NOT mark as FAILED. Mark the payment state as
UNKNOWN_TIMEOUT. - Schedule an exponential backoff query to the PSP’s
/v1/charges/{psp_reference}or charge lookup endpoint using the deterministic idempotency key. - The background worker polls until the status is definitively standard (
SUCCEEDEDorFAILED).
API Gateway Worker Payment DB PSP
│ │ │ │
│── POST /payments ───►│ │ │
│ │── Begin Tx ──────────►│ │
│ │ Insert Payment │ │
│ │ Insert Outbox │ │
│ │── Commit Tx ─────────►│ │
│◄── 201 Created ──────│ │ │
│ │ │ │
│ │── Read Outbox ───────►│ │
│ │ │
│ │── POST /charges (Idempotency Key) ───────────►│
│ │◄─── Network Timeout / 504 Gateway Error ──────│
│ │ │
│ │── Update Status: UNKNOWN_TIMEOUT ────────────►│
│ │ │
│ │── Polling Query (Retry w/ exponential backoff)│
│ │──────────────────────────────────────────────►│
│ │◄── 200 OK (Status: Charge Succeeded) ─────────│
│ │ │
│ │── Update Status: SUCCEEDED ──────────────────►│
Handling Asynchronous Webhooks & Out-of-Order Delivery
- Signature Verification: Every incoming webhook payload is validated against HMAC signatures using public keys or shared webhook secrets.
- Deduplication: Webhook event IDs are stored in Redis/DB with an expiration window. If an event ID has been processed, return
200 OKimmediately. - Monotonic State Enforcement: Check state ordering rules before applying updates. If a payment is already in
SUCCEEDED, ignore late-arrivingPROCESSINGor duplicateSUCCEEDEDwebhooks.
3. Reconciliation System
Webhooks can fail, network drops can obscure status updates, and third-party systems can have internal glitches. A daily/hourly Reconciliation Engine acts as the safety net for state correctness.
┌─────────────────────────────────┐ ┌─────────────────────────────────┐
│ Internal Database Records │ │ PSP Settlement File (CSV) │
└────────────────┬────────────────┘ └────────────────┬────────────────┘
│ │
│ 1. Fetch Terminal States │ 1. Download SFTP/API
▼ ▼
┌─────────────────────────────────────────────────────────┐
│ Reconciliation Engine │
└────────────────────────────┬────────────────────────────┘
│
┌──────────────────────────┼──────────────────────────┐
▼ ▼ ▼
┌─────────────┐ ┌─────────────┐ ┌─────────────┐
│ Matched Records │ Internal Missing │ External Missing
│ (Verified) │ │ (Discrepancy Log) │ (Discrepancy Log)
└─────────────┘ └─────────────┘ └─────────────┘
- Settlement File Ingestion: PSPs push daily settlement CSV/JSON reports containing settled transaction IDs, fee breakdowns, and net amounts.
- Matching Engine:
- Joins internal database payments with PSP settlement files using
psp_referenceandpayment_id. - Checks three conditions: Status Match, Amount Match, Fee Variance Check.
- Joins internal database payments with PSP settlement files using
- Discrepancy Handling:
- Internal Missing: Payment exists on PSP as charged, but internal DB shows
FAILEDorUNKNOWN_TIMEOUT. System auto-heals DB state toSUCCEEDEDand flags an alert for audit. - External Missing: Internal DB shows
SUCCEEDED, but missing from PSP settlement. Triggers immediate PagerDuty/incident ticket (potential loss of funds or delay in PSP settlement).
- Internal Missing: Payment exists on PSP as charged, but internal DB shows
4. Resilience, Operational Controls & Scale
Data Partitioning Strategy
- Database is partitioned by
merchant_idorpayment_idhash. - To guarantee sequential state execution for a specific payment, all workers handling a specific
payment_idacquire a distributed lock (e.g., Redis Redlock) or route messages usingpayment_idas the Kafka partition key.
Circuit Breaking & Rate Limiting
- PSP Rate Limits: Implement Token Bucket algorithm per outbound PSP connection. If a PSP responds with
429 Too Many Requests, circuit breakers open (e.g., via Resilience4j or Envoy) to prevent cascading worker thread exhaustion. - Failover Routing: If a primary PSP experiences elevated latency or error rates (>5% errors), the orchestrator dynamically reroutes new charges to a secondary PSP gateway.
Failure Invariants & Chaos Testing
To guarantee strict system correctness, continuous automated testing must assert the following invariants under simulated network partition (e.g., Chaos Mesh):
- No Double Charge Invariant: $\sum \text{Successful PSP Charges for Request } I \le 1$
- Ledger Balance Invariant: $\sum \text{Debits} - \sum \text{Credits} = 0$
- Monotonic State Invariant: A payment in a terminal state (
SUCCEEDED,FAILED,REFUNDED) can never transition back to an active state.
Key Trade-Offs Summary
| Decision | Chosen Approach | Trade-Off / Cost |
|---|---|---|
| Monetary Precision | Integer minor units (BIGINT) | Requires clear conversion rules per currency across APIs. |
| Consistency Model | Async execution via Transactional Outbox | Increases end-to-end latency slightly; API clients must poll or listen to webhooks for completion. |
| State Resolution | Strict UNKNOWN_TIMEOUT + Active Reconciliation | Temporary state ambiguity for end users until backoff polling or reconciliation completes. |
| Data Audit | Immutable, append-only payment_events table | Higher storage cost over time; requires automated database archiving strategy. |