UPI (Unified Payments Interface) has revolutionized digital payments in India, processing billions of transactions monthly. Designing a system like UPI, or a TPAP (Third Party Application Provider) like PhonePe or Google Pay, is a classic system design interview question. It tests your ability to handle high concurrency, ensure zero data loss, and maintain strict consistency when dealing with money.
Requirements (functional and non-functional)
Functional Requirements
- Link Accounts: Users can link their bank accounts to a Virtual Payment Address (VPA).
- Transfer Money: Users can send money from their VPA to another user's VPA.
- Transaction History: Users can view their past transactions and check the status of pending ones.
Non-functional Requirements
- Strict Consistency (ACID): Financial systems cannot lose money or create money out of nowhere. Consistency is prioritized over availability.
- Idempotency: A user must never be charged twice for the same transaction, even if they retry due to a network timeout.
- High Availability: The system should aim for 99.99% uptime for core components.
- Low Latency: The p99 latency for initiating a payment should be under 2 seconds.
Capacity estimates
Let us assume the system is operating at the scale of a major Indian payment app.
- Users: 100 million Daily Active Users (DAU).
- Throughput: If each user makes an average of 3 transactions per day, that is 300 million transactions daily.
- TPS (Transactions Per Second): 300,000,000 / 86,400 seconds ≈ 3,500 TPS on average. Peak traffic (e.g., during Diwali or flash sales) can easily hit 3x this, so we must design for 10,500 TPS.
- Storage: A single transaction record (including metadata, timestamps, and IDs) takes about 1 KB. 300 million transactions * 1 KB = 300 GB/day. Over a year, this is roughly 110 TB of relational data, meaning database sharding is mandatory.
API design
We will expose RESTful APIs for the client. The most critical endpoint is the transfer API.
1. Initiate Payment
POST /v1/payments/transfer
Headers:
Authorization: Bearer <token>Idempotency-Key: <UUID>(Crucial for preventing double charges)
Request Body:
{
"sender_vpa": "alice@upi",
"receiver_vpa": "bob@upi",
"amount": 500.00,
"currency": "INR",
"device_id": "dev_9876"
}Response: 202 Accepted (Since payment processing involves third-party bank APIs, it is best handled asynchronously or via polling).
{
"transaction_id": "txn_123456",
"status": "PROCESSING"
}2. Get Transaction Status
GET /v1/payments/status/{transaction_id}
Returns the current state of the transaction (e.g., SUCCESS, FAILED, PENDING).
Data model
For a payment system, a Relational Database (RDBMS) like PostgreSQL or MySQL is non-negotiable. We need ACID properties, specifically atomicity and isolation, to handle concurrent balance updates safely.
Core Tables
- Users:
user_id(PK),name,phone_number,created_at - Accounts:
account_id(PK),user_id(FK),vpa(Unique),bank_id,status - Transactions:
txn_id(PK),idempotency_key(Unique),sender_account_id,receiver_account_id,amount,status,created_at,updated_at - Ledger: To maintain double-entry bookkeeping. Every transaction creates two ledger entries: a debit for the sender and a credit for the receiver.
High-level architecture
Here is how the components interact when a user initiates a payment:
- The request hits the API Gateway, which handles rate limiting, authentication, and SSL termination.
- The Payment Service receives the request and checks Redis to see if the
Idempotency-Keyhas been processed recently. - If it is a new request, it writes a
PENDINGtransaction to PostgreSQL. - It calls the Bank Integration Service, which acts as an adapter to communicate with various external bank APIs or the NPCI network.
- Once the bank responds, the database is updated, and an event is published to Kafka for downstream services like notifications and analytics.
Deep dives
1. Idempotency: Preventing Double Charges
Network calls are unreliable. If the client sends a payment request, but the response is lost due to a network drop, the client will retry. If we process the retry as a new payment, the user gets charged twice.
To solve this, the client generates a unique Idempotency-Key (usually a UUID) for every distinct payment attempt.
Here is how we handle it across different languages:
def process_payment(request):
# 1. Check Redis for fast rejection/return
existing_txn = redis.get(request.idempotency_key)
if existing_txn:
return get_transaction_status(existing_txn)
# 2. Create DB record (Unique constraint prevents race conditions)
try:
txn = db.execute(
"INSERT INTO transactions (idempotency_key, amount, status) VALUES (?, ?, 'PENDING')",
(request.idempotency_key, request.amount)
)
except IntegrityError:
# Another concurrent thread inserted it first
return get_transaction_status_by_key(request.idempotency_key)
# 3. Proceed with bank integration
return execute_bank_transfer(txn)2. Distributed Transactions and the Saga Pattern
In a UPI transfer, money must be debited from the sender's bank and credited to the receiver's bank. Because these are two separate external systems, we cannot use a traditional database 2-Phase Commit (2PC).
Instead, we use the Saga Pattern. We break the transaction into a sequence of local steps:
- Debit Sender: Call Sender's Bank API.
- Credit Receiver: Call Receiver's Bank API.
If step 2 fails (e.g., receiver's bank is down), we cannot simply "rollback" step 1 because the money has already left the sender's account. We must execute a Compensating Transaction: we initiate a refund to the sender's bank. The state machine in our database tracks this meticulously (PENDING -> DEBIT_SUCCESS -> CREDIT_FAILED -> REFUND_INITIATED -> REFUND_SUCCESS).
3. Handling Flaky Bank APIs (Reconciliation)
What happens if we call the sender's bank to debit the money, and the API times out? Did the debit succeed or fail?
When an external API times out, the transaction must be moved to an UNKNOWN or PROCESSING state. A background Reconciliation Service will then take over. It will periodically poll the bank's status API for that specific transaction ID. If the bank doesn't support real-time polling, the reconciliation service will parse the end-of-day settlement files provided by the bank to match transactions and resolve discrepancies.
Bottlenecks and trade-offs
| Bottleneck / Trade-off | Description | Resolution |
|---|---|---|
| Database Scaling | A single PostgreSQL instance cannot handle 10,500 TPS. | Sharding: We must shard the database. Sharding by user_id is tricky because every transaction involves two users. A common approach is sharding the Transactions table by transaction_id (or a time-based UUID) for write-heavy payment processing, and maintaining an asynchronous read-optimized view sharded by user_id for users to view their history. |
| Consistency vs. Availability | CAP Theorem dictates we must choose during a partition. | CP over AP: In payments, we choose Consistency. If the database cannot guarantee ACID properties due to a node failure, it is better to reject the payment (lower availability) than to process it incorrectly. |
| Sync vs. Async | Waiting for bank APIs synchronously holds up server connections. | Async Processing: We accept the request, return 202 Accepted, and process the bank calls via message queues. The client polls for the status or receives a push notification (WebSocket/FCM) when done. |
Questions an interviewer will ask next
1. How do you ensure the Kafka notification event is sent ONLY if the database transaction commits?
Use the Transactional Outbox Pattern. Instead of publishing directly to Kafka, write the event to an outbox table in the exact same database transaction as the payment update. A separate background process (like Debezium) tails the database binlog and publishes the outbox entries to Kafka. This guarantees at-least-once delivery.
2. How do you prevent a malicious user from initiating 100 concurrent transfers to drain their account beyond its balance?
If we maintain a wallet balance internally, we must use row-level locking. In PostgreSQL, using SELECT ... FOR UPDATE on the sender's account row ensures that concurrent transactions are processed sequentially, preventing race conditions that could lead to a negative balance.
3. How would you detect fraudulent transactions in real-time? We can tap into the Kafka event stream. A stream processing framework like Apache Flink can consume payment events, aggregate them over a sliding window (e.g., "user made 5 transactions in 1 minute"), and evaluate them against a rules engine or an ML model. If fraud is suspected, the system can automatically freeze the account.