System Design 17: Design Payment Gateway (Stripe, PayPal, Razorpay)
Designing a payment gateway is one of the most complex, domain-centric challenges in system design interviews. A payment gateway acts as the secure orchestration engine that captures user payment details, tokenizes them, and safely communicates with downstream financial networks to process transactions.
1. Why Do We Need a Payment Gateway? (Problem Statement & Status Quo)
Online merchants (e-commerce platforms like Amazon, Flipkart, or small SaaS websites) cannot directly integrate with every single bank or credit card network globally. Doing so would require handling immense security standards, managing thousands of varying bank APIs, and navigating complex regulatory compliance.
- The Complexity of Payments: Moving money involves high risk, strict security regulations (PCI-DSS), and massive scale (thousands of transactions per second).
- The Decoupling Need: Merchants need a unified, plug-and-play abstraction layer that accepts diverse payment methods, manages checkout sessions, and reliably talks to financial institutions.
- The Core Challenge: Guaranteeing absolute consistency and zero data loss. In distributed systems, if a network partition occurs, a balance must be struck: money cannot vanish or duplicate.
2. Core Mental Model & Definitions: Gateway vs. Processor
Real-Life Analogy
Think of a Payment Gateway like an airport check-in desk and security checkpoint, whereas a Payment Processor is the air traffic control and the airplane managing the actual physical transit.
Note: In this chapter, our primary system design scope focuses entirely on building the Payment Gateway (orchestration, tokenization, session management, and PCI compliance), treating the Payment Processor as an external downstream dependency.
3. Functional Requirements
To establish clear interview boundaries, we define four core functional requirements while explicitly scoping out edge cases.
- 1. Create Payment Intent: The client (merchant) should be able to initiate a payment intent request containing order metadata, amount, and currency.
- 2. Temporary Session Page: The payment gateway environment must generate a secure, temporary session page where the end-user can input their credit/debit card details.
- 3. Secure PCI-DSS Handling: The system must securely handle and tokenize sensitive card data in compliance with global security standards.
- 4. Transaction Status & Webhooks: Once a transaction completes or fails, the gateway must deliver status updates back to the client via callbacks or webhooks.
Out of Scope:
- Partial payments (split payments).
- Refunds and chargeback workflows.
4. Non-Functional Requirements & Scale Estimation
- Scale & TPS (Transactions Per Second): The system targets a high-throughput workload of 10,000 TPS.
- CAP Theorem Trade-Off: Consistency () is prioritized over Availability (). When dealing with financial ledgers and money transactions, stale data or double-charging is catastrophic. The system must never compromise on ledger accuracy.
- Low Latency: Payment authorization and tokenization logic within our gateway must execute in under 200 milliseconds. (Note: Downstream bank processing takes its own time, but our internal orchestration/tokenization must be lightning-fast).
- Security & Compliance: The entire system must be strictly PCI-DSS (Payment Card Industry Data Security Standard) compliant.
5. Core Entities & Database Schema Design
From the functional requirements, we identify six foundational entities:
- Merchant / Client: The business utilizing our payment gateway (e.g., Amazon, Flipkart).
- Customer / User: The end-buyer purchasing items from the merchant.
- Payment Intent: Represents the intent to purchase (items, price, currency).
- Payment Session: A short-lived secure session controlling the checkout window.
- Payment Method: The instrument used (Visa, Mastercard, etc.).
- Webhook / Callback: The notification mechanism informing merchants of payment success or failure.
Database Schemas (RDBMS / PostgreSQL)
A. Payment Intent Table (payment_intents)
CREATE TABLE payment_intents (
intent_id VARCHAR(64) PRIMARY KEY,
merchant_id VARCHAR(64) NOT NULL,
customer_id VARCHAR(64) NOT NULL,
order_id VARCHAR(64) NOT NULL,
amount DECIMAL(12, 2) NOT NULL,
currency VARCHAR(3) NOT NULL,
status VARCHAR(32) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
B. Payment Processor / Transaction Table (payment_transactions)
CREATE TABLE payment_transactions (
transaction_id VARCHAR(64) PRIMARY KEY,
intent_id VARCHAR(64) NOT NULL,
merchant_id VARCHAR(64) NOT NULL,
status VARCHAR(32) NOT NULL,
processor_response_code VARCHAR(16),
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
6. API Design Endpoints
To orchestrate the payment lifecycle, our gateway exposes three primary REST endpoints:
7. Step-by-Step Transaction Flow Walkthrough
When an end-user clicks "Buy Now" on a merchant's website, three distinct phases execute:
8. High-Level System Architecture
9. Deep-Dive Design: Component-by-Component Breakdown
A. Payment Intent & Session Management
- When the user clicks "Buy Now", the merchant calls our Payment Intent Service, which writes metadata into a consistent relational database (PostgreSQL).
- Next, the client requests a session. The Checkout Session Service stores session metadata inside a Redis Cluster configured with a strict Time-To-Live (TTL) of 10 minutes (enforcing the checkout countdown timer).
- Redis ensures sub-millisecond retrieval times, helping us stay well under our 200ms latency budget.
- The gateway returns a secure redirect URL (
https://pay.gateway.com/session_id_xyz), ensuring the card input page is hosted entirely on our secure domain, insulating the merchant from handling raw PCI data.
B. PCI-DSS Compliance & Tokenization Service
When the user fills out their credit card details inside our hosted checkout frontend and clicks "Pay", the request lands in our Checkout Backend Service.
Security Guarantee: At no point do the merchant or their servers touch, process, or store raw credit card numbers (Primary Account Number - PAN).
To remain strictly PCI-DSS compliant, sensitive card data enters an isolated internal security zone:
- Card Validation: The Tokenization Service validates card number algorithms (e.g., Luhn check).
- Card Fingerprinting: A secure hash fingerprint is generated combining:
- BIN Number: The first 6 digits identifying the issuing bank (e.g., Chase, ICICI).
- Last 4 Digits: For user display purposes.
- Expiration Date & Cardholder Name.
- Hardware Security Module (HSM): Instead of software-based encryption keys that could leak in cloud storage, raw card numbers are encrypted using an isolated physical Hardware Security Module (HSM).
- Token Generation: The system returns an opaque
encrypted_card_tokento be used in downstream processing.
C. Orchestrator Service & Adaptor Pattern
Once the card token is secured, the request moves to the Orchestrator Service:
- Merchant Preference Lookup: The orchestrator queries the Merchant Preference DB to check which downstream processor the merchant selected (e.g., Stripe, PayPal, Razorpay) based on routing costs or region.
- Adapter Design Pattern: Because every payment processor exposes a unique API payload format, the orchestrator utilizes Processor Connectors (e.g.,
StripeConnector,PayUConnector) to translate our internal token payload into the specific third-party schema required. - External Processor Gateway: The connector invokes the external financial network.
10. Real-World Pitfalls, Failures, & Reconciliation Workflows
The Distributed Transaction Dilemma
When our gateway makes an HTTP call to an external payment processor, network timeouts can occur.
- The Failure Mode: The user clicks pay, the bank successfully debits the money, but the network drops the HTTP response before our gateway receives the confirmation. The UI displays "Payment Failed", causing user panic and support tickets.
- The Resolution (Reconciliation Job):
- When the request is sent to the processor, our transaction status is initially marked as
SENT. - A decoupled Async Event-Driven Architecture powered by Kafka ingests immediate callbacks.
- A scheduled Reconciliation Service runs batch jobs nightly (or hourly), pulling ledger files from processors (Stripe/Bank) and cross-referencing them against our Payment Processor DB.
- If a discrepancy is found (money deducted at bank, marked failed in gateway), a background reconciliation ledger updates the final state and triggers automatic webhook notifications or refunds.
- When the request is sent to the processor, our transaction status is initially marked as
Kafka Event Pipeline Architecture
11. Summary and Key Takeaways
- Gateway vs. Processor: A payment gateway acts as the orchestration and tokenization traffic controller, while a processor interfaces directly with banking networks.
- Consistency over Availability: Payment systems prioritize strict data consistency ( in CAP theorem) to prevent double-charging and ledger corruptions.
- Zero-Trust PCI Boundary: Merchants must never touch raw card data; tokenization via isolated frontend services and Hardware Security Modules (HSMs) is mandatory.
- Low-Latency Caching: Redis clusters with short TTLs power checkout sessions to maintain sub-200ms API response times.
- Extensible Routing: The Adapter Design Pattern paired with Merchant Preference databases allows dynamic routing across multiple payment processors (Stripe, PayPal, Razorpay).
- Asynchronous Event-Driven Callbacks: Kafka brokers decouple immediate synchronous user checkouts from heavy downstream bank verifications.
- Nightly Reconciliation: Automated background reconciliation jobs are essential to resolve network partition dropouts, missing webhook callbacks, and ledger discrepancies.