How Money Actually Moves: Building Payment Systems at Scale
It's 8:47 PM on a Sunday. You're at a dhaba on NH-44, somewhere between Hyderabad and Bangalore. The biryani was excellent. You pull out your phone, open PhonePe, scan the QR code, and tap "Pay ₹180."
Two seconds later: "Payment Successful."
What just happened in those two seconds?
Your phone talked to PhonePe's servers in Bangalore. PhonePe talked to NPCI in Mumbai. NPCI talked to your bank (maybe HDFC in Chennai). Your bank talked to the dhaba owner's bank (maybe SBI in Delhi). Money moved. Confirmations flowed back. Your phone buzzed.
Nine network hops. Four organizations. Two seconds. Zero room for error.
That's what we're building today.
The Scale That Keeps Engineers Awake
Before we dive into architecture, let's appreciate what we're dealing with.
UPI in 2024:
- 14 billion transactions per month (and growing 50% year-over-year)
- Peak load: 50,000+ transactions per second (during IPL matches, Diwali sales)
- 99.95% success rate required (regulators are watching)
- 2-second end-to-end latency (users expect instant)

UPI Scale 2024
To put this in perspective: UPI processes more real-time transactions than Visa and Mastercard combined. And it does it in a country where internet connectivity is... let's say "variable."
This isn't a theoretical exercise. This is nation-scale infrastructure that handles more money in a day than most countries' GDP.
The Anatomy of a Single Payment
Let's follow your ₹180 biryani payment through the system. Understanding one transaction deeply will help us understand how to handle 50,000 per second.
The Players
You (Payer): priya@okicici (your UPI ID linked to ICICI Bank)
Dhaba Owner (Payee): dhaba.nh44@sbi (their UPI ID linked to SBI)
PhonePe: The app you're using (PSP - Payment Service Provider)
NPCI: The central switch that routes all UPI transactions
ICICI Bank: Your bank (will debit your account)
SBI: Dhaba's bank (will credit their account)
The Flow

Payment Flow Sequence
Let's walk through this step by step:
Step 1: You tap "Pay"
Your PhonePe app creates a payment request:
json{ "payer_vpa": "priya@okicici", "payee_vpa": "dhaba.nh44@sbi", "amount": 180.00, "client_txn_id": "PP-2024-01-15-XYZ123", "device_fingerprint": "abc123...", "location": {"lat": 15.4, "lng": 78.2} }
The app signs this request cryptographically. This signature proves the request came from your phone, not an attacker.
Step 2: PhonePe validates
Before forwarding to NPCI, PhonePe checks:
- Is this a valid UPI ID format?
- Is the amount within limits?
- Is this user's account active?
- Is this device registered?
- Does this look like fraud? (more on this later)
If everything checks out, PhonePe adds its own signature and forwards to NPCI.
Step 3: NPCI routes
NPCI is the brain of UPI. It:
- Parses the payee VPA:
dhaba.nh44@sbi→ SBI's handle - Looks up SBI's endpoint in its registry
- Checks: Is SBI's system responding? (health checks run constantly)
- Forwards the request to SBI
Step 4: Payee's bank validates
SBI checks:
- Does
dhaba.nh44exist? - Is this account active?
- Are there any blocks or holds?
SBI responds: "Yes, this payee is valid. Proceed."
Step 5: NPCI routes to payer's bank
Now NPCI knows the payee is valid. It routes to ICICI (your bank) with: "Please debit ₹180 from priya@okicici."
Step 6: Your bank debits
ICICI:
- Checks your balance (₹15,432.50 - plenty)
- Places a hold on ₹180
- Debits the amount
- Returns: "Debit successful, reference: ICICI-REF-789"
Step 7: Credit the payee
NPCI tells SBI: "Credit ₹180 to dhaba.nh44, reference: ICICI-REF-789"
SBI credits the dhaba owner's account.
Step 8: Confirmations flow back
SBI → NPCI → PhonePe → Your phone: "Payment Successful! ₹180 paid to dhaba.nh44@sbi"
The dhaba owner's phone buzzes too: "₹180 received from priya@okicici"
Total time: 1.8 seconds.
The Architecture That Makes This Possible
Now that we understand a single transaction, let's see how we handle 50,000 of them simultaneously.

UPI Architecture
Layer 1: API Gateway
The API Gateway is the front door. Every request hits this layer first.
What it does:
- Authentication: Is this really PhonePe? (verify digital signatures)
- Rate Limiting: PhonePe gets 10,000 req/sec quota. Google Pay gets their quota. Nobody gets unlimited.
- Request Validation: Is the JSON well-formed? Are required fields present?
- Logging: Every request is logged. Regulators audit these logs.
- Routing: Forward to the appropriate internal service.
Why it matters:
During demonetization in 2016, NPCI saw traffic spike 10x overnight. Without rate limiting, rogue apps could have brought down the entire system. The API Gateway is your first line of defense.
Layer 2: Transaction Router
The router's job seems simple: look at the VPA handle (@sbi, @okicici, @ybl) and route to the right bank. But at 50,000 TPS, "simple" becomes complex.
The routing table:
@sbi → sbi.npci.internal:8443 @okicici → icici.npci.internal:8443 @ybl → yesbank.npci.internal:8443 @okaxis → axis.npci.internal:8443 ... (200+ banks)
The challenges:
-
Handle updates: Banks sometimes change their handles. @paytm used to route to Paytm Payments Bank, now routes to Axis Bank. Updates must be atomic—no transactions should route to the wrong bank during an update.
-
Health checks: If SBI's system is down, don't send traffic there. Route to their backup endpoint. If both are down, fail fast with a clear error.
-
Load balancing: Large banks have multiple endpoints. Distribute traffic evenly. If one endpoint is slow, send less traffic there.
Layer 3: Transaction Processor
This is the brain. It maintains a state machine for every active transaction.

Transaction State Machine
The states:
- INITIATED: Request received, validated
- PAYEE_VALIDATED: Payee's bank confirmed the account exists
- DEBIT_PENDING: Waiting for payer's bank to debit
- DEBITED: Money left payer's account
- CREDIT_PENDING: Waiting for payee's bank to credit
- COMPLETED: Money arrived, everyone happy
- FAILED: Something went wrong (with reason code)
- REFUND_PENDING: Debit succeeded but credit failed, initiating refund
Why state machines matter:
Imagine the credit step fails. Without a state machine, you'd have to figure out: did the debit happen? Is the money stuck somewhere? With a state machine, you know exactly where you are and what to do next.
The state machine also handles timeouts. If a bank doesn't respond in 30 seconds, the transaction moves to a timeout state, and recovery procedures kick in.
The Database Design
We're storing 14 billion transactions per month. Let's do the math:
- 14B transactions/month × 500 bytes/transaction = 7 TB/month
- Query requirements: Find any transaction in <100ms
- Compliance: Store for 10 years (RBI mandate)
The Schema
sqlCREATE TABLE transactions ( txn_id UUID PRIMARY KEY, idempotency_key VARCHAR(100) UNIQUE NOT NULL, -- Parties payer_vpa VARCHAR(50) NOT NULL, payee_vpa VARCHAR(50) NOT NULL, payer_bank_code VARCHAR(10) NOT NULL, payee_bank_code VARCHAR(10) NOT NULL, -- Money amount DECIMAL(15,2) NOT NULL, currency CHAR(3) DEFAULT 'INR', -- Status status VARCHAR(20) NOT NULL, failure_code VARCHAR(20), failure_reason VARCHAR(200), -- Timestamps initiated_at TIMESTAMP NOT NULL, completed_at TIMESTAMP, -- References payer_ref VARCHAR(50), payee_ref VARCHAR(50), npci_ref VARCHAR(50), -- Audit created_at TIMESTAMP DEFAULT NOW(), updated_at TIMESTAMP DEFAULT NOW() ) PARTITION BY RANGE (initiated_at); -- Monthly partitions CREATE TABLE transactions_2024_01 PARTITION OF transactions FOR VALUES FROM ('2024-01-01') TO ('2024-02-01'); CREATE TABLE transactions_2024_02 PARTITION OF transactions FOR VALUES FROM ('2024-02-01') TO ('2024-03-01'); -- ... and so on -- Indexes CREATE INDEX idx_txn_payer ON transactions(payer_vpa, initiated_at DESC); CREATE INDEX idx_txn_payee ON transactions(payee_vpa, initiated_at DESC); CREATE INDEX idx_txn_status ON transactions(status) WHERE status NOT IN ('COMPLETED', 'FAILED');
Why This Design?
Partitioning by month:
- Queries like "show my last 10 transactions" only scan recent partitions
- Archiving old data is simple: detach and move the partition
- Each partition has its own indexes—smaller, faster
UUID primary key:
- No sequential bottleneck (BIGSERIAL would create contention)
- Can be generated on any server without coordination
- Globally unique across all instances
Idempotency key:
- The UNIQUE constraint on this column is your last line of defense against double payments
- If someone tries to insert a duplicate, the database rejects it
Partial index on status:
- 99% of transactions are COMPLETED or FAILED
- This index only covers active transactions—much smaller and faster
The Hard Problem: Preventing Double Payments
This is the most important problem in payment systems. Get this wrong, and you'll either:
- Charge customers twice (they'll sue)
- Give merchants free money (you'll go bankrupt)
How Double Payments Happen
Scenario 1: Network timeout
- User taps "Pay"
- Request reaches your server
- You debit the user's account
- Network drops before response reaches user's phone
- User sees "Payment Failed" (but it actually succeeded!)
- User taps "Pay" again
- You debit again → Double charge
Scenario 2: Retry storm
- User taps "Pay"
- App doesn't get response in 2 seconds
- App automatically retries
- Meanwhile, original request is still processing
- Both requests succeed → Double charge
Scenario 3: Malicious replay
- Attacker captures a valid payment request
- Replays it 100 times
- Each replay triggers a new payment
The Defense: Idempotency
The word "idempotent" means "same result no matter how many times you do it." For payments, this means: no matter how many times a user clicks "Pay," exactly one payment happens.

Preventing Double Payments
The implementation:
gofunc (s *PaymentService) ProcessPayment(ctx context.Context, req *PaymentRequest) (*PaymentResponse, error) { // Step 1: Generate idempotency key // This is deterministic based on request content idemKey := generateIdempotencyKey(req) // Step 2: Check if already processed if cachedResponse := s.redis.Get(ctx, "idem:"+idemKey); cachedResponse != nil { // Return the same response as before return cachedResponse, nil } // Step 3: Acquire distributed lock // Prevents concurrent processing of same payment lock, err := s.acquireLock(ctx, "lock:"+req.PayerVPA, 30*time.Second) if err != nil { return nil, errors.New("another transaction in progress") } defer lock.Release() // Step 4: Double-check after acquiring lock if cachedResponse := s.redis.Get(ctx, "idem:"+idemKey); cachedResponse != nil { return cachedResponse, nil } // Step 5: Insert with conflict detection txnID := uuid.New() result, err := s.db.Exec(ctx, ` INSERT INTO transactions (txn_id, idempotency_key, status, ...) VALUES ($1, $2, 'INITIATED', ...) ON CONFLICT (idempotency_key) DO NOTHING RETURNING txn_id `, txnID, idemKey) if result.RowsAffected() == 0 { // Duplicate! Fetch the existing transaction's result return s.getExistingResult(ctx, idemKey) } // Step 6: Process the payment response, err := s.executePayment(ctx, txnID, req) // Step 7: Cache the response for future retries s.redis.Set(ctx, "idem:"+idemKey, response, 24*time.Hour) return response, err } func generateIdempotencyKey(req *PaymentRequest) string { // Combine fields that uniquely identify this payment intent data := req.PayerVPA + "|" + req.PayeeVPA + "|" + req.Amount.String() + "|" + req.ClientTxnID hash := sha256.Sum256([]byte(data)) return hex.EncodeToString(hash[:]) }
Three layers of protection:
-
Redis cache: Fast path. If we've seen this key, return cached response immediately.
-
Distributed lock: Prevents concurrent processing. Only one thread can process a payment for a given payer at a time.
-
Database constraint: Last line of defense. Even if Redis fails, the UNIQUE constraint prevents duplicates.
When Things Go Wrong: Failure Handling
In distributed systems, failure isn't exceptional—it's expected. Networks drop. Databases slow down. Banks go offline. Your system must handle all of this gracefully.
Scenario 1: Debit Succeeds, Credit Fails
This is the nightmare scenario. Money left the payer's account but never arrived at the payee's account. Where is the money?

Credit Failure Flow
The solution: Automatic refund
gofunc (s *PaymentService) handleCreditFailure(ctx context.Context, txn *Transaction) error { // Update transaction status s.db.Exec(ctx, ` UPDATE transactions SET status = 'REFUND_PENDING', failure_code = $1 WHERE txn_id = $2 `, "CREDIT_FAILED", txn.ID) // Initiate refund to payer's bank refundReq := &RefundRequest{ OriginalTxnID: txn.ID, Amount: txn.Amount, PayerBank: txn.PayerBank, Reason: "CREDIT_FAILED", } // This goes through the same idempotent flow return s.initiateRefund(ctx, refundReq) }
Important: The refund is also idempotent. If the refund request fails and retries, it won't refund twice.
Scenario 2: Bank Timeout
You asked ICICI to debit. They didn't respond. Did the debit happen or not?
The wrong approach: Assume failure and retry.
If the debit actually happened, you've now debited twice.
The right approach: Check status before doing anything.

Bank Timeout Handling
gofunc (s *PaymentService) handleDebitTimeout(ctx context.Context, txn *Transaction) error { // Don't retry! Check status first. status, err := s.checkDebitStatus(ctx, txn.PayerBank, txn.NPCIRef) switch status { case "SUCCESS": // Debit happened. Continue to credit step. return s.initiateCredit(ctx, txn) case "FAILED": // Debit didn't happen. Safe to mark transaction as failed. return s.markFailed(ctx, txn, "DEBIT_FAILED") case "PENDING": // Bank is still processing. Wait and retry status check. return s.scheduleStatusCheck(ctx, txn, 30*time.Second) case "UNKNOWN": // Bank doesn't know either. Escalate to manual review. return s.escalateToManualReview(ctx, txn) } }
Golden rule: When in doubt, check status. Never retry blindly.
Scenario 3: Your Own System Crashes
Midway through processing, your server dies. The transaction is in DEBIT_PENDING state. What happens?
The solution: Recovery workers
gofunc (s *RecoveryWorker) Run(ctx context.Context) { ticker := time.NewTicker(1 * time.Minute) for range ticker.C { // Find stuck transactions stuckTxns, _ := s.db.Query(ctx, ` SELECT * FROM transactions WHERE status IN ('DEBIT_PENDING', 'CREDIT_PENDING') AND updated_at < NOW() - INTERVAL '5 minutes' FOR UPDATE SKIP LOCKED `) for _, txn := range stuckTxns { s.recoverTransaction(ctx, txn) } } } func (s *RecoveryWorker) recoverTransaction(ctx context.Context, txn *Transaction) { switch txn.Status { case "DEBIT_PENDING": // Check if debit happened s.handleDebitTimeout(ctx, txn) case "CREDIT_PENDING": // Check if credit happened, or initiate refund s.handleCreditTimeout(ctx, txn) } }
The key insight: Transactions should never be "stuck." Every state has a timeout. Every timeout triggers a recovery action.
Scaling: From Startup to Nation-Scale
Let's see how the architecture evolves as traffic grows.
Stage 1: 1,000 TPS (Seed Stage)

Scale 1K TPS
Architecture:
- 3 application servers behind a load balancer
- Single PostgreSQL database (with read replicas)
- Single Redis cluster
- Synchronous processing end-to-end
What works:
- Simple to operate and debug
- All transactions are consistent
- Easy to reason about
Numbers:
- p99 latency: 200ms
- Infra cost: ~₹5 lakh/month
Stage 2: 10,000 TPS (Growth Stage)

Scale 10K TPS
What changes:
-
Async credit processing:
- User doesn't need to wait for credit to complete
- Debit is synchronous, credit goes to a queue
- User sees "Success" the moment debit confirms
-
Database sharding:
- Transactions sharded by payer bank
- Each bank's transactions are isolated
- No cross-shard queries needed
-
Caching:
- VPA validation results cached (10-minute TTL)
- Bank routing table cached (1-minute TTL)
- Reduces database load by 80%
Numbers:
- p99 latency: 150ms (faster due to async credit)
- Infra cost: ~₹25 lakh/month
Stage 3: 50,000+ TPS (IPL Final Night)

Scale 50K TPS
Emergency measures:
-
Request queuing:
- Absorb traffic spikes in Kafka
- Process at a sustainable rate
- Users wait slightly longer but system doesn't crash
-
Circuit breakers:
- If HDFC is slow, stop sending traffic there
- Transactions to HDFC fail fast instead of timing out
- Other banks continue working
-
Graceful degradation:
Normal mode: All features enabled Spike mode: ├── ❌ Real-time balance (use cached balance) ├── ❌ Transaction history ├── ✅ Core payments only └── ⏳ Queue transactions < ₹100
The key insight: During extreme load, it's better to provide degraded service to everyone than perfect service to some and errors to others.
A Real Incident: The NPCI Timeout Storm
Let me tell you about a production incident that taught us an expensive lesson.
The symptom: At 6:30 PM on a Friday (of course), our success rate dropped from 99.5% to 73%. Alerts were firing everywhere.
The investigation:
Looking at metrics, we saw:
- NPCI response times spiking from 200ms to 15 seconds
- Our timeout was 10 seconds
- Every request was timing out
But here's the weird part: NPCI's status page showed "All Systems Operational."
What happened:
We dug into the logs and found:
6:15 PM - NPCI deployed a new version 6:20 PM - NPCI's connection pool started leaking 6:25 PM - NPCI's available connections dropped to 0 6:30 PM - All new requests queued behind dead connections
NPCI had a bug in their deployment. Their servers were "up" but couldn't accept new connections.
Our mistake:
Our health checks were pinging NPCI's
/health endpoint, which was responding. But actual payment requests were stuck in a queue.We were sending traffic to a system that looked healthy but couldn't actually process requests.
The fix:
-
Implemented "deep health checks" — Don't just ping
/health. Send a dummy transaction and verify end-to-end response. -
Added latency-based circuit breakers — If p50 latency exceeds 5 seconds, trip the circuit breaker. Don't wait for timeouts.
-
Built a manual override — On-call engineer can force-disconnect from NPCI and route all transactions to "pending" state.
The lesson: A system isn't healthy just because it responds to pings. Health is about whether it can do its job.
Security: Protecting the Money Pipeline
Payment systems are prime targets for attackers. Let's cover the major threats and defenses.
Attack 1: Replay Attacks
The attack: Attacker captures a valid payment request and replays it.
The defense: We already covered this—idempotency keys. But there's more:
gofunc validateRequest(req *PaymentRequest) error { // 1. Check timestamp reqTime := req.Timestamp if time.Since(reqTime) > 5*time.Minute { return errors.New("request expired") } // 2. Check nonce (one-time random value) if s.nonceCache.Exists(req.Nonce) { return errors.New("nonce already used") } s.nonceCache.Set(req.Nonce, true, 10*time.Minute) // 3. Verify signature if !verifySignature(req, req.Signature) { return errors.New("invalid signature") } return nil }
Attack 2: Account Takeover
The attack: Attacker gains access to someone's UPI PIN or device.
The defense: Multi-layer verification
- Device binding: UPI PIN only works from registered device
- SIM binding: App verifies phone number via silent SMS
- Velocity checks: Flag unusual patterns (new device, new location, sudden large transactions)
- Step-up authentication: High-risk transactions require additional verification
gofunc assessRisk(txn *Transaction, user *User) RiskLevel { score := 0 // New device? if !user.Devices.Contains(txn.DeviceID) { score += 30 } // New location? (>50km from usual) if distance(txn.Location, user.UsualLocation) > 50 { score += 20 } // Large amount? if txn.Amount > user.AverageTransaction * 5 { score += 25 } // Unusual time? if txn.Time.Hour() >= 0 && txn.Time.Hour() <= 5 { score += 15 } // First transaction to this payee? if !user.PreviousPayees.Contains(txn.PayeeVPA) { score += 10 } switch { case score >= 60: return RiskHigh // Block and verify case score >= 30: return RiskMedium // Allow but monitor default: return RiskLow // Allow } }
Attack 3: Man-in-the-Middle
The attack: Attacker intercepts traffic between app and server, modifies payment details.
The defense:
- TLS 1.3 everywhere: All communication encrypted
- Certificate pinning: App only trusts specific certificates (not just any CA-signed cert)
- Request signing: Every request signed with device-specific key
- Amount verification: Display amount on device, user confirms
Attack 4: Insider Threat
The attack: Employee with database access modifies transaction amounts.
The defense:
- Append-only ledger: No UPDATE operations allowed on financial data
- Multi-party signatures: Large transactions require multiple approvals
- Audit logging: Every query logged with employee ID
- Segregation of duties: The person who writes code can't deploy it
sql-- Trigger to prevent updates on ledger CREATE OR REPLACE FUNCTION prevent_ledger_update() RETURNS TRIGGER AS $$ BEGIN RAISE EXCEPTION 'Updates are not allowed on ledger_entries'; END; $$ LANGUAGE plpgsql; CREATE TRIGGER no_update_ledger BEFORE UPDATE ON ledger_entries FOR EACH ROW EXECUTE FUNCTION prevent_ledger_update();
Security Checklist
Before going live:
- All API endpoints require authentication
- Request signatures validated on every call
- Idempotency keys prevent replay attacks
- Rate limiting per user, per app, per IP
- TLS 1.3 with certificate pinning
- All sensitive data encrypted at rest
- Audit logs for every database operation
- Fraud detection on every transaction
- PCI-DSS compliance verified
- Penetration testing completed
Interview Tips: What to Say
When payment systems come up in interviews, structure your answer like this:
1. Start with Scale
"UPI processes 50,000+ TPS at peak. Our design needs to handle this while maintaining 99.95% success rate and <2 second latency."
2. Walk Through a Transaction
"Let me trace a single payment through the system: app to PSP to NPCI to banks. This helps us identify all the moving parts."
3. Focus on Idempotency
"The critical challenge in payments is preventing double-charging. We use a three-layer defense: request signing, idempotency keys, and database constraints."
4. Discuss Failure Modes
"What happens when the credit fails after debit succeeds? We need automatic refund mechanisms with their own idempotency guarantees."
5. Address Security
"Payment systems are high-value targets. We implement defense in depth: encryption, signing, fraud detection, and audit logging."
Key Takeaways

Key Takeaways Mindmap
The fundamentals:
- Payment systems are state machines. Every transaction has a clear state and defined transitions.
- Idempotency is non-negotiable. Three layers: cache, lock, database constraint.
- Failure is expected. Design for recovery, not just success.
The architecture:
4. Partition data by time. Most queries are recent; old data can be archived.
5. Async where possible. Users don't need to wait for credit confirmation.
6. Circuit breakers protect the system. One bank's failure shouldn't cascade.
The hard parts:
7. Timeouts are the hardest failure mode. Always check status; never retry blindly.
8. Reconciliation is your safety net. Compare your records with banks daily.
9. Security is multi-layered. Assume every layer can be breached.
What's Next?
In Part 2: Distributed Systems Deep Dive, we'll explore:
- Building distributed rate limiters for API protection
- Notification systems that handle 10M messages/hour
- Fraud detection pipelines with 100ms budgets
- Transaction reconciliation across multiple systems
Found this helpful? Share it with someone preparing for fintech interviews.