Every company that sells something eventually asks this question: Stripe, Amazon, Uber, Flipkart, PhonePe and Razorpay all report it. Unlike a like count, money can't be “roughly right”. The design is less about huge scale and more about correctness when things fail: timeouts, retries, duplicate messages, crashed servers and banks that answer late.
Step 1 · Requirements
- Functional: a customer pays a merchant (card, UPI, wallet); see payment status; refunds (full or partial); merchants get paid out (settlement); payment history.
- Non-functional: never charge twice and never lose a payment; strongly consistent records; every change auditable; highly available checkout; secure (card data, fraud).
- Out of scope (say it): building our own card network or bank; detailed fraud models; currency exchange; tax and invoicing.
Step 2 · Estimates
- Volume: 10 million payments a day ≈ 115/s on average, with sale-day peaks maybe 20× higher (≈ 2,500/s).
- Data: a payment plus its ledger rows ≈ 2 KB → 20 GB a day, a few TB a year. Easy for a well-indexed relational database, kept for many years for audits.
- The real constraint: not size but correctness and the speed of outside providers (a bank or UPI call can take seconds).
Step 3 · API
POST /payments Idempotency-Key: 7c1e…
{ orderId: "ord_77", amount: 50000, currency: "INR", method: "upi" } // amounts in paise, never floats
→ { paymentId: "pay_1", status: "pending", nextAction: { upiIntentUrl } }
GET /payments/{id} → { status: "succeeded" | "failed" | "pending", ... }
POST /payments/{id}/refunds Idempotency-Key: … { amount: 20000 } → { refundId, status }
POST /webhooks/provider (signed, from the gateway) → 200 after it is safely recordedStep 4 · Design
Rule 1: retries must never charge twice
🎮 The retry that charges twice
Timeouts don't tell you whether the payment happened. Retrying is right; retrying without an idempotency key is what charges people twice. The ledger shows the other rule: every payment writes equal debits and credits, so money is never created or lost.
-- Idempotency: a unique key makes the second insert fail, so only one attempt proceeds
INSERT INTO idempotency_keys (key, merchant_id, request_hash, status)
VALUES ('7c1e…', 'm_42', 'sha256(body)', 'in_progress'); -- duplicate key → look up the stored result instead
-- ...call the provider, update the payment...
UPDATE idempotency_keys SET status = 'done', response = '{"paymentId":"pay_1",...}' WHERE key = '7c1e…';The same idea protects every hop: your service sends its own idempotency key to the provider, and webhook and queue handlers check “have I already applied this event?” before acting. If the same key arrives with a different request body, reject it: that's a bug, not a retry.
Rule 2: a payment only moves forward
created ──► pending ──► succeeded ──► partially_refunded ──► refunded
└──────► failed
-- Apply a webhook only if the move is allowed:
UPDATE payments SET status = 'succeeded' WHERE id = 'pay_1' AND status = 'pending'; -- 0 rows = already handledRule 3: money is never created or destroyed
| Entry | Account | Debit | Credit |
|---|---|---|---|
| Riya pays ₹500 | Customer funds (via provider) | ₹500 | |
| Merchant payable: ChaiPoint | ₹500 | ||
| Our ₹10 fee | Merchant payable: ChaiPoint | ₹10 | |
| Platform revenue | ₹10 | ||
| Total | ₹510 | ₹510 |
Ledger rows are never updated or deleted. A refund is a new pair of entries in the opposite direction. Balances are sums of entries (cached for speed), and the rule “debits = credits” is checked constantly.
Step 5 · Scale and reliability
- Strong consistency: payments and ledger live in a relational database with transactions. Shard by merchant ID when one database isn't enough, keeping each payment's rows on one shard.
- Webhooks plus polling: verify the webhook signature, store the event, reply 200 quickly, and process it from a queue. A job also polls the provider for payments stuck in pending, because webhooks can be late or lost.
- Outbox pattern: write “payment succeeded” to an outbox table in the same transaction as the state change; a relay publishes it to the message queue. Orders, emails and payouts never miss it.
- Reconciliation: every day, match ledger entries with the provider's settlement report line by line. Auto-fix known cases (for example, refund a payment that succeeded after the order was cancelled); send the rest to finance.
- Security: the gateway collects card details and returns a token, keeping you out of most PCI DSS scope; encrypt sensitive data; rate-limit and run fraud checks before calling the provider.
- Many providers: route through more than one gateway, so if one is down or slow, new payments go to another. Never switch providers mid-payment.
- Money as integers: store paise (or cents) as whole numbers with a currency code. Floating-point maths can turn ₹0.10 + ₹0.20 into 0.30000000000000004.
🧠 PATH memory card
Remember the payment system design for good
Picture it · Anchor it · Trace it · Hit-recall it. Four quick steps that turn “I read it once” into “I can explain it in an exam”.
- P
Picture it
Your brain remembers scenes far better than definitions.
← swipe to see the whole picture →
A careful kirana shopkeeper gives every sale a bill number. If a customer comes back saying “did my payment go through?”, he checks that bill number instead of taking money again. Each bill gets stamps in order: unpaid, then paid, then maybe refunded, never backwards. Every rupee goes into a two-column khata book, money in and money out, and he never rubs anything out. Each evening he tallies the khata against his bank passbook.
- A
Anchor it
A silly sentence you can't forget, where every word maps to the concept.
“Bill number, Stamps, Khata, Evening tally”
- Bill number→Idempotency key: retries return the same result
- Stamps in order→Payment state machine; only valid forward moves
- Two-column khata→Append-only double-entry ledger; debits = credits
- Never rub out→Refunds and fixes are new entries
- Evening tally→Daily reconciliation with the provider's settlement file
- T
Trace it
Run it by hand on a tiny example once. Doing beats reading.
Riya taps Pay ₹500 for chai. The app sends key7c1e; the payment service createspay_1(pending) and opens a UPI request. Her network drops, the app retries with7c1eand gets backpay_1, no second charge. She approves in her UPI app; the provider's webhook arrives twice. The first moves pending → succeeded and writes debit ₹500 / credit ₹500 plus an outbox event; the second finds it already succeeded and does nothing. That night, reconciliation findspay_1in the bank file. ✓ - H
Hit-recall it
Test yourself now, then again on the day each card comes back.
Card 1 / 8 · new0 mastered · 0 practisedSay the answer out loud first, then flip and be honest.
Follow-up questions interviewers ask
- “Payment succeeded but the order service was down?” The outbox event waits in the queue and is delivered when it recovers; reconciliation catches anything that still slips.
- “How do merchants get paid?” A payout job sums each merchant's payable balance from the ledger, sends a bank transfer with its own idempotency key, and writes the payout entries.
- “A user disputes a card charge (chargeback)?” It's another state and another set of ledger entries: hold the amount from the merchant's balance while the dispute is reviewed.
You've finished the course 🎉
That's seventeen parts: the READS framework, then sixteen famous questions, from a URL shortener to a payment system that never loses a rupee. Notice how the same blocks kept returning: caches, queues, consistent hashing, quorums, idempotency, atomic updates and append-only logs. That's the real skill interviewers test. Go back to the course page to review with the flashcards, or sharpen the algorithms underneath in the DSA course.
Key takeaways
- ✓Send an idempotency key with every payment and refund; retries return the stored result.
- ✓Payments follow a forward-only state machine, updated with conditional writes.
- ✓Record money in an append-only double-entry ledger where debits always equal credits.
- ✓Trust webhooks only after verifying them, process them idempotently, and poll for stuck payments.
- ✓Reconcile daily with provider files, use tokens instead of card numbers, and store amounts as integers.
Frequently asked questions
What is an idempotency key in payments?
A unique ID the client creates for one payment attempt and sends with the request (often as an Idempotency-Key header). The server stores the key with the result. If the same request arrives again, for example after a timeout and retry, the server returns the saved result instead of charging again.
What is a double-entry ledger?
An accounting record where every movement of money is written as at least two entries that balance: a debit from one account and an equal credit to another. Entries are only ever added, never edited. If the totals of debits and credits don't match, something is wrong, which makes errors easy to detect and audit.
What is payment reconciliation?
Regularly comparing your own records with the records of banks and payment providers (their settlement files or reports) to find mismatches: payments you think succeeded but the bank didn't settle, money received with no matching order, or amounts that differ. Mismatches are fixed automatically where possible or sent to a finance team.
Should a payment system store card numbers?
Almost never. Storing card numbers brings strict PCI DSS security rules. Most companies let the payment gateway collect card details and store only a token that represents the card. In India, RBI card-on-file tokenisation rules also stop merchants from storing full card numbers.
Why do payment systems use webhooks?
Many payments finish later and somewhere else: the user approves a UPI request in another app, or a bank completes 3-D Secure. The payment provider calls your webhook URL when the final status is known. Webhooks can be delayed, repeated or arrive out of order, so handlers check signatures, are idempotent and only move a payment forward through valid states.
🧠 Quick check: payment systems
1. The ‘Pay’ request times out. Did the payment happen?
2. A refund of ₹200 is needed. How should the ledger change?
3. The same ‘payment succeeded’ webhook arrives three times. What should happen?
4. Your records say ₹10,000 succeeded today; the bank's settlement file says ₹9,500. What finds this?
Checking your access…