Design a Payment Service

Difficulty: MEDIUMCategory: HLDFrequency: 1Asked On 2025-04-21

Problem Statement

Design a Payment Service that enables users to make secure, reliable, and fast digital payments for online transactions (e.g., e-commerce orders, subscriptions, or digital content).


The system should handle payment processing, refunds, transaction history, and integration with multiple payment gateways (like Razorpay, Stripe, PayPal, etc.) while maintaining high availability, security, and compliance with financial standards.


🎯 Objective


Build a scalable, fault-tolerant, and secure payment processing platform that can:


•Accept and process payments from various sources (credit/debit cards, UPI, net banking, wallets).
•Integrate seamlessly with external payment gateways and banks.
•Provide real-time status updates and transaction traceability.
•Support refunds, retries, and reconciliation in case of failures.
•Handle high concurrency during large-scale events (e.g., sales, subscriptions).


✅ Functional Requirements


1. User & Merchant Management


•Merchants can register, configure payout accounts, and obtain API keys.
•Users can make payments via the merchant’s app or website.
•Each merchant has transaction limits, commission rates, and supported payment methods.


2. Payment Initiation


•A merchant initiates a payment request with amount, order ID, and payment mode.
•Payment service redirects to selected gateway or UPI app.
•Generate a Payment Link or Checkout Session for web and mobile.


3. Payment Authorization & Processing


•Validate user payment details.
•Forward request to an external payment gateway.
•Handle two-factor authentication (2FA) and OTP verification.
•Support multiple payment modes:
•Cards (Visa/Mastercard/Amex)
•Net banking
•Wallets (Paytm, PhonePe)
•UPI (Google Pay, BHIM)
•Record payment intent, status, and response codes.


4. Payment Confirmation


•Receive gateway callback on success/failure.
•Update payment status as SUCCESS, FAILED, or PENDING.
•Notify merchant system via webhook or API callback.
•Provide a transaction receipt with unique reference ID.


5. Refunds & Reconciliation


•Support full and partial refunds initiated by merchants.
•Reconcile daily transactions with gateways and banks.
•Maintain idempotency to avoid double refunds or duplicate charges.
•Detect and flag failed or mismatched transactions.


6. Transaction History


•Users and merchants can view payment history and status.
•Support filtering by date, status, or payment mode.
•Export transaction data for reports and audits.


7. Notifications


•Real-time notifications for:
•Payment success/failure.
•Refund initiation/completion.
•Settlement completion for merchants.


8. Security & Compliance


•PCI-DSS compliant data handling.
•End-to-end encryption of payment data.
•Tokenization of card details.
•Role-based access control for admins and merchants.
•Audit logging of all financial operations.


⚙️ Non-Functional Requirements


| Attribute | Target |

| ------------------- | ---------------------------------------- |

| **Scalability** | Handle 100K+ TPS during peak load |

| **Availability** | 99.99% uptime |

| **Latency** | < 500 ms for internal operations |

| **Consistency** | Strong consistency for payment states |

| **Security** | PCI-DSS, GDPR, and encryption compliance |

| **Fault Tolerance** | Retry mechanisms and redundant gateways |

| **Observability** | End-to-end tracing for each transaction |


🧩 Core Components


| Component | Responsibility |

| -------------------------------- | --------------------------------------------------- |

| **API Gateway** | Entry point for merchants and apps |

| **Payment Orchestrator Service** | Routes and manages payment workflow |

| **Gateway Adapter Service** | Integrates with multiple external gateways |

| **Transaction Service** | Manages states and metadata of each transaction |

| **Notification Service** | Sends alerts and webhooks |

| **Reconciliation Service** | Verifies payment status with banks |

| **Refund Service** | Handles refund processing and tracking |

| **Ledger Service** | Maintains financial transactions and audit logs |

| **Auth & Tokenization Service** | Manages user tokens, encryption, and authentication |


🧱 High-Level Architecture

1 2 +------------------------+ 3 | Merchant / User App | 4 +-----------+------------+ 5 | 6 v 7 +---------+---------+ 8 | API Gateway | 9 +---------+----------+ 10 | 11 +-----------------------------------+ 12 | Payment Backend | 13 |-----------------------------------| 14 | | 15 | +-----------------------------+ | 16 | | Payment Orchestrator | | 17 | +-----------------------------+ | 18 | | | | 19 | | | | 20 | +---v---+ +---v---+ | 21 | | Gateway| | Ledger| | 22 | | Adapter| | Service| | 23 | +---+----+ +---+----+ | 24 | | | | 25 | +---v----+ +---v----+ | 26 | | Refund | | Reconcile| | 27 | +---+-----+ +---+-----+ | 28 +------|-------------|----------------+ 29 | | 30 v v 31 +--------------+ +-------------+ 32 | Payment APIs | | Bank / PSPs | 33 | (e.g., Stripe,| | UPI, Razorpay| 34 | PayPal) | | Gateways) | 35 +--------------+ +-------------+ 36 | 37 v 38 +----------------------+ 39 | Storage & Data Layer | 40 | (Postgres, Redis, | 41 | Kafka, S3, Vault) | 42 +----------------------+

🧾 Data Model (Simplified)


Transaction Table

| Field | Description |

| ------------ | -------------------------------------- |

| txn_id | Unique transaction ID |

| user_id | Payer |

| merchant_id | Merchant |

| amount | Transaction amount |

| currency | ISO code (INR, USD, etc.) |

| status | INITIATED / SUCCESS / FAILED / PENDING |

| payment_mode | CARD / UPI / WALLET |

| gateway_id | External gateway |

| created_at | Initiation timestamp |

| updated_at | Status update timestamp |


Refund Table

| Field | Description |

| ------------ | ------------------------------ |

| refund_id | Unique refund ID |

| txn_id | Linked transaction |

| amount | Refund amount |

| status | INITIATED / COMPLETED / FAILED |

| initiated_at | Timestamp |

| completed_at | Timestamp |



Ledger Table

| Field | Description |

| ------------- | --------------------- |

| entry_id | Unique ID |

| txn_id | Transaction reference |

| type | Debit / Credit |

| amount | Transaction amount |

| balance_after | Current balance |

| created_at | Timestamp |



⚡ Scalability & Performance Considerations


| Challenge | Solution |

| ----------------------- | ------------------------------------------- |

| **Gateway downtime** | Multi-gateway failover and fallback routing |

| **Duplicate requests** | Idempotency tokens per transaction |

| **Concurrency control** | Optimistic locking for transactions |

| **Throughput spikes** | Kafka-based async processing and retries |

| **Read scalability** | Redis caching for transaction lookups |

| **Data partitioning** | Shard transactions by merchant or region |


🔐 Security & Compliance

•PCI-DSS compliant card storage (use tokens, not raw data).
•TLS 1.3 encryption for all communications.
•Secure vaults (e.g., HashiCorp Vault) for API keys and secrets.
•Web Application Firewall (WAF) for fraud detection.
•Audit logging for all payment activities.

📊 Observability & Monitoring

•Distributed tracing for every transaction (e.g., OpenTelemetry).
•Metrics:
•Success/failure rate per gateway.
•Latency distribution (p50, p95, p99).
•Refund SLA adherence.
•Real-time dashboards for transaction volume and gateway health.


⚙️ Tech Stack (Example)


| Layer | Technology |

| --------------------------- | ------------------------------- |

| **Frontend / Merchant SDK** | React, Flutter SDKs |

| **Backend** | Java Spring Boot / Go / Node.js |

| **Database** | PostgreSQL / Aurora / DynamoDB |

| **Queue** | Kafka / RabbitMQ |

| **Cache** | Redis |

| **API Gateway** | Kong / NGINX / AWS API Gateway |

| **Storage** | S3 (for receipts, reports) |

| **Security** | Vault, JWT, OAuth2 |

| **Monitoring** | Prometheus + Grafana |


🚨 Failure & Recovery



| Failure | Handling |

| ------------------------ | ------------------------------ |

| Gateway timeout | Retry with exponential backoff |

| Duplicate transaction | Idempotency key check |

| Refund mismatch | Periodic reconciliation |

| Network partition | Queue retry mechanism |

| Merchant callback failed | Async webhook retry |



💡 Possible Extensions

•Support for subscriptions and recurring payments.
•Fraud detection service using ML models.
•Dynamic routing to gateways based on cost/success rate.
•Settlement service for automatic merchant payouts.
•Multi-currency conversion for international transactions.


✅ End Goal


Design a highly available, fault-tolerant, and secure Payment Service that processes millions of transactions daily, supports multiple payment modes, integrates with external gateways, and ensures financial consistency and compliance across the entire payment lifecycle.

Solution

Comments