SyntaxPilot
Courses/System Design/Lesson 34
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

System Design · Lesson 34 of 40

Design UPI payments

queued

These are the notes for System Design episode 34. Asha buys a cutting chai at Ramu's stall for ₹20. She scans his QR code, types her PIN, and a few seconds later Ramu's speaker says "₹20 received", even though Asha banks with Alpha Bank and Ramu with Beta Bank. Today you design the system behind that moment: you'll write the requirements, find that wiring every app to every bank needs 28,120 connections and route everything through one central switch instead (743), stop a one-letter typo (KeyError: 'chaiwalla@beta') with a VPA that is validated before the PIN, stop a retry from charging Asha twice (960 → 980) with transaction IDs and idempotency, get back the ₹20 that vanished between two banks with a reversal, and turn NPCI's monthly number into 9,286 payments a second. Every demo is plain Python and runs as-is; outputs are real (Python 3.13). Alpha Bank, Beta Bank, Asha and Ramu are fictional; the number of apps (40), the balances and the 3x evening peak are our own assumptions; the real-world facts come only from the sources at the end.

UPI (Unified Payments Interface) is India's system for sending money instantly from one bank account to another using a phone. Example: scanning a shop's QR code and paying ₹20 from your bank account to theirs.

The problems

Problem What it teaches
Twenty rupees at the chai stall Requirements: any bank to any bank, seconds, never debit twice, never lose money
Every app to every bank Hub and spoke: one central switch (NPCI's UPI) instead of 28,120 links
One wrong letter VPAs, a directory lookup, address validation before the PIN
The retry that pays twice Timeouts, transaction IDs, idempotency, status checks
Debited, not credited Two steps on two banks; reversals; RBI's T+1 rule
The scale 2,407 crore a month → 9,286 a second
Put it all together App → switch → payer's bank → payee's bank, plus logs and reconciliation

Problem 0: twenty rupees at the chai stall (requirements)

Asha scans the QR code at Ramu's stall. Her account is at Alpha Bank. Ramu's account is at Beta Bank: a different bank with its own, separate computer system. A few seconds later Ramu's speaker announces the payment, exactly once.

A few words first:

  • A payer is the person paying (Asha); a payee is the person being paid (Ramu).
  • A debit takes money out of an account. Example: Alpha Bank debits ₹20 from Asha: 1000 → 980.
  • A credit puts money into an account. Example: Beta Bank credits ₹20 to Ramu: 0 → 20.
  • A QR code is a square barcode the phone camera reads; here it carries the payee's payment address so Asha doesn't have to type it.

Functional requirements:

  • Any app, any bank, to any bank: a payer at one bank can pay a payee at any other bank.
  • Pay to an address or a QR code, not a long account number.

Non-functional requirements:

  • Fast: done in seconds, at any hour, on any day.
  • Huge: hundreds of millions of payments a day.
  • Never debit twice. Never lose money.
  • Both banks agree on what happened.

For money, correctness comes before speed: a slow payment is annoying, but a double debit or a vanished ₹20 is unacceptable.

Problem 1: every app to every bank (a central switch)

Real life: railway junctions

Indian Railways Payments
A track from every town to every town: impossible to build Every app wired to every bank: each pair needs its own link
A big junction: every line connects there once A central switch: NPCI's UPI
Any station, any route: change at the junction PSP apps: any app reaches any bank through the switch
  • NPCI (National Payments Corporation of India) is the organisation that, in the Paytm blog's words, is "responsible for operating and managing the entire UPI infrastructure".
  • A PSP (payment service provider) is the company behind a payment app: PSPs "offer the mobile applications you use to make UPI payments" (Paytm blog). Example: the app Asha opens to scan the QR.
  • A switch is a central system that receives a message from one party and routes it to the right other party. Example: the UPI switch takes Asha's payment request and forwards the debit to Alpha Bank and the credit to Beta Bank.
  • Hub and spoke (general knowledge) is a design where everyone connects once to one central hub instead of to each other. Example: a courier company sending every parcel through one sorting centre.

"Every bank that offers UPI services has to integrate its own systems with NPCI's platform" (Paytm blog): one link per bank. 703 banks were live on UPI by 2025-26, up from 44 in 2016-17 (YourStory). The number of apps, 40, is our own assumption.

BANKS = 703                               # banks live on UPI (2025-26)
APPS = 40                                 # payment apps (our assumption)

direct = BANKS * APPS                     # every app wired to every bank
hub = BANKS + APPS                        # everyone wires to one switch
print(f"every app to every bank: {direct:,} connections")
print(f"through one central switch: {hub:,} connections")
print(f"a new bank joins: {APPS} new links, or just 1")

Output:

every app to every bank: 28,120 connections
through one central switch: 743 connections
a new bank joins: 40 new links, or just 1
  • Without a switch: 703 × 40 = 28,120 connections, each with its own agreement, testing and ways to fail.
  • With a switch: 703 + 40 = 743. A new bank builds one link, not forty.
  • The switch routes the messages; it doesn't hold the money. In the Paytm blog's words, "the money moves straight from your bank account to the recipient's bank account".

Problem 2: one wrong letter (VPAs and validation)

Who are we paying? For a normal bank transfer you need the payee's account number and IFSC code.

  • An account number identifies one bank account. Example: Ramu's account XXXX-0937 at Beta Bank (masked here, as apps do).
  • An IFSC code (Indian Financial System Code) identifies the bank branch that holds an account (general knowledge); a normal bank transfer needs it together with the account number.
  • A VPA (virtual payment address), also called a UPI ID, is a short address that stands for your bank account. A VPA can be used "instead of sharing your bank account number and IFSC code" (Paytm blog). Example (fictional): chaiwala@beta.
  • A directory is a lookup table from each VPA to its bank and account. Example: "chaiwala@beta" → ("Beta Bank", "XXXX-0937").
  • Resolving a VPA means looking it up in the directory to find where the money should go.
  • A KeyError is the error Python raises when you look up a key that isn't in a dictionary. Example: directory["chaiwalla@beta"] when only chaiwala@beta exists.
directory = {                             # VPA -> (bank, account)
    "asha@alpha":     ("Alpha Bank", "XXXX-4821"),
    "chaiwala@beta":  ("Beta Bank",  "XXXX-0937"),
}

def resolve(vpa):
    bank, account = directory[vpa]        # look the address up
    return f"{vpa} -> {bank}, account {account}"

print(resolve("chaiwala@beta"))           # Asha pays the chai stall
print(resolve("chaiwalla@beta"))          # one extra letter...

Output (file paths in the traceback shortened to main.py):

chaiwala@beta -> Beta Bank, account XXXX-0937
Traceback (most recent call last):
  File "main.py", line 11, in <module>
    print(resolve("chaiwalla@beta"))          # one extra letter...
          ~~~~~~~^^^^^^^^^^^^^^^^^^
  File "main.py", line 7, in resolve
    bank, account = directory[vpa]        # look the address up
                    ~~~~~~~~~^^^^^
KeyError: 'chaiwalla@beta'
  • The right address resolves to Beta Bank. One extra letter, the kind of typo anyone makes, crashes with KeyError: 'chaiwalla@beta': the address doesn't exist.
  • A crash is bad; silently paying the wrong person would be worse. And this check happens only after the payment has started. We need to check the address before any money moves.

The fix: validate before the PIN

  • Address validation means checking that a VPA exists, and showing the payee's registered name, before the payer approves the payment. Example: "pay Ramu Tea Stall (Beta Bank)?"
  • The UPI PIN is the secret number the payer types to approve a payment; it ensures "only you can approve payments from your account" (Paytm blog).
directory = {                             # VPA -> (registered name, bank)
    "asha@alpha":     ("Asha Verma",      "Alpha Bank"),
    "chaiwala@beta":  ("Ramu Tea Stall",  "Beta Bank"),
}

def validate(vpa):                        # BEFORE asking for the PIN
    if vpa not in directory:
        return f"{vpa}: invalid UPI ID, please check"
    name, bank = directory[vpa]
    return f"{vpa}: pay {name} ({bank})?"

print(validate("chaiwalla@beta"))         # typo caught, no money moved
print(validate("chaiwala@beta"))          # right shop: show the name

Output:

chaiwalla@beta: invalid UPI ID, please check
chaiwala@beta: pay Ramu Tea Stall (Beta Bank)?
  • The typo gets a clear message, and no money moved.
  • The right address shows the name, so Asha can see she's paying Ramu's stall, then types her PIN.
  • That's why your payment app shows the shop's name before asking for the PIN. Validation also catches an address that exists but belongs to the wrong person: the name on screen won't match.
  • NPCI's rules give address validation 8 seconds (cut from 10 s in an NPCI circular of 26 April 2025, effective 16 June 2025, as reported by Business Today).

Problem 3: the retry that pays twice (idempotency)

Real life: the spinner at the counter

At the chai stall What the system sees
Asha taps Pay; her bank debits ₹20 Step done: balance 980
The reply is lost on the stall's weak network The app sees a timeout: did it work or not?
The app tries again: "maybe it failed?" A second debit of ₹20: danger
  • A timeout is when a caller stops waiting for a reply after a fixed time. A timeout does not mean the request failed; it means "we don't know". Example: the debit worked, but the reply never arrived.
  • A retry is sending the same request again after a failure or timeout (episode 24 covered retries).
balance = {"asha": 1000}
seen = {}                                 # txn id -> result (for the fix)

def debit_naive(user, amount):
    balance[user] -= amount
    return "SUCCESS"

def debit(user, amount, txn_id):          # idempotent: same id, same result
    if txn_id in seen:
        return seen[txn_id]               # already done: don't debit again
    balance[user] -= amount
    seen[txn_id] = "SUCCESS"
    return "SUCCESS"

# the bank debits, but the reply is lost on a weak network; the app retries
debit_naive("asha", 20); debit_naive("asha", 20)
print("naive retry: balance", balance["asha"])

balance["asha"] = 1000
debit("asha", 20, "TXN501"); debit("asha", 20, "TXN501")
print("retry with the same txn id: balance", balance["asha"])

Output:

naive retry: balance 960
retry with the same txn id: balance 980
  • Naive retry: 960. Asha paid ₹40 for one chai.
  • Same transaction ID: 980. The second call finds TXN501 in seen and returns the saved result without debiting again: charged exactly once.

The words:

  • A transaction ID is a unique name given to one payment when it's created, and reused on every retry of that payment. Example: TXN501.
  • Idempotency (general knowledge) means doing the same request twice has the same effect as doing it once. Example: debit("asha", 20, "TXN501") twice takes ₹20, not ₹40.
  • A status check is asking "what happened to this transaction ID?" instead of blindly retrying. Example: the app asks about TXN501 and hears SUCCESS, so it shows "Paid" and does nothing more.

Every UPI payment carries a unique transaction ID for exactly this. NPCI's rules now require an answer to a transaction status check within 10 seconds (cut from 30 s, same circular, Business Today).

Problem 4: debited, not credited (reversals)

A payment is two steps on two banks: a debit at Asha's bank, then a credit at Ramu's. What if Ramu's bank is down?

balance = {"asha": 1000, "chaiwala": 0}
beta_bank_up = False                      # the payee's bank is down

def pay(payer, payee, amount):
    balance[payer] -= amount              # step 1: debit at Asha's bank
    print("debited", payer, amount)
    if not beta_bank_up:                  # step 2: credit at the other bank
        print("credit FAILED at Beta Bank")
        return "FAILED"
    balance[payee] += amount
    return "SUCCESS"

print(pay("asha", "chaiwala", 20), balance)

Output:

debited asha 20
credit FAILED at Beta Bank
FAILED {'asha': 980, 'chaiwala': 0}
  • Asha has 980, Ramu has 0: ₹20 has vanished.
  • Why? The two steps run on two different banks' computers, so one can succeed while the other fails. A database transaction (all-or-nothing changes inside one database, episode 9) can't cover both, because there is no single database that holds both banks' accounts.

Real life: the returned courier

Sending a courier A UPI payment
You hand over the parcel: it has left your hands Debit: Asha's bank takes ₹20 (step 1)
The house is locked: nobody can receive it Credit fails: Beta Bank is down (step 2 fails)
Return to sender: the parcel comes back Reversal: ₹20 back to Asha (undo step 1)
  • A reversal is a step that undoes an earlier debit by crediting the money back to the payer. Example: credit failed, so Alpha Bank puts ₹20 back in Asha's account.
  • The rule (general knowledge): every step that moves money needs an undo step.
balance = {"asha": 1000, "chaiwala": 0}
beta_bank_up = False

def pay(payer, payee, amount):
    balance[payer] -= amount              # step 1: debit
    if not beta_bank_up:                  # step 2: credit fails...
        balance[payer] += amount          # ...so undo step 1: a reversal
        print("credit failed -> reversed", amount, "to", payer)
        return "FAILED"
    balance[payee] += amount
    return "SUCCESS"

print(pay("asha", "chaiwala", 20), balance)

Output:

credit failed -> reversed 20 to asha
FAILED {'asha': 1000, 'chaiwala': 0}

The payment failed, but no money vanished: Asha is back to 1000.

It's also the rule. RBI circular RBI/2019-20/67 (20 September 2019), for UPI, case "Account debited but the beneficiary account is not credited": "auto reversal (R) by the Beneficiary bank latest on T + 1 day", and "₹100/- per day if delay is beyond T + 1 day".

  • RBI (Reserve Bank of India) is India's central bank, which sets rules for banks.
  • The beneficiary is the person who receives the money (the payee, Ramu).
  • T + 1 means the transaction day (T) plus one day. Example: a failed payment on Monday must be reversed by Tuesday at the latest.
  • TAT (turnaround time) is the deadline for resolving a case; the circular "harmonises" these deadlines.

NPCI's rules also give transaction reversals 10 seconds (cut from 30 s, Business Today).

Problem 5: the scale

NPCI's numbers for September 2026 (FinTech BizNews): "UPI processed 2,407 crore transactions valued at Rs 29.37 lakh crore". A crore is 10 million (1,00,00,000) and a lakh is 100,000 (Indian number words).

month = 2_407 * 10**7                     # UPI, September 2026 (NPCI)
per_day = month / 30
per_second = per_day / 86_400
print(f"per day: {per_day / 1e6:,.0f} million")
print(f"per second, on average: {per_second:,.0f}")
print(f"at a 3x evening peak (our guess): {per_second * 3:,.0f}")

Output:

per day: 802 million
per second, on average: 9,286
at a 3x evening peak (our guess): 27,859
  • 2,407 crore = 24,070 million a month; ÷ 30 days = 802 million a day; ÷ 86,400 seconds = 9,286 a second on average.
  • Evenings are busier than nights. At our assumed 3x peak: nearly 28,000 a second.
  • Every one of them is validated, debited, credited, made idempotent and logged. So each bank and the switch run many servers side by side (horizontal scaling, episode 5), with strict time limits for every step: NPCI cut the time for a pay request from 30 seconds to 15 (Business Today).
  • TPS (transactions per second) is the usual unit for this. Example: 9,286 TPS on average.

The full design

  payer app (PSP)            UPI switch (NPCI)            payer's bank        payee's bank
  ───────────────            ─────────────────            ────────────        ────────────
  scan QR / type VPA ──────▶ validate address ──────────▶ (directory)
  show "Ramu Tea Stall" ◀─── name, bank
  PIN + txn id TXN501 ─────▶ pay request ───────────────▶ check PIN, debit
                                                 ◀─────── debited
                             credit ──────────────────────────────────────────▶ credit
                                                 ◀──────────────────────────── credited (or failed → reversal)
  "Paid" ◀────────────────── result for TXN501
  timeout? status check(TXN501) ──▶ stored result
                                                        every step logged → end-of-day reconciliation
  1. The payer's PSP app reads the QR or the typed VPA and asks the switch to validate it; the app shows the payee's name.
  2. The app creates a unique transaction ID and sends the pay request with the payer's UPI PIN to the UPI switch.
  3. The switch asks the payer's bank to check the PIN and debit (idempotently, by transaction ID).
  4. The switch asks the payee's bank to credit.
  5. If the credit fails, the debit is reversed: by T + 1 at the latest under RBI's rule.
  6. On a timeout, the app does a status check by transaction ID, never a blind second debit.
  7. Every step is written to a log. At the end of the day, banks compare their records with the switch's: reconciliation catches anything the live system missed.
  • A log here is an append-only record of every step: "TXN501 debit 20 at Alpha Bank, 10:02:03".
  • Reconciliation (general knowledge) means comparing two sets of records of the same events and fixing every difference. Example: Beta Bank's records show a credit for a transaction that the switch still marks as pending; reconciliation marks it as successful.

The whole chain

  1. 28,120 app-to-bank links → one switch: 743 (hub and spoke).
  2. One wrong letter → KeyError → a VPA plus validation before the PIN.
  3. A retry debits twice (960) → transaction IDs and idempotency (980), plus status checks.
  4. ₹20 vanished between two banks → a reversal (RBI: by T + 1, ₹100/day after).
  5. 9,286 a second → many servers, strict time limits for every step.
  6. App, switch, two banks, logs, reconciliation.

Common mistakes (and the real outputs)

Mistake What you see Why Fix
directory[vpa] with a typo KeyError: 'chaiwalla@beta' The address doesn't exist Validate first, show the name
Retry the debit after a timeout naive retry: balance 960 The first debit had worked Same transaction ID + status check
Retry with a new transaction ID retry with a new txn id: balance 960 A new ID looks like a new payment Create the ID once, reuse it on every retry
Debit, then credit, nothing else FAILED {'asha': 980, 'chaiwala': 0} Step 2 failed on another bank Reverse the debit
Assume the reversal always works PENDING: reversal queued {'asha': 980, 'chaiwala': 0} (Practice 2) The payer's bank can be down too Queue the reversal, retry it with the same ID, reconcile
Treat a timeout as "failed" The user is told it failed, but the money left A timeout means "unknown", not "failed" Mark PENDING, check status, settle at reconciliation

Mini project: a tiny UPI switch

A VPA directory with validation, two banks with idempotent debits (one step per transaction ID), transaction IDs with status checks, a reversal when the credit fails, a lost reply, and an end-of-day reconciliation, in under 80 lines:

# Mini project: a tiny UPI switch. A VPA directory with validation, two banks
# with idempotent debits, transaction IDs with status checks, a reversal when
# the credit fails, and end-of-day reconciliation. One process, fake money.
class Bank:
    def __init__(self, name, accounts):
        self.name, self.accounts, self.up = name, accounts, True
        self.ledger = {}                      # (txn id, step) -> amount
        self.lose_reply = False               # simulate a lost reply once
    def apply(self, txn, step, account, amount):
        if not self.up:
            raise ConnectionError(f"{self.name} is down")
        if (txn, step) not in self.ledger:    # idempotent: once per id + step
            if step == "debit" and self.accounts[account] < amount:
                raise ValueError("insufficient balance")
            sign = -1 if step == "debit" else 1
            self.accounts[account] += sign * amount
            self.ledger[(txn, step)] = sign * amount
        if self.lose_reply:
            self.lose_reply = False
            raise TimeoutError("reply lost")

class Switch:
    def __init__(self, banks, directory):
        self.banks, self.directory, self.status = banks, directory, {}
    def validate(self, vpa):
        if vpa not in self.directory:
            return None
        name, bank, _ = self.directory[vpa]
        return f"{name} ({bank})"
    def pay(self, txn, payer, payee, amount):
        if txn in self.status:                # a retry: same id, same answer
            return self.status[txn]
        _, pbank, pacct = self.directory[payer]
        _, qbank, qacct = self.directory[payee]
        try:
            self.banks[pbank].apply(txn, "debit", pacct, amount)
        except ValueError:
            self.status[txn] = "DECLINED"
            return "DECLINED"
        try:
            self.banks[qbank].apply(txn, "credit", qacct, amount)
            self.status[txn] = "SUCCESS"
        except ConnectionError:
            self.banks[pbank].apply(txn, "reversal", pacct, amount)
            self.status[txn] = "REVERSED"
        except TimeoutError:
            self.status[txn] = "PENDING"      # don't guess: settle it later
        return self.status[txn]
    def reconcile(self):                      # end of day: banks vs switch
        for txn, said in self.status.items():
            steps = {s for b in self.banks.values() for (t, s) in b.ledger if t == txn}
            truth = ("SUCCESS" if steps == {"debit", "credit"} else
                     "REVERSED" if "reversal" in steps else "DECLINED")
            mark = "ok" if truth == said else f"MISMATCH -> fix to {truth}"
            print(f"  {txn}: switch {said:<8} banks {sorted(steps)} {mark}")
            self.status[txn] = truth

alpha = Bank("Alpha Bank", {"XXXX-4821": 1000})
beta = Bank("Beta Bank", {"XXXX-0937": 0})
upi = Switch({"Alpha Bank": alpha, "Beta Bank": beta},
             {"asha@alpha": ("Asha Verma", "Alpha Bank", "XXXX-4821"),
              "chaiwala@beta": ("Ramu Tea Stall", "Beta Bank", "XXXX-0937")})

print("validate chaiwalla@beta:", upi.validate("chaiwalla@beta"))
print("validate chaiwala@beta: ", upi.validate("chaiwala@beta"))
print("TXN1:", upi.pay("TXN1", "asha@alpha", "chaiwala@beta", 20))
print("TXN1 retry:", upi.pay("TXN1", "asha@alpha", "chaiwala@beta", 20))
beta.up = False
print("TXN2:", upi.pay("TXN2", "asha@alpha", "chaiwala@beta", 20))
beta.up = True
print("TXN3:", upi.pay("TXN3", "asha@alpha", "chaiwala@beta", 5000))
beta.lose_reply = True
print("TXN4:", upi.pay("TXN4", "asha@alpha", "chaiwala@beta", 30))
print("status check TXN4:", upi.status["TXN4"])
print("balances:", alpha.accounts, beta.accounts)
print("end-of-day reconciliation:")
upi.reconcile()
print("status check TXN4:", upi.status["TXN4"])

Output:

validate chaiwalla@beta: None
validate chaiwala@beta:  Ramu Tea Stall (Beta Bank)
TXN1: SUCCESS
TXN1 retry: SUCCESS
TXN2: REVERSED
TXN3: DECLINED
TXN4: PENDING
status check TXN4: PENDING
balances: {'XXXX-4821': 950} {'XXXX-0937': 50}
end-of-day reconciliation:
  TXN1: switch SUCCESS  banks ['credit', 'debit'] ok
  TXN2: switch REVERSED banks ['debit', 'reversal'] ok
  TXN3: switch DECLINED banks [] ok
  TXN4: switch PENDING  banks ['credit', 'debit'] MISMATCH -> fix to SUCCESS
status check TXN4: SUCCESS
  • The retry of TXN1 charged nothing extra, and the balances add up: Asha 1000 − 20 (TXN1) − 20 + 20 (TXN2, reversed) − 30 (TXN4) = 950; Ramu 20 + 30 = 50. No rupee was created or lost.
  • TXN4's credit worked, but the reply was lost, so the switch honestly said PENDING instead of guessing "failed" (which would have made Asha pay again) or "success" (which it couldn't know).
  • Reconciliation found the mismatch by comparing the switch's status with both banks' ledgers, and fixed TXN4 to SUCCESS: exactly the kind of error only an end-of-day comparison can catch.

Try extending it: make Alpha Bank go down while Beta Bank is also down (the reversal itself fails), and add a queue of reversals to retry; then give each payment a deadline and print which reversals are past T + 1.

Practice

  1. Homework: in the RETRY demo, retry three times. What are the two balances?
  2. Homework: in the REVERSE demo, make the reversal fail too (Asha's bank is down as well). What would you do?
  3. Homework: in the SCALE demo, use a 5x peak instead of 3x.
  4. Homework (comment): what kind of mistake can only end-of-day reconciliation catch?
  5. In the SWITCH demo, use 60 apps instead of 40. How many connections in each case?
  6. Add a status(txn_id) function to the RETRY demo, and use it for the quiz's TXN777.
  7. Why does the app validate the VPA before asking for the PIN, not after?
  8. Why is "debit again with a new transaction ID" just as bad as a naive retry?
Solutions and hints

1. Call each function a third time: debit_naive("asha", 20) three times and debit("asha", 20, "TXN501") three times. Output:

naive retry: balance 940
retry with the same txn id: balance 980

The naive version takes ₹60 for one chai. The idempotent one still takes ₹20, however many retries.

2. Add a second flag for Asha's bank and a queue of reversals still owed, then retry them (same transaction ID) when the bank is back:

balance = {"asha": 1000, "chaiwala": 0}
beta_bank_up = False
alpha_bank_up = False                     # now Asha's bank is down too
pending = []                              # reversals still owed

def pay(payer, payee, amount, txn_id):
    balance[payer] -= amount              # step 1: debit
    if not beta_bank_up:                  # step 2: credit fails...
        if alpha_bank_up:
            balance[payer] += amount      # ...reversal works
            return "FAILED, reversed"
        pending.append((txn_id, payer, amount))   # ...reversal fails too
        return "PENDING: reversal queued"
    balance[payee] += amount
    return "SUCCESS"

print(pay("asha", "chaiwala", 20, "TXN601"), balance)

alpha_bank_up = True                      # later: retry with the same id
for txn_id, user, amount in pending:
    balance[user] += amount
    print("reversed", txn_id, amount, "to", user)
pending.clear()
print(balance)

Output:

PENDING: reversal queued {'asha': 980, 'chaiwala': 0}
reversed TXN601 20 to asha
{'asha': 1000, 'chaiwala': 0}

Never drop a reversal: record it, mark the payment PENDING (not "failed", not "success"), keep retrying with the same transaction ID so a retry can't refund twice, and let reconciliation catch anything still open. Under RBI's rule the deadline is T + 1; after that the bank pays ₹100 a day.

3. Change the last line to per_second * 5 (and its label). Output:

per day: 802 million
per second, on average: 9,286
at a 5x peak (our guess): 46,431

The average doesn't change; the system must be sized for the peak, here over 46,000 a second (with our assumed 5x).

4. Mistakes where the live system believes something different from what actually happened: a credit that succeeded but whose reply was lost (the switch says pending, the bank says credited, like TXN4 in the mini project); a reversal that was recorded but never applied; a bug that logged a payment twice; a server that crashed between two steps. No single live request sees both sides; comparing the full records of the banks and the switch does.

5. Change APPS = 40 to APPS = 60. Output:

every app to every bank: 42,180 connections
through one central switch: 763 connections
a new bank joins: 60 new links, or just 1

Direct links grow with banks × apps; links to a switch grow with banks + apps.

6.

balance = {"asha": 1000}
seen = {}                                 # txn id -> result

def debit(user, amount, txn_id):
    if txn_id in seen:
        return seen[txn_id]
    balance[user] -= amount
    seen[txn_id] = "SUCCESS"
    return "SUCCESS"

def status(txn_id):                       # "what happened to this id?"
    return seen.get(txn_id, "NOT FOUND")

debit("asha", 500, "TXN777")              # worked, but the reply was lost
print("status TXN777:", status("TXN777"))
print("status TXN778:", status("TXN778"))
print("balance", balance["asha"])

Output:

status TXN777: SUCCESS
status TXN778: NOT FOUND
balance 500

The app now knows TXN777 went through and shows "Paid", without touching the money again.

7. After the PIN the money starts moving. Validating first means a typo or a wrong person is caught while nothing has happened yet, and the payer sees the name and can stop. Undoing a payment (a reversal, or asking a stranger to send it back) is much harder than not making it.

8. The bank decides "is this the same payment?" by the transaction ID. A new ID looks like a brand-new payment, so it's debited again. Real output, changing the second call in the RETRY demo to "TXN502": retry with a new txn id: balance 960. Create the ID once, when the payment is created, and reuse it.

Quick quiz

Pay ₹500, txn id TXN777
... no reply after 15 seconds ...
balance unknown

The app timed out. What now?

  • A. Debit again with a new ID
  • B. Tell Asha it failed
  • C. Check the status of TXN777
  • D. Ask Asha to pay in cash
Answer

C. The first debit may have worked. Ask about the same transaction ID; if you must retry, reuse TXN777 so it can't debit twice. A new ID could charge her twice (our demo: balance 960), and saying it failed could be a lie.

Interview questions: "Design UPI / a payment system"

1. Clarify requirements. Who pays whom: person to person, person to shop? Between different banks? How do payers identify payees (account number, address, QR)? Expected volume and peak? Time limits? What happens on failure? Then state: any bank to any bank, pay to an address or QR, done in seconds at any hour, never debit twice, never lose money, both sides agree.

2. Estimate. "2,407 crore a month (NPCI, September 2026) is 802 million a day, about 9,300 a second on average; I'll design for a few times that at peak (our guess: 3x, nearly 28,000 a second). If each payment record is about 1 KB (our assumption), that's roughly 800 GB of records a day, kept for years."

3. Components.

  • PSP apps: QR scanning, VPA entry, show the payee's name, collect the PIN, create the transaction ID.
  • Central switch: hub and spoke; routes validation, pay, status-check and reversal messages; stores the status of every transaction ID.
  • Directory: VPA → bank and account, used for address validation.
  • Banks: verify the PIN, debit and credit idempotently (one effect per transaction ID and step), reverse on failure.
  • Logs and reconciliation: append-only records at every party; end-of-day comparison.

4. The hard parts. Idempotency by transaction ID; timeouts treated as "unknown" with status checks; reversals for every debit whose credit fails; strict per-step time limits (validation 8 s, status check 10 s, reversal 10 s, pay request 15 s under NPCI's 2025 circular); reconciliation.

5. Scale and reliability (general knowledge). Many stateless servers behind load balancers; partition the transaction store by transaction ID; replicate it so a crashed server loses nothing; rate-limit and protect banks that are slow (episode 19); alert when a bank's failure rate jumps.

Common follow-ups:

  • What if the app crashes after the debit? (The transaction ID and its status live at the switch and banks, not in the app; a status check on reopening finds it.)
  • Why not one big database transaction across both banks? (They're separate systems run by separate organisations; there's no single database. Use steps plus reversals plus reconciliation instead.)
  • How do you stop a double credit on retry? (The payee's bank applies one credit per transaction ID, just like the debit.)
  • What if the reversal fails? (Queue it, retry with the same ID, mark PENDING, reconcile; RBI's deadline is T + 1.)
  • Why show the payee's name before the PIN? (Catches typos and wrong people before any money moves.)

Glossary

Term Meaning
UPI Unified Payments Interface: India's system for instant bank-to-bank payments from a phone
NPCI National Payments Corporation of India, which operates and manages the UPI infrastructure
RBI Reserve Bank of India, India's central bank, which sets rules for banks
PSP Payment service provider: the company that offers the payment app you use
Payer / payee The person paying / the person being paid
Beneficiary The person who receives the money (the payee)
Debit Taking money out of an account
Credit Putting money into an account
QR code A square barcode the camera reads; here it carries the payee's address
Account number The number that identifies one bank account
IFSC code Indian Financial System Code: identifies the bank branch holding an account
VPA / UPI ID Virtual payment address, e.g. chaiwala@beta, standing in for an account number and IFSC
Directory A lookup table from VPA to bank and account
Resolve Look up a VPA to find where the money should go
KeyError Python's error for looking up a key that isn't in a dictionary
Address validation Checking a VPA exists and showing the payee's name before the PIN
UPI PIN The secret number that approves a payment from your account
Switch A central system that routes messages between the right parties
Hub and spoke Everyone connects once to a central hub instead of to each other
Timeout Giving up waiting for a reply; the result is unknown, not failed
Retry Sending the same request again after a failure or timeout
Transaction ID A unique name for one payment, reused on every retry, e.g. TXN501
Idempotency Doing the same request twice has the same effect as once
Status check Asking "what happened to this transaction ID?" instead of retrying blindly
Database transaction All-or-nothing changes inside one database
Reversal Undoing a debit by crediting the money back to the payer
PENDING A payment whose outcome isn't known yet; settled by status checks or reconciliation
T + 1 The transaction day plus one day; RBI's deadline for auto-reversal
TAT Turnaround time: the deadline for resolving a case
Log An append-only record of every step
Reconciliation Comparing two sets of records of the same events and fixing every difference
Crore / lakh 10 million / 100,000
TPS Transactions per second
Peak The busiest period's load, here assumed 3x the average

Summary

  • A payment system must be correct before fast: never debit twice, never lose money, both banks agree; then done in seconds, at huge scale.
  • One central switch (hub and spoke, NPCI's UPI) instead of every app wired to every bank: 28,120 → 743 connections. The switch routes messages; the money moves bank to bank.
  • A VPA replaces the account number and IFSC; validating it before the PIN turns KeyError: 'chaiwalla@beta' into "invalid UPI ID, please check" and shows "pay Ramu Tea Stall (Beta Bank)?".
  • A timeout means unknown. A unique transaction ID makes the debit idempotent (960 → 980), and a status check asks what happened instead of retrying blindly.
  • Debit and credit are two steps on two banks; when the credit fails, a reversal puts the money back (RBI: by T + 1, ₹100/day after), and end-of-day reconciliation catches whatever the live system missed.
  • 2,407 crore transactions in September 2026 = 802 million a day = 9,286 a second on average.

Next episode: it's 10 am, Tatkal booking opens, and lakhs of people want the same few hundred seats at the same second. Design IRCTC Tatkal booking.

Sources: FinTech BizNews, 1 Oct 2026, citing NPCI: "UPI processed 2,407 crore transactions valued at Rs 29.37 lakh crore in September 2026". YourStory, Aug 2026 ("UPI completes 10 years"): UPI launched 25 August 2016; 703 banks by 2025-26, up from 44 in 2016-17. Paytm blog, "The Technology Stack: How UPI Powers Your Scan & Pay Transactions": PSPs "offer the mobile applications you use to make UPI payments"; NPCI is "responsible for operating and managing the entire UPI infrastructure"; "Every bank that offers UPI services has to integrate its own systems with NPCI's platform"; a VPA can be used "instead of sharing your bank account number and IFSC code"; the UPI PIN ensures "only you can approve payments from your account"; "the money moves straight from your bank account to the recipient's bank account". Business Today, 17 Jun 2025, citing an NPCI circular of 26 Apr 2025 (effective 16 Jun 2025): request pay 30 s → 15 s; transaction status checks 30 s → 10 s; transaction reversals 30 s → 10 s; address validation 10 s → 8 s. RBI circular RBI/2019-20/67 (20 Sep 2019, "Harmonisation of TAT ..."), UPI row 4a, "Account debited but the beneficiary account is not credited": "auto reversal (R) by the Beneficiary bank latest on T + 1 day"; "₹100/- per day if delay is beyond T + 1 day". The number of payment apps (40), the bank names, people, balances, the 1 KB record size and the 3x and 5x peaks are our own stated assumptions; idempotency, reversals, reconciliation and hub and spoke are general textbook knowledge.