Skip to content

Design a Real-Time Payment Network (UPI and Card Rails)

Advanced 101 min read Part 17 of 18

Design a national real-time payment switch like UPI plus card rails: routing, VPA lookup, clearing and settlement, reversals, fraud and 24/7 availability.

The Problem#

When you pay a shop with a card or scan a QR code with a payment app, the money looks like it moves straight from your bank to the shop's bank. It does not. Between them sits a payment network: a shared switch that every bank and payment app plugs into, so that any customer of any bank can pay any customer of any other bank, in seconds, at any hour.

The separate payment system case study designs a payment service provider (a Stripe-like company that helps merchants accept money). This case study goes one level lower. We design the rail itself: the network that the payment service providers, banks and apps connect to. There are two families of rails, and we cover both:

  1. A real-time account-to-account network, modelled on India's Unified Payments Interface (UPI). A customer types a short address such as asha@okbank, or scans a QR code, enters a PIN, and the money leaves their bank account and lands in the other person's bank account within seconds. UPI is run by the National Payments Corporation of India (NPCI) and, per its Wikipedia article, handled about 20 billion transactions in August 2025 (an average of nearly 7,500 per second), which is more than 640 million a day.
  2. A card network, modelled on Visa and Mastercard. A card is tapped at a terminal, the request flows from the shop's bank through the network to the card owner's bank, which approves or declines it in well under two seconds. The money actually moves later, in batches, through clearing and settlement.

Four things make this hard:

  1. Many independent parties. A single payment touches the payer's app, the payer's bank, the switch, the payee's app and the payee's bank. Each is a separate company with its own computers, its own outages and its own clock. No single database holds "the truth".
  2. Money cannot be lost, created or moved twice. At national scale, a bug that double-debits one in a million payments hurts hundreds of people every day. Every step must be idempotent, every outcome must eventually be known, and every party's books must agree at the end of the day.
  3. The network must never stop. A national rail is critical infrastructure. People buy food, pay for taxis and pay for medicine with it. Downtime of a few minutes makes the news; a five-hour outage is a national event.
  4. Fraud and abuse. Instant, irreversible payments are exactly what fraudsters want. The network must score risk in milliseconds, without becoming slow or blocking honest payments.

An analogy. Think of a national postal sorting hub for money. Every bank is a post office. Customers hand a letter ("pay ₹500 to this address") to their own post office. That office sends it to the central hub. The hub reads the address, looks up which post office serves it, and forwards it. The receiving office delivers it and sends back a signed receipt. The hub never holds the customers' money; it only routes letters and keeps a register of every letter. At the end of each day, the hub adds up how much each post office owes every other one and asks the central bank to move only the net amounts between their accounts. That last step, settling the net amount, is why billions of payments a month need only a handful of real money movements between banks each day.

Background: a few terms used in this design#

  • Issuer. The bank that gave the customer their card or holds their account. It decides whether a payment from that account is allowed ("Does Asha have the money? Is this really Asha?").
  • Acquirer. The bank (or processor) that signs up the merchant and receives card payments on the merchant's behalf. In account-to-account systems the equivalent is the beneficiary bank: the bank that receives the money.
  • Remitter bank and beneficiary bank. In UPI language, the remitter bank holds the payer's account (money goes out); the beneficiary bank holds the payee's account (money comes in).
  • Network, scheme or switch. The shared hub that connects issuers and acquirers. Visa and Mastercard are card schemes; NPCI runs the UPI switch. A switch is a system that receives a message, decides where it should go, forwards it, and tracks the reply.
  • PSP (payment service provider). In UPI, a bank that runs the customer-facing side: it registers users, authenticates them and sends their requests to the switch. A TPAP (third-party application provider), such as a popular payments app, provides the app but must connect through one or more PSP banks.
  • VPA (virtual payment address). A short handle such as asha@okbank, also called a UPI ID. It hides the real account number and IFSC code. The part after @ names the PSP that can resolve the handle to an account.
  • Push and pull. In a push payment, the payer starts it ("send money"). In a pull or collect payment, the payee requests money and the payer approves it on their phone.
  • Authorisation. The issuer's real-time yes or no. For cards, an approval usually places a hold on the funds; the money has not moved yet.
  • Clearing. Exchanging the final records of which transactions happened and who owes whom, so every party can calculate its position.
  • Settlement. The actual movement of central-bank money between the banks' accounts, usually at a central bank or a settlement bank.
  • Netting. Adding up all obligations between parties and moving only the difference. If bank B owes bank A ₹500 and A owes B ₹100, B pays A ₹400.
  • RTGS (real-time gross settlement). A central-bank system that settles each large payment individually and immediately, with no netting. India's RTGS has run 24/7 since 14 December 2020.
  • MDR (merchant discount rate). The fee a merchant pays on each payment. For cards it bundles the interchange fee (paid to the issuer), the scheme fee (paid to the network) and the acquirer's margin.
  • Interchange. The fee the acquirer pays the issuer on each card payment. It pays for the issuer's fraud risk, credit risk and rewards.
  • PAN. The primary account number printed on a card (8 to 19 digits, per ISO/IEC 7812), whose first digits (the IIN or BIN) identify the issuer.
  • ISO 8583. The message standard that card networks use for authorisation messages. ISO 20022 is a newer, richer standard (XML or similar) used by many real-time and cross-border systems.
  • HSM (hardware security module). A tamper-resistant box that holds encryption keys and performs PIN and cryptogram operations without ever revealing the keys to the host computer.
  • TAT (turnaround time). A regulator's deadline for fixing a failed payment. In India, an RBI circular of 20 September 2019 requires a UPI payment that debited the payer but did not credit the payee to be reversed automatically by T+1 (one day after the transaction), with compensation of ₹100 per day of delay after that.

Clarifying Questions#

QuestionWhy it mattersAssumed answer
Are we designing the switch (network), a bank, or an app?Each has a very different scopeThe switch and its rules, plus the interfaces banks and apps must implement
Account-to-account, cards, or both?Different flows: instant debit and credit versus authorise now, settle laterBoth: real-time account-to-account as the main design, card rails as a second flow
What scale?Sizes every tier700 million payments a day on the real-time rail, peaks of 25,000 to 40,000 per second; cards 300 million a day
How fast must a payment complete?Drives timeouts and the number of hopsPayer sees a final result in under 5 seconds for 99% of payments; switch adds under 100 ms
Who holds customer money?Changes the risk modelBanks hold all money; the switch never holds customer funds
How do banks settle with each other?Determines netting and liquidity designDeferred net settlement in several cycles a day at the central bank; RTGS for large values
What happens when a bank is down or slow?The most common failure in practiceThe switch times out, declines new payments to that bank fast, and resolves in-flight ones through status checks and reversals
Are payments reversible?Push payments are final; cards allow chargebacksReal-time push payments are final once credited; errors are fixed by refunds or disputes. Cards support chargebacks
What limits apply?Fraud and liquidity controlPer-transaction and daily limits per user and per category; small-value offline wallet for tiny payments
Is cross-border in scope?Adds FX and foreign railsYes, as a deep dive: linking to other countries' fast payment systems and to card networks
Regulatory constraints?Data location, dispute deadlinesPayment data stored in-country; reversal and dispute deadlines set by the regulator
Must the network run 24/7?Rules out maintenance windowsYes, 24/7/365 with target availability of 99.99% for the switch itself

Requirements#

Functional requirements#

  1. Register and link. A user installs an app, verifies their phone number, links a bank account, creates a VPA and sets a PIN that only their bank can verify.
  2. Pay by address or QR (push). The payer enters a VPA, a mobile number, an account number plus bank code, or scans a QR code; enters an amount and PIN; the switch debits the payer's bank and credits the payee's bank.
  3. Request money (pull or collect). A payee sends a request; the payer approves with their PIN or declines; requests expire.
  4. Merchant payments. Merchants accept payments by static QR (fixed code at the counter), dynamic QR (code per order) and online intents (the shop's checkout opens the payment app).
  5. Card authorisation. Route card authorisation requests from acquirers to issuers by card number range, and return the issuer's decision.
  6. Clearing and settlement. Produce settlement files per cycle, calculate each bank's net position, and instruct the central bank to settle.
  7. Status and reversals. Any party can ask the final status of a transaction; failed or unknown payments that debited the payer are reversed automatically within the regulator's deadline.
  8. Disputes. Customers can raise complaints ("debited but not credited", "paid wrong person"), which move through the app, the banks and the switch with deadlines.
  9. Fraud and risk checks. Score each payment in real time and decline or step up suspicious ones.
  10. Mandates and recurring payments. A payer can approve a standing instruction once, for subscriptions and instalments.

Non-functional requirements#

  • Correctness. Never debit twice, never credit without a matching debit, and every transaction reaches a final state (success, failure or reversed).
  • Latency. Switch processing under 100 ms at p99, excluding the banks' own time; end-to-end p99 under 5 seconds.
  • Availability. Switch 99.99% or better (about 52 minutes of downtime a year at most), with no planned downtime. Failure of one bank must not affect payments between other banks.
  • Throughput. 40,000 payments per second at peak on the real-time rail, with headroom of at least 2×.
  • Durability and audit. Every message and every state change is stored durably and kept for years for audit and disputes.
  • Security. PINs never leave the payer's device or bank in clear text; messages are signed and encrypted; banks are authenticated with certificates.
  • Fairness and isolation. No single bank or app can overload the switch; each is rate-limited by its agreed capacity.
  • Data location. Payment data stays inside the country, as required by the regulator.

Capacity Estimation#

Start from the number of payments, then count messages, because a switch is sized by messages, not by payments.

Real-time account-to-account payments.

  • 700 million payments a day (UPI's published figure is above 640 million a day as of 2025, so this is a near-term target).
  • 700 M / 86,400 ≈ 8,100 payments per second on average.
  • Traffic is not flat. Evenings, salary days, the first days of a month and festival days are much busier, and night hours are quiet. Plan for a peak of about 4× the average: about 32,000 per second, and build the switch for 80,000 per second so that one data centre can absorb the whole load if the other fails.
  • About half of all payments are small. Wikipedia's UPI article notes that 50% of UPI transactions were below ₹200, which is why an on-device wallet for small payments (deep dive 10) was introduced to take load off banks.

Messages per payment. One push payment from Asha to Kai is not one message. In our design:

StepMessages
Payer PSP sends pay request to switch, switch acknowledges2
Switch asks payee PSP to resolve the VPA, gets reply2
Switch sends debit request to the remitter bank, gets reply2
Switch sends credit request to the beneficiary bank, gets reply2
Switch sends final result to payer PSP and payee PSP, gets acknowledgements4
Totalabout 12

So the peak is 32,000 × 12 ≈ 400,000 messages per second through the switch, and design capacity is about 1 million per second.

Bandwidth. A signed, encrypted XML or JSON message is about 2–4 KB. 400,000 × 3 KB ≈ 1.2 GB/s ≈ 10 Gbit/s at peak, spread over hundreds of bank connections. Each large bank sees thousands of messages a second; a small cooperative bank sees a few per second.

Latency budget (p99, target 5 seconds end to end).

HopBudget
Phone to payer PSP (mobile network)300–800 ms
PSP to switch, switch processing, switch to banks (network plus switch)under 100 ms of switch time, 10–30 ms per leased-line hop
Remitter bank debit (core banking)200–1,500 ms
Beneficiary bank credit200–1,500 ms
Notifications back100–300 ms

The banks' core systems dominate. The switch is a small part of the total, which is why the switch's job is mostly to stay out of the way and handle bank slowness gracefully.

Storage.

DataCalculationSize
Transaction record (state, parties, amounts, leg results)700 M × 1 KB0.7 TB a day
Message log (every message, signed, for audit)700 M × 12 × 3 KBabout 25 TB a day raw, about 5–8 TB compressed
Hot window for status checks and reversals (7 days)7 × 0.7 TB × 3 replicasabout 15 TB
Dispute window (6 months, transaction records)180 × 0.7 TBabout 125 TB, replicated
Long-term archive (years, compressed, object storage)about 2–3 PB a year including message logsobject storage
Handle-to-PSP routing tablea few thousand handlesunder 1 MB
Mobile-number directory (if the switch runs one)500 M users × 200 bytesabout 100 GB
Settlement positions per cycle600 banks × 600 counterpartiesa few MB

Status checks. If 0.5% of payments end in an unknown state and each is checked up to 3 times, that is 700 M × 0.005 × 3 ≈ 10 million status checks a day, about 120 per second. This is tiny. But if banks retry blindly, it can become hundreds of times larger, which is exactly what happened on 12 April 2025 (deep dive 3).

Fraud scoring. Every payment is scored once: 32,000 scores per second at peak, each in under 20–30 ms, each reading 50–200 features from an in-memory store.

Card rails. Visa's network processed 257.5 billion transactions in 2025 according to Wikipedia, about 700 million a day or 8,200 per second on average. For our card flow assume 300 million authorisations a day (3,500 per second average, 15,000 per second at holiday peaks), with clearing records produced in daily batches.

QuantityAveragePeak
Real-time payments8,100/s32,000/s (build for 80,000/s)
Switch messages100,000/s400,000/s
Card authorisations3,500/s15,000/s
Fraud scores11,600/s47,000/s
Switch processing latencyp50 10–20 msp99 under 100 ms
Hot transaction storeabout 15 TB
Settlement cyclesseveral a day

Core Entities#

  • Participant: a bank, PSP bank, third-party app (through its sponsor PSP), acquirer or issuer. Has a participant code, certificates, endpoints, capacity limit, settlement account at the central bank, and status (live, suspended, degraded).
  • Handle: the suffix after @ in a VPA (for example okbank), mapped to the PSP that owns it.
  • VPA: name@handle, owned by the PSP that issued it; the PSP maps it to an account. The switch does not need to store every VPA.
  • Transaction: the switch's record of one payment: transaction id, type (pay, collect, refund, reversal), payer and payee references, amount, currency, initiation mode (QR, intent, VPA, account), state, timestamps, and leg results.
  • Leg: one step with one bank: debit leg (remitter bank) and credit leg (beneficiary bank), each with request time, response code, bank reference number and retries.
  • CollectRequest: payee, payer, amount, expiry, state (pending, approved, declined, expired).
  • Mandate: payer, payee, maximum amount, frequency, validity, and state; used for recurring payments.
  • SettlementCycle: cycle id, cut-off time, state (open, closed, files published, settled).
  • NetPosition: for each cycle and participant, total debits, total credits, fees, and net amount to pay or receive.
  • Dispute: original transaction, type, raised by, current owner, deadline, state, and resolution.
  • BinRange: for cards, a range of card numbers mapped to an issuer and a routing endpoint.
  • Token: for card tokenisation, a token number mapped (in a secure vault) to the real card number, with domain restrictions (device, merchant).

API Design#

A payment network's "API" is a set of messages between the switch and its members, carried over private leased lines or a secure network with mutual TLS. Real networks have their own message names; the names below are generic.

# Real-time rail: participant <-> switch (signed, encrypted, async)
PayRequest     { txn_id, type: PAY|COLLECT|REFUND, initiation: VPA|QR|INTENT|ACCOUNT|MOBILE,
                 payer: { vpa | account+bank_code }, payee: { vpa | account+bank_code | qr_payload },
                 amount_minor, currency: "INR", note, ref_url?,
                 cred: <PIN block encrypted for the remitter bank>, device: { id, os, app, geo }, risk_hints }
  -> Ack { txn_id, accepted: true }          # synchronous, means "received", not "paid"
  -> PayResult (callback) { txn_id, status: SUCCESS|FAILURE|DEEMED, code, rrn, payer_name, payee_name }
ResolveAddress { txn_id, vpa }            -> { name, account_ref_masked, merchant_category? }
DebitRequest   { txn_id, account_ref, amount_minor, cred }      -> DebitResult { code, bank_ref }
CreditRequest  { txn_id, account_ref, amount_minor }            -> CreditResult { code, bank_ref }
ReversalRequest{ orig_txn_id, leg: DEBIT, reason }              -> ReversalResult
StatusCheck    { orig_txn_id }            -> { state, debit_leg, credit_leg, rrn }
Heartbeat      {}                          -> {}                 # every few seconds per connection
ListSettlement { cycle_id }               -> signed settlement file per participant
RaiseDispute   { orig_txn_id, type, details } -> { dispute_id, deadline }
 
# Card rail: acquirer <-> network <-> issuer (ISO 8583, binary over TCP)
0100 / 0110   authorisation request / response
0200 / 0210   financial request / response (single message, e.g. ATM or debit)
0400 / 0410   reversal request / response
0420 / 0430   reversal advice / acknowledgement (guaranteed delivery)
0800 / 0810   network management (sign-on, echo, key exchange)

Design notes:

  • Asynchronous by default. The switch acknowledges a pay request at once ("I have it") and sends the result later through a callback. This lets the switch hold millions of payments in flight without keeping a thread or a connection open for each, and it makes timeouts explicit.
  • The originator creates the transaction id. The id starts with the originating participant's code and is unique for that participant (for example a 35-character string). Every later message about the payment carries it. It is the network-wide idempotency key (see Idempotency and Safe Retries): a duplicate pay request with the same id returns the stored result, never a second payment.
  • Amounts are integers in the smallest unit (paise, cents). Never use floating point for money.
  • The PIN is encrypted for the remitter bank, not for the switch. The switch forwards the encrypted block; only the remitter bank's HSM can decrypt and verify it. A breach of an app or of the switch does not reveal PINs.
  • Every message is signed by the sender's private key, and the receiver verifies the signature against the certificate registered for that participant. This gives integrity and non-repudiation: in a dispute, nobody can claim they never sent a message.
  • Status check is a first-class message with strict rules on how often it may be called. Its misuse is one of the most important failure modes (deep dive 3).
  • Card messages use ISO 8583, a compact binary format from the 1980s. Wikipedia's ISO 8583 article notes that Visa and Mastercard base their authorisation messages on it. Its four-digit message type indicator (MTI) says what a message is: in 0110, the first digit is the version (0 = 1987), the second the class (1 = authorisation), the third the function (1 = response) and the fourth the origin (0 = acquirer).

High-Level Design#

We build the network one requirement at a time, starting with the simplest version that works, then add the pieces that real-world failures force on us.

1) Registration, linking and the VPA#

Before anyone can pay, the user needs three things: a proven link between their phone and their app, a link from the app to a bank account, and a PIN that only the bank can check.

  1. Phone binding. The app checks that the SIM card with the user's registered mobile number is really in this phone. A common way is to have the app send an SMS from the phone to the PSP's number; the PSP sees the message arrive from that number and binds the device id to it. Receiving an OTP is weaker, because OTPs can be phished; sending from the SIM proves possession of the SIM.
  2. Account discovery. The PSP asks the switch to find accounts linked to that mobile number. The switch forwards the query to banks (or to the bank the user picked), and the bank returns masked account references (never the full account number to the app).
  3. VPA creation. The PSP creates asha@okbank and stores the mapping from that VPA to Asha's account reference. The VPA lives at the PSP, not at the switch.
  4. PIN setting. The user proves they own the account to their bank, for example by entering the last six digits of their debit card, its expiry date and an OTP sent by the bank. Then they choose a PIN. The PIN is encrypted on the phone with a key for the bank, so the PSP and switch see only an encrypted block.

2) A push payment through the switch#

Asha (payer) wants to pay ₹500 to Kai (payee, kai@paybank).

  1. Asha's app builds a pay request with a fresh transaction id, the payee VPA, the amount and her PIN encrypted for her bank, and sends it to her payer PSP.
  2. The payer PSP checks the device and the app, runs its own risk rules, and forwards the request to the switch.
  3. The switch validates the signature and the format, checks limits and runs its fraud score, then reads the handle paybank and asks the payee PSP to resolve kai@paybank. The payee PSP returns Kai's name and an account reference.
  4. The switch sends a debit request to the remitter bank (Asha's bank) with the encrypted PIN. The bank verifies the PIN in its HSM, checks the balance and debits ₹500.
  5. On success, the switch sends a credit request to the beneficiary bank (Kai's bank), which credits ₹500.
  6. The switch sends the result to both PSPs, which notify Asha and Kai.

The order matters: debit first, then credit. If the debit fails, nothing has happened. If the debit succeeds and the credit fails, the switch must reverse the debit. The opposite order (credit first) would create money that might never be collected.

Note that the switch never holds Asha's or Kai's money. It routes instructions and records outcomes. Money moves between the two banks later, at settlement.

3) Collect requests, QR codes and merchant intents#

Collect (pull). Kai sends a collect request for ₹500 to asha@okbank. The switch routes it to Asha's PSP, whose app shows "Kai requests ₹500". If Asha approves with her PIN, the flow continues exactly like a push payment from step 3. Requests carry an expiry (minutes to days) and may be declined.

Collect requests are a known fraud channel: a scammer sends a request labelled "to receive your refund, approve this", and the victim enters their PIN, not realising that a PIN always sends money. Networks restrict collect requests (lower limits, only from verified merchants, or none between individuals), and apps show a clear "you are paying" warning. Deep dive 8 covers this.

QR codes. A QR code is just a way to type the payee details without typing. QR payments come in four combinations:

Static (same code every time)Dynamic (new code per transaction)
Merchant-presented (the shop shows the code, the customer scans)A printed code at a tea stall: payee VPA and name; customer types the amountA code shown on the checkout screen: payee, amount, order id
Consumer-presented (the customer shows the code, the shop scans)Rare; a fixed customer codeA one-time code in the customer's app, scanned by the shop's scanner

For our rail, a merchant-presented QR encodes a payment URI such as upi://pay?pa=shop@paybank&pn=Tea%20Stall&am=20.00&tr=ORDER123. Scanning it fills in a push payment. The switch does not care that it came from a QR; it only sees the initiation mode for risk scoring and reporting.

Intents. On a phone, a shopping app can open a payment app with the same URI. After the payment, the payment app returns to the shopping app, which then asks its own server (which asks the merchant's PSP) for the real status. The return value from the phone is only a hint: a malicious app could fake it.

4) Card authorisation through a scheme#

A card payment follows a different shape. The shop's terminal sends an authorisation to the acquirer, the acquirer sends it to the network, the network reads the card number's leading digits (BIN range) to find the issuer, and the issuer approves or declines.

  1. Sam taps a card at a shop for $40. The terminal reads the card's chip, which produces a one-time cryptogram for this transaction.
  2. The terminal sends an authorisation request to the acquirer's processor.
  3. The acquirer forwards an ISO 8583 0100 message to the network.
  4. The network looks up the BIN range, optionally checks fraud and token mapping, and forwards to the issuer's processor.
  5. The issuer checks the cryptogram, the card status, the available credit and its fraud model; it approves and places a hold of $40 on Sam's account.
  6. The 0110 response flows back to the terminal: "approved".
  7. Later (often at the end of the day), the shop sends a capture batch. The acquirer submits clearing records to the network, the network builds clearing files for each issuer, and settlement moves the money: issuers pay the network's settlement bank, which pays acquirers, which pay merchants.

This is the "authorise now, settle later" model: authorisation freezes funds; capture and clearing finalise them; settlement moves them, usually a day or two later.

Stand-in processing. If the issuer does not answer in time (its systems are down or slow), the network can answer on the issuer's behalf using rules the issuer agreed in advance, such as "approve up to $100 for cards in good standing". This keeps shops working through issuer outages, at the cost of some risk the issuer accepted beforehand. The real-time account rail cannot do this, because it would mean crediting money nobody has confirmed is available.

5) Clearing and settlement#

Every successful real-time payment creates an obligation: the remitter bank owes the beneficiary bank. The switch does not move money after each payment. Instead:

  1. The day is divided into settlement cycles (for example several a day). Each transaction belongs to the cycle in which it completed.
  2. At a cycle's cut-off, the switch closes the cycle, adds up every bank's debits and credits, and computes net positions: one number per bank, positive (receive) or negative (pay).
  3. The switch publishes signed settlement files to each bank, listing every transaction in the cycle, so each bank can reconcile.
  4. The switch sends one settlement instruction to the central bank, which debits the net payers' settlement accounts and credits the net receivers' accounts.

The sum of all net positions is exactly zero: money is only moved between banks, never created. With 600 banks and 30 million payments in a cycle, netting reduces 30 million obligations to at most 600 account movements.

The risk in this design is that a bank that owes money in a cycle may not have it. Deep dive 5 covers how networks control that settlement risk: limits, collateral and prefunding.

6) Status, reversals and disputes#

Some payments end in uncertainty: the debit request timed out, so the switch does not know whether the remitter bank debited Asha or not. Three tools close the gap:

  • Status check. The switch (or a PSP) asks the bank "what happened to transaction X?". This must be rate-limited and backed off (at most a few checks, spaced apart).
  • Deemed or pending state. If the credit timed out after a successful debit, the payment is marked deemed: probably successful, to be confirmed. The payer sees "pending", not "failed", so they do not pay twice.
  • Reversal. If the credit definitely failed, or nobody can confirm it before a deadline, the switch sends a reversal to the remitter bank, which returns the money to Asha. In India the regulator requires this by T+1 at the latest, with compensation after that.

Anything still wrong becomes a dispute, raised by the customer through the app and escalated (app, PSP bank, customer's bank, switch, ombudsman), each with a deadline.

The full high-level design#

Components:

  • Switch edge. Terminates mutual TLS from each member, checks message signatures (with HSM-held or HSM-verified keys), validates the schema, and enforces each member's agreed rate limit. Rejects fast when a member is over capacity, so one member cannot overload the core.
  • Payment orchestrator. The heart of the real-time rail. Runs each transaction's state machine (received, resolved, debit pending, debited, credit pending, success, failed, deemed, reversed), sends requests to banks, and records every transition. Stateless processes; all state lives in the transaction store.
  • Routing service. Maps VPA handles to PSPs, bank codes to bank endpoints and card BIN ranges to issuers. Knows each member's health and can mark a bank "degraded" so new payments to it fail fast with a clear code.
  • Risk engine. Scores every payment in milliseconds with rules and machine-learning models, using a feature store of velocity counters and history. Returns allow, decline or step-up.
  • Transaction store. Sharded by transaction id, synchronously replicated so that no acknowledged transaction is lost if a data centre fails.
  • Timeout and retry scheduler, recovery service. Fires when a leg times out, drives status checks with strict back-off, sends reversals and resolves deemed transactions.
  • Message log. Append-only record of every signed message in and out, for audit, disputes and replay.
  • Card authorisation router. Routes ISO 8583 messages by BIN, maps tokens to card numbers through the token vault, applies stand-in rules when issuers are slow.
  • Clearing and settlement engine. Groups completed transactions into cycles, computes net positions, publishes files, instructs the central bank, and tracks confirmation.
  • Dispute management. Tracks complaints and their deadlines across parties, and drives refunds, reversals and chargebacks.
  • Member health monitor. Measures each bank's success rate and latency in real time, feeds routing and alerts.
  • HSM cluster. Holds signing keys, network keys, token keys and card network cryptographic keys.

Key Flows#

Flow 1: A push payment, happy path#

Asha pays Kai ₹500 by VPA. The numbers on the right are typical times.

Points to notice:

  • The ack is not the result. The payer PSP holds the app's request open (or the app polls the PSP) until the final result arrives.
  • Each state change is written before the next message goes out. The switch writes "debit pending" before sending the debit request, and "debited" before sending the credit. If the switch crashes between steps, the recovery service reads the stored state and knows exactly what to do next.
  • The RRN (retrieval reference number) is a short reference shown to both users. It ties the payment together for support calls and disputes.

Flow 2: The credit times out#

This is the flow that keeps payment engineers awake. Asha's bank debited her, but Kai's bank does not answer within the timeout.

The key rule: never reverse the debit while the credit might still have happened, and never tell the payer "failed" while the money might be at Kai's bank. "Pending" is the honest answer. If the bank stays silent, the end-of-cycle reconciliation between the switch's records and the bank's files settles the question, and the reversal happens by the T+1 deadline.

Flow 3: Card authorisation, stand-in and clearing#

The 0120 message is an advice: it tells the issuer "this was approved on your behalf". Wikipedia's ISO 8583 article explains that requests are end-to-end messages with timeouts and automatic reversals, while advices are point-to-point messages with guaranteed delivery. The issuer must accept the advice and update the cardholder's available balance.

If the acquirer never receives the 0110 (a timeout on its side), it sends a 0400 reversal for that authorisation, so the issuer releases any hold it placed. This is the card world's version of Flow 2.

Flow 4: A settlement cycle#

Late arrivals. A transaction that completes one millisecond after cut-off belongs to the next cycle. The cycle id is assigned at the moment of the final state change, from one authoritative clock in the switch, so every party agrees which cycle a transaction belongs to. Reconciliation teams call a transaction that one side counts in this cycle and the other in the next a "temporary break": it fixes itself one cycle later and must not be treated as an error.

Flow 5: A collect request#

The approval message carries the same transaction id as the original request, so a double tap on "approve" cannot pay twice.

Data Model#

The transaction store holds the hot data. A relational schema shows the shape and the constraints; at national scale it runs on a sharded, synchronously replicated database (the store table below discusses which).

CREATE TABLE txn (
  txn_id        VARCHAR(40) PRIMARY KEY,       -- created by originator, network-wide unique
  txn_type      VARCHAR(12) NOT NULL,          -- PAY, COLLECT, REFUND, REVERSAL
  state         VARCHAR(16) NOT NULL,          -- RECEIVED, RESOLVED, DEBIT_PENDING, DEBITED,
                                               -- CREDIT_PENDING, SUCCESS, FAILED, DEEMED, REVERSED
  amount_minor  BIGINT      NOT NULL CHECK (amount_minor > 0),
  currency      CHAR(3)     NOT NULL,
  payer_bank    VARCHAR(12) NOT NULL,
  payee_bank    VARCHAR(12),
  payer_ref     VARCHAR(64) NOT NULL,          -- VPA or masked account ref, never full PAN
  payee_ref     VARCHAR(64) NOT NULL,
  initiation    VARCHAR(10) NOT NULL,          -- VPA, QR, INTENT, ACCOUNT, MOBILE
  rrn           CHAR(12),
  cycle_id      VARCHAR(16),                   -- set when state becomes final
  risk_score    SMALLINT,
  created_at    TIMESTAMP   NOT NULL,
  updated_at    TIMESTAMP   NOT NULL,
  version       INT         NOT NULL           -- optimistic concurrency for state changes
);
 
CREATE TABLE txn_leg (
  txn_id      VARCHAR(40) NOT NULL REFERENCES txn(txn_id),
  kind        VARCHAR(10) NOT NULL,            -- DEBIT, CREDIT, REVERSAL
  state       VARCHAR(12) NOT NULL,            -- SENT, OK, FAILED, TIMEOUT, UNKNOWN
  bank_ref    VARCHAR(32),
  resp_code   VARCHAR(8),
  attempts    SMALLINT    NOT NULL DEFAULT 0,
  next_check  TIMESTAMP,                       -- drives the recovery scheduler
  PRIMARY KEY (txn_id, kind)
);
 
CREATE TABLE net_position (
  cycle_id      VARCHAR(16) NOT NULL,
  participant   VARCHAR(12) NOT NULL,
  debits_minor  BIGINT NOT NULL,
  credits_minor BIGINT NOT NULL,
  fees_minor    BIGINT NOT NULL,
  net_minor     BIGINT NOT NULL,               -- credits - debits - fees; sum over cycle = 0
  PRIMARY KEY (cycle_id, participant)
);

Notes on the schema:

  • State changes are conditional updates. The orchestrator moves a transaction with UPDATE txn SET state = 'DEBITED', version = version + 1 WHERE txn_id = ? AND state = 'DEBIT_PENDING' AND version = ?. If zero rows change, another worker (or a late bank reply) got there first, and this worker stops. This is optimistic concurrency control (see Concurrency Control and Database Locking), and it is what makes it safe to have retries, timeouts and late replies racing each other.
  • Legs are separate rows with their own state and attempt count. A late "debit OK" that arrives after a timeout updates the debit leg, and the state machine decides what that means.
  • next_check is an index that the recovery scheduler scans for due work, so it never needs to scan the whole table.
  • The primary key is the originator's transaction id, so the database itself enforces "one payment per id": a duplicate insert fails, and the orchestrator returns the stored result.
  • The switch stores references, not secrets. It never stores PINs, full card numbers (outside the token vault), or full account numbers it does not need.

Which store for which data.

DataAccess patternStoreWhy
Transactions and legs (hot, 7 days)Point reads and conditional writes by id, 400,000 operations per secondSharded relational database (PostgreSQL or MySQL with sharding, or a distributed SQL database such as CockroachDB, TiDB or Spanner-style) with synchronous replication across two data centresStrong consistency per transaction; conditional updates; must not lose an acknowledged write
Message logAppend only, read for audit and disputesReplicated log (Kafka with acks from all in-sync replicas), then compressed files in object storageCheap, ordered, durable
Completed transaction eventsStream consumed by settlement, analytics, disputesKafka topics partitioned by transaction idDecouples the hot path from slower consumers (see Apache Kafka in Practice)
Routing tables (handles, bank codes, BIN ranges)Read on every payment, changed rarelyIn-memory copies in every orchestrator, loaded from a versioned config storeMicrosecond lookups; changes are deliberate releases
Risk features (velocity counters, device history)Very high read and increment rateIn-memory key-value store (Redis or Aerospike) with replication, rebuilt from the event streamSub-millisecond reads within the risk budget (see Redis in Practice)
Settlement positions and cyclesSmall, critical, auditedRelational database with strict transactionsEvery number must be explainable
DisputesWorkflow with deadlinesRelational database plus a workflow engineLong-running, state-heavy (see Pattern: Multi-Step Processes and Workflows)
Archive (years)Rare reads, legal holdsObject storage with columnar files (Parquet) and an index by id and dateLow cost per terabyte
Card token vaultLow volume, highest sensitivityDedicated, isolated database with HSM-backed encryptionSmallest possible attack surface

For the general method behind these choices, see Choosing a Database: A Decision Guide.

Sharding key. Transactions shard by a hash of the transaction id. Every message about a payment carries the id, so every lookup goes to exactly one shard, and load spreads evenly. Sharding by bank would be a mistake: the largest banks carry a large share of all traffic, so their shards would be hot, and an outage of one shard would take out one bank's customers completely.

Deep Dives#

1. The switch core: a state machine at 80,000 payments per second#

The orchestrator is the part that must be both fast and exactly right. Its job for each payment is a small, fixed state machine.

Rules that keep it correct.

  1. Write ahead of every external call. Before sending the debit request, persist DEBIT_PENDING. Before sending the credit, persist DEBITED and then CREDIT_PENDING. A crash at any point leaves a state from which recovery knows the next step. This is the same idea as a database's write-ahead log, applied to a business process.
  2. Every transition is a conditional update on the current state and version. Two workers, or a worker and a late reply, can never both apply a transition.
  3. Late replies are welcome. A "debit OK" that arrives after the switch marked DEBIT_UNKNOWN is a perfectly good answer: it moves the payment to DEBITED, and the credit goes out. The only replies the switch ignores are those for states that are already final, and those it logs for reconciliation.
  4. Unknown is a real state. A timeout does not mean "failed". It means "we do not know". The design gives unknown its own states (DEBIT_UNKNOWN, DEEMED) with their own recovery paths.
  5. Final states are final. Once SUCCESS, FAILED or REVERSED, the transaction never changes. Corrections after that are new transactions (a refund is a new payment in the opposite direction, referring to the original).

How the orchestrator handles 80,000 payments per second.

  • Stateless workers, partitioned by transaction id. Each incoming message is hashed by transaction id to a partition, and each partition is owned by one worker at a time. That gives ordered processing per payment without distributed locks. With 512 partitions and 100 workers, each worker handles about 800 payments per second at the design peak.
  • Event-driven, not thread-per-payment. A worker sends the debit request and moves on. The bank's reply arrives as a new event on the same partition. A payment that waits 2 seconds for a bank costs a row in the database and an entry in the timer wheel, not a blocked thread. This is how a switch keeps millions of payments in flight.
  • Timers in a hierarchical timer wheel. Each pending leg schedules a timeout (say 10 seconds for the debit). A timer wheel inserts and expires timers in constant time, which matters when millions of timers exist. Timers are also persisted (the next_check column), so a worker that crashes does not lose them: the new owner of the partition reloads due timers from the database.
  • Batch writes. Each worker groups state changes into small batches (for example every 2 ms) to reduce write overhead, while keeping each payment's own changes in order. At 400,000 state changes per second across 64 database shards, each shard does about 6,000 writes per second, which is comfortable for a well-tuned shard on NVMe drives.
  • Bank adapters are separate. Each bank's connection, message format quirks, timeouts and concurrency limit live in its own adapter. A slow bank fills its own adapter's queue, not the orchestrator's.

A worked latency budget inside the switch (p99 target 100 ms).

StepTime
TLS, signature verification (with session reuse, keys cached)1–3 ms
Schema validation, limit checkunder 1 ms
Risk score (in parallel with address resolution)10–30 ms
Database write per state change (synchronous replication across two nearby data centres)2–5 ms each, 4–6 changes
Internal queues and scheduling5–10 ms
Total switch timeabout 40–80 ms

The banks' time comes on top: 0.5 to 3 seconds in total for the debit and credit legs.

Why not a distributed transaction across the two banks? Two-phase commit (2PC) would ask both banks to "prepare" and then "commit". It fails here for three reasons: the banks are independent companies that will not let an outside coordinator hold locks in their core systems; a coordinator failure during 2PC leaves both banks blocked; and the debit-then-credit order with reversal is simpler, auditable and already understood by banks and regulators. The design is a saga: a sequence of local steps, each with a compensating step (the reversal) if a later step fails (see Distributed Transactions: 2PC, Sagas and Outbox).

2. Address resolution and routing#

A payment can name the payee in five ways: a VPA, a mobile number, an account number plus a bank code (IFSC in India), a QR code (which contains one of these), or a merchant's intent link. The switch must turn each into "which bank, which account" in a few milliseconds.

Design choice: who stores the VPAs? There are two options.

OptionHow it worksProsCons
Central directory at the switchSwitch stores every VPA and its accountOne lookup, fast; easy to check if a VPA existsSwitch holds a copy of every user's account link: a huge privacy and security target; must stay in sync with hundreds of PSPs
Federated: the handle names the PSPSwitch stores only handle -> PSP; asks the PSP to resolve the restSwitch holds almost no personal data; PSPs control their own usersOne extra network round trip per payment; payee PSP must be available

UPI uses the federated model: the part after @ tells the switch which PSP to ask. Our design follows it. The routing table of a few thousand handles fits in memory on every orchestrator.

The cost of federation is availability. If the payee PSP is down, payments to its VPAs fail even if the payee's bank is up. Two mitigations:

  • Cache successful resolutions briefly. A shop's VPA resolves to the same account thousands of times a day. Caching vpa -> account ref for a few minutes (with the PSP's permission and a way to invalidate) removes most lookups for merchants. Individuals change accounts rarely, but caching them is riskier (a VPA moved to another account would send money to the old one), so keep their cache very short or disable it.
  • Account-plus-bank-code payments do not need resolution. The switch routes them straight to the beneficiary bank by bank code.

Mobile-number payments need a mapping from a phone number to a VPA. That mapping is a central directory by nature (the payer's app does not know which PSP the payee uses). It is a small, well-defined table (one primary VPA per number, with the user's consent), held by the switch, and updated when users port numbers or change their primary account. Phone numbers are reassigned by mobile operators after an account closes, so the directory must expire mappings for numbers that leave the network, otherwise a new owner of an old number could receive someone else's payments.

Routing to banks. The beneficiary bank is found from the payee's account reference (resolved VPA) or the bank code. Each bank has one or more endpoints, often in two data centres. The routing service keeps, per bank:

  • endpoints and their health,
  • the bank's agreed peak capacity (messages per second),
  • current success rate and latency (sliding windows of 10 seconds and 1 minute),
  • status: live, degraded, or suspended (for example during the bank's announced maintenance).

Fail fast for a sick bank. If a remitter bank's success rate collapses (for example below 50% for 30 seconds), sending it more requests only adds timeouts, reversals and angry customers. The switch can:

  1. Shed load to that bank: admit only a fraction of new payments, so the bank has room to recover.
  2. Decline new payments immediately with a clear code ("remitter bank unavailable"), so apps can tell users "your bank is having problems, try later or use another account", rather than spinning for 30 seconds.
  3. Continue to process status checks and reversals with priority, because they resolve money already in flight.

This is a circuit breaker per bank (see Resilience Patterns: Timeouts, Retries and Circuit Breakers), and it is what keeps one bank's outage from becoming a network outage.

Card BIN routing. Card networks route by the card number's leading digits. Wikipedia's article on payment card numbers notes that the issuer identification number (IIN) is the leading six or eight digits. The router keeps a sorted array of non-overlapping ranges (low, high, issuer, endpoint) and finds the range by binary search: with a few hundred thousand ranges that is about 18 comparisons, well under a microsecond. Range tables are versioned and swapped atomically, so a lookup never sees half an update. Tokens (deep dive 7) have their own ranges, so the router knows when to ask the token vault first.

3. Timeouts, unknown outcomes and status-check storms#

A national network has hundreds of banks, and on any given minute some of them are slow. Timeouts are therefore not an edge case; they are a daily, high-volume event. How the network handles them decides both its correctness and its availability.

Timeouts must nest. Each layer must wait longer than the layers beneath it, plus a margin:

LayerExample timeout
Bank leg (switch waiting for one bank)8–10 seconds
Switch overall for one payment (debit plus credit plus margin)25–30 seconds
Payer PSP waiting for the switch's final result35–45 seconds
App waiting for the PSP60 seconds, then "pending, we will notify you"

If the order is wrong, for example the app gives up after 20 seconds while the switch is still waiting for a credit, the app shows "failed" while the money may still arrive at Kai's bank. Asha pays again, and now she has paid twice. Never let an outer layer turn "unknown" into "failed".

Choose the leg timeout from data. Measure each bank's response time distribution. If a bank's p99.9 is 2.5 seconds and its worst minutes reach 6 seconds, a 10-second timeout catches almost all real answers while still bounding the wait. Too short a timeout creates unknown outcomes that were actually going to succeed; too long a timeout keeps users waiting and ties up capacity.

What happens after a timeout. The switch does not just retry the debit: a second debit request for the same payment could debit twice if the bank does not deduplicate properly. Instead it asks, with a status check, "what happened to transaction X?". The answer may be "debited", "not debited" or "never heard of it" (which, after a safe wait, means the request never arrived and the payment can fail cleanly).

Retry amplification, the arithmetic. Suppose three layers (app, PSP, switch) each retry up to 3 times on a timeout. One user action can then produce up to (1 + 3)^3 = 64 requests at the bottom layer. During an incident, when timeouts are common, almost every request triggers retries, and a bank that was 20% overloaded suddenly receives many times its normal load. This is the classic retry storm: the cure (retrying) makes the disease (overload) worse. The fixes are standard:

  • Retry at one layer only, ideally the one closest to the failure (the switch's recovery service). Upper layers wait or poll the switch's stored result.
  • Retry budgets: retries may be at most, say, 10% of normal requests per bank. Beyond that, they are dropped.
  • Exponential back-off with jitter (random spread), so retries do not arrive in synchronised waves.
  • Status checks capped in number and spaced in time.

Case study: the outage of 12 April 2025. According to Wikipedia's UPI article, UPI had its largest outage in more than three years on 12 April 2025, lasting over five hours. NPCI attributed it to the lack of a limit on transaction status checks in the system architecture: some banks repeatedly sent "Check transaction" requests, including for older transactions. NPCI's operating rules allowed a bank to check a transaction's status only three times, 90 seconds apart, but that limit was expected to be enforced by the banks, and NPCI did not rate-limit excess requests at its firewall. The success rate fell to about 50% for two hours and about 80% for the next three, and stabilised at 4:40 p.m.

Lessons that apply to any shared network:

  1. A rule that is not enforced is a suggestion. "At most 3 checks, 90 seconds apart" must be enforced at the switch edge, per member and per original transaction, not trusted to hundreds of independent implementations.
  2. Separate capacity for different work. Status checks share databases and CPUs with payments. Give them their own quota (for example at most 5% of a member's message rate) and their own worker pool, so a flood of checks cannot starve new payments. This is the bulkhead pattern.
  3. Cheap answers for repeated questions. Status for a transaction that is already final can be served from a cache or a read replica, never from the primary path.
  4. Watch success rate by message type. A sudden rise in status checks per payment is an early warning, minutes before the success rate falls.

Wikipedia also notes that from 1 August 2025 NPCI introduced technical limits across UPI apps, including daily limits on balance enquiries and "list accounts" calls. These are the same idea applied to other non-payment messages that apps used to call freely.

Enforcing the status-check rule at the edge. A small per-transaction counter plus a per-member token bucket is enough:

on status_check(member, orig_txn_id, now):
    # per-member budget: token bucket sized at 5% of the member's agreed payment rate
    if not bucket[member].take(1, now):
        return reject(code = "RATE_LIMITED", retry_after = bucket[member].next_token_at())
 
    # per-transaction rule: at most 3 checks, at least 90 s apart
    c = checks.get(orig_txn_id)               # {count, last_at}, TTL 1 day
    if c and c.count >= 3:
        return reject(code = "CHECK_LIMIT")   # resolution now comes from reconciliation
    if c and now - c.last_at < 90 s:
        return reject(code = "TOO_SOON", retry_after = c.last_at + 90 s - now)
    checks.put(orig_txn_id, {count: (c.count if c else 0) + 1, last_at: now})
 
    # answer final states from the read path, never touch the primary
    t = status_cache.get(orig_txn_id) or replica.read(orig_txn_id)
    return t.public_status()

The counters live in the same in-memory store as other rate limits (see Rate Limiting and Throttling). A deliberate design point: once a transaction has used its 3 checks, the member is told to stop asking, and the answer will arrive through the settlement file or the reversal. This bounds the worst-case load from status checks to a known number.

Shrinking the time money is stuck. When a payment times out after the debit, the payer's money is held until the payment is resolved. Wikipedia's UPI article notes that NPCI introduced a real-time feature, launched on 20 September 2022, to cut the time banks took to release funds after a timeout or decline from 24 hours to 30 seconds. The design lesson: the network should drive resolution actively (status checks and reversals within seconds), instead of leaving it to overnight reconciliation.

4. Idempotency and reconciliation across parties#

Within one company, idempotency means "store the key and the result". Across five companies, every party must deduplicate on its own, and every party must be able to prove, later, what it did.

One payment, many identifiers.

IdentifierCreated byScopeUsed for
Client request idAppOne app installApp-level retries to its PSP
Network transaction idOriginating PSPWhole network, foreverIdempotency at the switch and banks; all messages
RRN (retrieval reference number)SwitchNetwork, shown to usersSupport, disputes, matching in files
Bank reference (debit)Remitter bankThat bankBank statement line, reversal reference
Bank reference (credit)Beneficiary bankThat bankBank statement line
Settlement cycle idSwitchNetworkWhich net settlement covered it

The switch stores all of them together. That table is what makes reconciliation and disputes possible: any party can arrive with its own identifier and find the payment.

Deduplication at every hop.

  • App to PSP: the app's request id. A retry after a lost response returns the stored result.
  • PSP to switch: the network transaction id. The switch's primary key rejects a second insert; the switch returns the stored state.
  • Switch to bank: the bank must treat (transaction id, leg kind) as unique. A repeated debit request for the same transaction id must return the first result, not debit again. This is a network rule that every bank's implementation is certified against before going live.
  • Reversal: keyed by the original transaction id. Reversing twice must have the same effect as reversing once.

The principle fits in one line: exactly-once processing = at-least-once delivery (retry until you get an answer) + at-most-once effect (deduplicate by an idempotency key). Shopify engineers have shared practical lessons from their payment systems: short timeouts (a 5-second read and 1-second write timeout instead of a 60-second default), circuit breakers (Shopify's Semian library), ULIDs as idempotency keys because they sort by time (good for database index locality), and storing reconciliation breaks in a database rather than in someone's spreadsheet. Stripe has described an idempotency design that stores the key with the cached response, expires keys after 24 hours, and requires a new key if the request body changes. On a payment network the key must live much longer than 24 hours, because disputes arrive months later: the switch keeps transaction ids unique for good (the archive is indexed by id).

Reconciliation: proving everyone agrees. At the end of every settlement cycle, three views of the same payments exist: the switch's records, the remitter bank's core banking entries, and the beneficiary bank's entries. Reconciliation matches them.

Each kind of break has a standard cause and fix:

BreakTypical causeFix
Switch says success, bank has no debitBank applied debit late or lost itBank posts the debit or raises an adjustment through the switch
Bank debited, switch says failed or unknownDebit reply was lost (the timeout case)Automatic reversal by T+1
Switch says success, beneficiary bank has no creditCredit reply was "ok" but posting failed inside the bankBeneficiary bank credits the customer; RBI-style rules penalise delay
Amounts differRounding, fee handling or bugAdjustment entry; investigate code
In one cycle on one side, next cycle on the otherClock differences around cut-offTemporary break; clears automatically next cycle

This flow solves the three classic reconciliation problems: data normalisation (each party has its own formats, ids and time zones), volume (stream processing such as Flink for near-real-time matching, or end-of-day batch jobs when that is enough) and the cut-off issue (records stamped either side of midnight).

Real-time reconciliation. Waiting for end of day leaves money stuck for hours. A better design streams the switch's final states and the banks' posting confirmations into a stream processor that matches them within minutes and raises breaks immediately; the end-of-cycle file reconciliation becomes the final, authoritative check rather than the only one (see Batch vs Stream Processing).

5. Clearing, netting and settlement risk#

Clearing and settlement are where "the switch said success" turns into "the banks' money actually moved". They are also where a network can lose real money if a bank fails.

Clearing versus settlement. Clearing is the exchange of information: which payments happened and who owes whom. Settlement is the movement of money: the central bank (or a settlement bank) debits one bank's account and credits another's. A useful way to keep them apart is that clearing moves information, settlement moves funds. On a real-time account rail, the customer sees the money at once (the beneficiary bank credits Kai immediately), but the interbank settlement that covers that credit happens later, at the end of the cycle. Between the two, the beneficiary bank has effectively given credit to the remitter bank.

A worked netting example. Three banks, one cycle:

From → ToAmount
A → B₹500
B → A₹100
B → C₹300
C → A₹250
A → C₹50

Gross total: ₹1,200 in 5 obligations.

  • Bilateral netting (pair by pair): A and B net to A → B ₹400; B → C ₹300; A and C net to C → A ₹200. Three movements, ₹900 in total.
  • Multilateral netting (each bank against the whole system):
    • A: receives 100 + 250 = 350, pays 500 + 50 = 550, net −200 (pays)
    • B: receives 500, pays 100 + 300 = 400, net +100 (receives)
    • C: receives 300 + 50 = 350, pays 250, net +100 (receives)
    • Check: −200 + 100 + 100 = 0.

So the settlement system moves ₹200 out of A's account and ₹100 into each of B and C: a total of ₹200 instead of ₹1,200, an 83% reduction in the money banks must have available. At national scale the saving is far larger, because flows between big banks largely cancel out: millions of payments each way between two large banks may net to a small difference.

The algorithm is trivial; the controls are not. Computing net positions is one pass over the cycle's transactions, adding each amount to the payer bank's debits and the payee bank's credits. Even 50 million transactions take seconds in a stream or batch job. The important engineering is around it:

close_cycle(cycle):
    freeze(cycle)                                  # no new transactions may join
    pos = map participant -> {debits: 0, credits: 0, fees: 0}
    for t in completed_transactions(cycle):        # stream from the event log
        pos[t.payer_bank].debits  += t.amount_minor
        pos[t.payee_bank].credits += t.amount_minor
        apply_fees(pos, t)                         # interchange-like fees, switch fees
    for p in pos: p.net = p.credits - p.debits - p.fees_net
    assert sum(p.net for p in pos) == 0            # money is neither created nor lost
    assert count == count_from_independent_counter(cycle)
    publish_signed_files(cycle, pos)               # each bank gets its own detail
    send_settlement_instruction(central_bank, pos) # one instruction, many postings
    await confirmation(cycle)                      # then mark cycle SETTLED

The two assertions are the most valuable lines. The first catches any bug that loses or invents money. The second compares the number of transactions with a counter maintained by a different path (for example the orchestrator's own count of final states), so a bug that drops events between the orchestrator and the clearing engine cannot go unnoticed.

Settlement risk. In deferred net settlement, a bank can build up a large net debit during a cycle. If it fails before settlement (insolvency, a technical failure, a sanction), the other banks have already credited their customers for payments the failed bank was supposed to fund. Networks control this risk in several ways:

ControlHow it worksTrade-off
Net debit cap per bankThe switch tracks each bank's running net position in real time and declines new outgoing payments when it would exceed the capRequires a fast, consistent running total; payments may be declined at busy times
CollateralEach bank pledges securities or cash in proportion to its typical net debitTies up the bank's liquidity
Settlement guarantee fundBanks contribute to a shared fund that covers a defaulter's shortfallMutualises risk; needs governance
More cycles per dayShorter cycles mean smaller net positionsMore settlement operations and more files
PrefundingBanks deposit money in advance; each payment draws down the prefunded balanceNo credit risk; costs the banks liquidity
Real-time gross settlementEach payment is settled individually in central-bank moneyNo settlement risk; needs the central bank's system to handle every payment and banks to have liquidity at every moment

The running net debit cap is a hot-counter problem. Every outgoing payment from a large bank updates the same counter. At thousands of payments per second for one bank, a single row in a database becomes a bottleneck. The usual answer is to split the counter: give each orchestrator partition a slice of the bank's cap (say 1/64 each), let partitions decrement their slice locally, and rebalance slices every few hundred milliseconds. A partition that runs out of its slice asks the coordinator for more before declining. The cap is never exceeded, and the hot row disappears. This is the same technique used for inventory counters in flash sales (see Pattern: Dealing with Contention).

Settlement in different systems. Which model a system uses depends on who runs it and what it carries. Wikipedia's article on RTGS describes the two families: RTGS settles each payment individually and immediately, while net settlement systems accumulate payments during the day and the central bank adjusts accounts by the net amounts. Large-value systems usually use RTGS. India's RTGS and NEFT both run 24/7 (NEFT since December 2019, RTGS since 14 December 2020), which matters for an instant rail: if net settlement happens at any hour, cycles can continue through nights, weekends and holidays. Instant payment systems run by central banks themselves, such as Brazil's Pix (launched November 2020) and the Federal Reserve's FedNow (launched 20 July 2023), are in a natural position to settle in central-bank money as payments happen; the exact settlement mechanics of each system are set in its own rulebook.

Settlement failures. What if the central bank's system is unavailable at cut-off, or a bank's settlement account lacks funds? The cycle stays in "pending settlement"; the switch keeps processing payments into the next cycle (payments do not stop because settlement is late); the defaulting bank may be suspended from sending new payments until it funds its position; and the guarantee mechanism covers the shortfall if needed. These rules must be decided and tested in advance, because during an incident nobody should be inventing settlement policy.

6. Card rails: ISO 8583, holds, stand-in and who earns what#

The card networks are older than the internet, and their design shows it: compact binary messages, long-lived TCP connections and a clear split between real-time authorisation and batch clearing and settlement.

The four-party model. A card payment involves the cardholder, the issuer, the merchant and the acquirer, with the network between the banks. In practice more companies sit in the chain: the merchant often signs up through an ISO (independent sales organisation) or merchant service provider, uses a payment gateway for online checkout, and both acquirers and issuers frequently outsource technical processing to processors. Each hop is a separate system that can be slow or fail, which is why each must handle timeouts and reversals on its own.

Anatomy of an ISO 8583 message. A message is: the MTI (4 digits), one or two bitmaps saying which of the numbered data elements are present, then the data elements themselves. Wikipedia's ISO 8583 article gives an example primary bitmap 70 10 00 11 02 C0 48 04, which decodes to data elements 2, 3, 4, 12, 28, 32, 39, 41, 42, 50, 53 and 62. A few widely used elements in the 1987 version are 2 (primary account number), 3 (processing code: purchase, withdrawal, refund), 4 (amount), 11 (system trace audit number), 37 (retrieval reference number), 38 (authorisation code), 39 (response code) and 41 and 42 (terminal and merchant ids). The first bit of the primary bitmap says whether a secondary bitmap (elements 65 to 128) follows.

Why bitmaps? In the 1980s bandwidth was precious; sending only present fields, with a compact presence map, kept messages to a few hundred bytes. The cost is that the format is brittle and every network adds its own private fields, so "ISO 8583" in practice means "ISO 8583 as interpreted by this network".

Message pairs and what they mean.

MTIMeaningDelivery
0100 / 0110Authorisation request / response (dual message: auth now, clearing later)End to end, timed out and reversed if no answer
0120 / 0130Authorisation advice (for example after stand-in)Point to point, guaranteed delivery with retries
0200 / 0210Financial request / response (single message: auth and clearing in one, typical for ATM and many debit networks)End to end
0400 / 0410Reversal request / responseEnd to end
0420 / 0430Reversal advice / responseGuaranteed delivery
0800 / 0810Network management: sign-on, echo test, key changePoint to point

Dual versus single message. Credit card networks typically use dual-message processing: the 0100 authorises and places a hold, and a separate clearing record (in a batch file) later finalises the amount, which may differ (a restaurant tip, a hotel's final bill, a fuel pump that pre-authorised a fixed amount). Debit and ATM networks often use single-message processing (0200), where one message both authorises and clears.

Authorisation holds. An approved 0100 reduces the cardholder's available balance but not their ledger balance. If no clearing record arrives within the issuer's hold period (often days), the hold drops off. This is why a hotel can "authorise" $500 and capture $420, and why a reversal (0400) is important: without it, a timed-out authorisation would hold the customer's money for days.

Stand-in processing and its risk. When an issuer is unreachable, the network can approve on its behalf within limits the issuer set in advance (per transaction, per day, by merchant category, only for cards not on a block list). The network then sends 0120 advices so the issuer can update balances when it returns. Stand-in keeps commerce running through issuer outages, but the issuer carries the risk of approving a payment it would have declined. The real-time account rail cannot copy this, because a push payment moves money that must already exist in the account.

Network topology. Wikipedia describes a notable difference between the two largest card networks. Nearly all Visa transactions are processed at one of four data centres (Ashburn, Virginia; Highlands Ranch, Colorado; London; and Singapore), which can operate independently of each other and of external utilities, and can handle up to 30,000 simultaneous transactions. Visa's network is star-based: endpoints connect to the main data centres, where transactions are processed centrally. Mastercard's Banknet, which uses ISO 8583 and has its operations hub in St. Louis, is described as edge-based and peer-to-peer: transactions travel through a meshed network directly to other endpoints, so a single point of failure cannot isolate large numbers of them. A star is simpler to operate and to secure, and gives one consistent view of all traffic for fraud models; a mesh is more resilient to the loss of a central site, but harder to keep consistent and to observe.

Who earns what on a $100 card purchase. A worked example often used to explain card economics:

  • The merchant pays a merchant discount fee of $2.00, so it receives $98.00.
  • Of that, the acquirer keeps $0.25 as its markup, and $1.75 goes to the issuer as interchange.
  • The network charges the banks assessments and usage fees, for example a 0.11% assessment plus about $0.02 per transaction.

Interchange is set by the network (not negotiated issuer by issuer), and it compensates the issuer for the fact that it pays the merchant even if the cardholder never pays the issuer, for fraud losses and for rewards. Regulators cap it in some places: Wikipedia's interchange article notes that the European Parliament voted in March 2015 to cap interchange at 0.3% for credit cards and 0.2% for debit cards (for personal cards with an intermediary), and that after the US Durbin Amendment took effect in 2010, banks cut back the incentives on their checking accounts. The design point for the network: fees are computed per transaction during clearing, so the clearing engine needs the merchant category, card type, region and entry mode on every record, and fee tables are versioned data, not code.

Clearing files. At the end of the day, acquirers submit clearing records (one per captured transaction, with final amount, authorisation code and fee-relevant attributes). The network validates each one against its authorisation log (does an approved authorisation exist? does the amount fit?), computes interchange, and produces per-issuer files. Records that fail validation are rejected back to the acquirer. Settlement follows the same netting logic as in deep dive 5, with the network's settlement bank in the middle.

7. Security: PINs, HSMs, message signing, cryptograms and tokens#

A payment network is a high-value target: anyone who can send one valid-looking message can move money. Security is designed in layers, so that a breach of one layer (an app, a PSP, even the switch) does not let an attacker move money.

Layer 1: member authentication and message integrity.

  • Every member connects over mutual TLS with a certificate issued by the network's own certificate authority. A connection without a valid member certificate never reaches the application.
  • Every message is signed with the member's private key, held in an HSM, and the switch verifies the signature against the member's registered public key. The switch signs its own messages too. Signing gives integrity (no tampering in transit) and non-repudiation (a bank cannot later deny it sent a debit approval).
  • Members are reachable only over private links or a dedicated network, never the open internet, and the switch accepts traffic from known addresses only.

Layer 2: the PIN never travels in the clear. On the real-time rail, the payer's app encrypts the PIN together with transaction details (amount, transaction id) under a key that only the remitter bank can use. The PSP and the switch pass the encrypted block along without being able to open it. At the remitter bank, the HSM decrypts the block and compares it with the stored PIN verification value, all inside the HSM; the bank's application server only sees "PIN correct" or "PIN wrong". Binding the PIN block to the transaction details means a captured block cannot be replayed for another payment.

What an HSM is for. A hardware security module is a tamper-resistant device that generates and stores keys and performs cryptographic operations with them, but never lets the keys out in plain form. If someone opens the case, sensors wipe the keys. Payment HSMs are certified to strict standards and expose high-level commands ("verify this PIN block", "generate this card cryptogram") rather than raw keys. The switch uses HSMs for its own signing keys, for the keys it shares with each member (often stored encrypted under a master key, so the HSM holds one key and the database holds the rest in encrypted form), and for token and cryptogram operations on the card side. A national switch at 400,000 messages per second needs a cluster of HSMs sized for signature operations, with session-key caching so that not every message needs a slow asymmetric operation.

Layer 3: the device is bound to the user. As in the registration flow, the app proves that this phone holds this SIM and this registered device. A stolen PIN alone is not enough: the attacker also needs the user's bound phone. When a user changes phones, re-registration repeats the binding and often triggers a cooling period with lower limits (a common anti-fraud measure, because a SIM swap is a standard first step in account takeover).

Layer 4: chip cards and one-time cryptograms. A magnetic stripe holds static data: copy it once, use it forever. An EMV chip instead holds secret keys and, for each transaction, computes an ARQC (authorisation request cryptogram): a cryptographic signature over the amount, currency, date, a terminal-provided unpredictable number and a counter. Wikipedia's EMV article explains that the ARQC is sent in the authorisation message and that the card can also return a TC (transaction certificate, offline approval) or an AAC (offline decline). The issuer recomputes the ARQC with its copy of the card's keys; if it matches, the card is genuine and the message has not been replayed or altered. The EMV article also describes the liability shift: normally the issuer bears the loss from card fraud, but after a network implements a shift, a merchant or ATM owner whose terminal does not support EMV is liable instead. In the US, Mastercard, Discover and American Express shifted liability for point-of-sale terminals on 1 October 2015. That economic rule did more to move merchants and banks to chip than any technical argument.

Layer 5: tokenisation. A token is a substitute card number that works only in a limited domain: one phone, one merchant, or one type of transaction. If the token leaks, it cannot be used elsewhere, and it can be cancelled without replacing the physical card.

  • When Sam adds a card to a phone wallet, the card network's token service (acting with the issuer) creates a device account number (DAN) and provisions it, with its keys, to the phone's secure element. In Apple's model, as described in published explanations of Apple Pay, the phone stores the DAN in the secure element, Apple does not keep the card number, and each payment produces a one-time cryptogram from the DAN and transaction details, which the network validates. Another common wallet model stores the card on the wallet provider's servers and issues a payment token from there.
  • At authorisation time, the network sees the token's BIN range, looks up the real card number in its token vault, checks that the token is being used in its allowed domain, validates the cryptogram, and forwards the request to the issuer with the real card number (or with both).
  • Wikipedia's tokenisation article notes that EMVCo published a payment tokenisation specification in March 2014. Because the network does the mapping, merchants and acquirers never see the real card number, which shrinks their PCI DSS scope (the Payment Card Industry Data Security Standard has twelve requirements that apply wherever card numbers are stored or processed).

Layer 6: customer authentication online. Online card payments cannot use a chip cryptogram, so networks add 3-D Secure: the issuer authenticates the cardholder during checkout (often silently, using device and behaviour data, or with an app approval or OTP). Wikipedia's 3-D Secure article describes the three domains (issuer, acquirer and the interoperability domain run by the network), the issuer's access control server, and version 2.0, whose specification EMVCo published in October 2016 to send more context data and interrupt customers less often. In Europe, PSD2's strong customer authentication requires two of three factors (something you know, have or are) for most electronic payments, and India requires an additional factor of authentication for card-not-present payments.

Lessons from real incidents.

  • In 2016, as described in Wikipedia's SWIFT article, attackers stole $81 million from Bangladesh's central bank through its account at the Federal Reserve Bank of New York, by compromising the bank's own SWIFT Alliance Access software. The malware sent unauthorised payment messages, deleted the database records of the transfers, and even altered the printed confirmation reports so that staff would not notice. The network's cryptography was intact; the member's endpoint was not. A network cannot rely only on members' security: it needs independent, out-of-band controls, such as anomaly detection on members' outgoing traffic patterns and confirmations that do not flow through the member's possibly compromised systems.
  • In July 2025, Wikipedia's Pix article notes, a cyberattack on a software company that connected institutions to the system led to the theft of more than R$540 million (about US$100 million). Third-party connectivity and software providers are part of the attack surface; they need the same security standards and monitoring as members.

8. Fraud checks at network scale#

Banks and PSPs each run their own fraud checks, but each sees only its own customers. The switch sees every payment between every bank, which makes it uniquely good at spotting patterns that no single bank can see: money mules receiving small amounts from hundreds of banks, a burst of collect requests from one new account, or a device that has registered with five different PSPs in a day.

The budget: 20–30 ms, in parallel with routing. The risk engine runs while the switch resolves the payee address, so it adds little to total latency. It must never become the bottleneck: if it is slow or down, the switch falls back to a safe rule set (deep dive 9).

Features that matter.

FeatureExampleWhy
Velocity of the payerPayments and amount in last 1 minute, 1 hour, 1 dayAccount takeover drains accounts fast
Velocity of the payeeNumber of distinct payers in the last hourMule accounts receive from many victims
Payee age and historyVPA created 2 hours ago, never received beforeFresh accounts are used for scams
Device signalsNew device, recent SIM change, rooted phone, many PSP registrationsClassic account-takeover markers
RelationshipHas the payer paid this payee before?Most honest payments go to known payees
Initiation modeCollect request between individualsCommon scam channel
Amount patternJust under a limit, round numbers, repeated test payments of ₹1Fraudsters probe limits
Graph signalsPayee two hops from a known muleMule networks form clusters

Velocity counters at 47,000 updates per second. Each counter is keyed by entity and window (for example payee:kai@paybank:distinct_payers:1h). A sliding window can be approximated with a ring of small buckets (60 one-minute buckets for one hour), so an update increments one bucket and a read sums 60 numbers. "Distinct payers" needs a cardinality estimate; a HyperLogLog per payee per hour uses about 12 KB at standard precision and counts millions of distinct values with about 1% error (see Probabilistic Data Structures for Big Data). For most payees the count is tiny, so a small exact set that upgrades to HyperLogLog only above a threshold saves memory.

Decisions, not just scores.

  • Allow most payments (well over 99%).
  • Step up: ask for an extra confirmation in the app ("You are paying a new payee ₹40,000. Confirm?"), or a cooling delay for the first large payment to a new payee.
  • Hold: the payment waits a few minutes for a second check (used sparingly; instant rails promise instant payments).
  • Decline with a clear code.

Collect-request scams. The classic scam on account-to-account rails is social engineering, not hacking: the victim is persuaded to approve a collect request or to scan a QR code "to receive money". The network's levers:

  • Restrict person-to-person collect requests (lower limits, or allow only from verified merchants).
  • Make the app's approval screen unmistakable: "You are paying ₹5,000 to Sam (new payee)". Entering a PIN must always mean sending money; never ask for a PIN to receive.
  • Score collect requests heavily on payee age and on how many collect requests the payee sent recently.

Mule detection after the fact. Not everything can be caught in 30 ms. A background job runs graph analysis on the last days of payments: accounts that receive many small payments from unrelated payers and immediately pass them on form recognisable shapes. Results feed back into the real-time model as features ("payee in suspected mule cluster") and as alerts to the payee's bank, which can freeze the account under its own rules.

Feedback loops. Labels come from fraud reports and disputes, which arrive days or weeks later. Models must be trained on data as it looked at decision time (to avoid "leaking" future information), and evaluated by the money saved versus honest payments declined, not by accuracy alone: with fraud at maybe 1 in 10,000 payments, a model that declines nothing is 99.99% "accurate" and useless.

Scale of the problem. Wikipedia's UPI article cites RBI data reporting 29,082 digital fraud cases worth ₹1,457 crore in 2023–24. Compared with hundreds of billions of payments a year, fraud is rare per payment, but large in absolute harm, which is why the network-level view is worth its cost.

9. High availability at national scale#

A national payment rail has a strange availability profile. The switch itself can be made very reliable, but each payment also depends on two banks and two PSPs, any of which can fail. The design goal is therefore two-fold: the switch must almost never be the cause of a failure, and a failure anywhere else must stay local.

What availability means here. If the switch is 99.99% available and each of the four other parties is 99.9% available, a payment that needs all five succeeds about 0.9999 × 0.999^4 ≈ 99.59% of the time from availability alone. The weakest links are the members, not the switch. That is why the network measures and publishes per-bank success rates, and holds members to technical-decline targets: it gives banks a reason to invest in their own availability.

Two kinds of declines. A business decline (wrong PIN, not enough money, limit exceeded) is a correct answer. A technical decline (timeout, system error, bank unreachable) is a failure of the system. Dashboards, alerts and member targets track technical declines separately; mixing the two hides outages inside normal customer behaviour.

Active-active across data centres. The switch runs in at least two data centres in different regions (for disaster recovery, ideally more than a few hundred kilometres apart), both live:

  • Every member connects to both data centres, over separate links from separate carriers. A member that loses one link keeps working.
  • Each transaction partition has one leader at a time, in one of the data centres, with a synchronous replica in the other. A write is acknowledged only when both have it, so a data centre loss loses no acknowledged payment. Cross-site synchronous replication adds latency (a few milliseconds for sites a few hundred kilometres apart), which fits within the 100 ms budget.
  • Leader election needs a third vote. With only two sites, a broken link between them makes each think the other is dead, and both might act as leader ("split brain"), which could process the same payment twice. A small witness in a third location breaks the tie; only the side that can reach a majority (two of three) keeps leadership. This is the core idea of consensus protocols such as Raft and Paxos (see Consensus: Raft and Paxos).
  • A third site holds an asynchronous replica and backups for disaster recovery (see Disaster Recovery and Backups).

Each site sized for all traffic. If two sites each run at 60% at peak and one fails, the survivor would need 120%: an outage turns into a total outage. Each site must handle the full peak alone, so at normal times both run below 50%. This is the reason for the design capacity of 80,000 payments per second against a 32,000 peak: each site can carry the whole peak with headroom.

No planned downtime. Upgrades happen as rolling deployments, partition by partition, with canary releases on a small share of traffic (for example one partition and one small bank first) (see CI/CD and Deployment Strategies). Database schema changes are backward compatible (add columns, never rename in place). Routing tables, fee tables and limits are data, deployed with versioning and an instant rollback.

Overload protection. At festival peaks or during a bank's incident, demand can exceed capacity. The switch protects itself with:

  1. Per-member admission limits at the edge, sized to each member's agreed capacity.
  2. Priority classes: reversals and final status updates first (they close money already in flight), then new payments, then status checks, then non-financial requests (balance enquiries, account listing).
  3. Load shedding with a fast, explicit "try again" code rather than slow timeouts.
  4. Queue limits: a request that has waited longer than it can be useful (for example 5 seconds in an internal queue) is dropped, because its caller has probably given up already.

These are the controls whose absence turned a status-check flood into a five-hour outage in April 2025 (deep dive 3). See also Designing for High Availability.

Graceful degradation of dependencies.

Dependency downBehaviour
Risk engineFall back to conservative rules: lower limits, decline new payees above a threshold, allow known payees. Never "fail open" for all payments, never "fail closed" for all
A payee PSP (VPA resolution)Use short-lived cached resolutions for merchants; other payments to that handle fail fast with a clear code
A remitter bankCircuit breaker opens; new payments from its customers decline fast; reversals and checks queue for when it returns
Event stream to settlementOrchestrator keeps writing the transaction store; the outbox (see below) replays events when the stream returns
Central bank settlement systemPayments continue; cycles queue for settlement; net debit caps tighten

The outbox. The orchestrator must both update the transaction store and publish the "completed" event for settlement. If it writes one and crashes before the other, settlement and the switch disagree. The fix is the transactional outbox: in the same database transaction that marks the payment final, insert a row into an outbox table; a separate relay publishes outbox rows to the event stream and marks them sent. Settlement may see an event twice (after a relay crash) but never zero times, and it deduplicates by transaction id.

Data localisation. Many countries require payment data to be stored only inside the country; in India, payment data must be stored in India. That rules out using another country's region as a failover site, so both active sites and the disaster-recovery site must be in-country, ideally in different seismic zones and on different power grids.

Observability. The core metrics per member, per message type and per minute: request rate, success rate, technical-decline rate, p50 and p99 latency, timeouts, status checks per payment and reversals per payment. Every payment carries its transaction id through every log line, so one id retrieves its whole story across services (see Observability: Logs, Metrics and Traces).

10. QR codes, small payments and offline payments#

Most payments on a national rail are small. Wikipedia's UPI article notes that half of UPI transactions were below ₹200, and that the stream of tiny payments created a backlog that raised failure rates and affected the stability of the whole network. Each ₹20 cup of tea costs the same bank processing as a ₹20,000 rent payment: a PIN check, a core-banking debit, a credit and settlement entries. Three techniques reduce that cost.

1. An on-device small-value wallet. The user moves a small amount (say up to ₹2,000) from their bank account into a wallet held on the phone, authorising that top-up with their PIN. Small payments are then paid from the on-device balance without a PIN and without touching the remitter bank's core system. The bank sees one debit for the top-up instead of fifty debits for fifty teas. Wikipedia's UPI article describes NPCI's UPI Lite this way: an on-device wallet with a per-payment limit (originally ₹200, later raised) and a wallet limit of ₹2,000, introduced partly to save banks' computing power; RBI directed apps to support it. The beneficiary side still credits the payee's bank account normally.

Design consequences:

  • The on-device balance is a mirror of a balance the bank also tracks; the phone is not trusted as the only record. Each wallet payment is reported to the switch and bank, and the bank's view is authoritative.
  • Losing the phone loses access to the small balance but not the money: the bank can return it to the account after re-registration.
  • No-PIN payments are capped per payment and per wallet, so the worst case for a stolen unlocked phone is small.

2. Offline payments. A payment where the payer's phone has no internet is possible only if the payer's side can authorise without the network, which is exactly what an on-device wallet enables. Wikipedia describes the first phase of UPI Lite as debiting offline with the credit happening when the device comes back online. The engineering challenges are the same as for any offline-first ledger: preventing double spending (the device's secure storage holds a counter and balance that cannot be rolled back), bounding the risk with low limits, and reconciling when the device reconnects.

3. Payments without a smartphone. Not everyone has a smartphone or a data connection. Wikipedia's UPI article describes UPI 123PAY, launched on 8 March 2022 for about 400 million feature-phone users, with several modes including calling an interactive voice response number, app-based payments on feature phones, missed-call-based payments and sound-based (proximity) payments. All of them end in the same switch messages; only the front end differs. A good network design keeps that separation: channels are many, the core flow is one.

QR codes in more depth. The four QR modes (merchant-presented or consumer-presented, static or dynamic) map to different risk and reconciliation properties:

ModeExampleReconciliationRisk
Static merchant QRPrinted code at a vegetable stallMerchant matches payments by time and amount, or simply trusts notificationsSticker fraud: a scammer pastes their own QR over the shop's
Dynamic merchant QRCode on a supermarket checkout screen with amount and order idExact: the payment carries the order idLow; the code expires
Static consumer QRA customer's fixed code (rare)WeakHigh if copied
Dynamic consumer QROne-time code in the customer's app, scanned by the shopExactLow; single use, short expiry

Sticker fraud is worth a design response: the payment app shows the verified merchant name resolved from the switch (not the name printed in the QR), so a customer who expects "Ravi's Vegetables" and sees "Unknown Person" can stop. Merchants also get an instant audio confirmation device ("₹50 received") so they know the money reached them, not someone else.

Interoperable QR standards. A shop should not need a different QR for every app or network. India's BharatQR, which Wikipedia's RuPay article describes as developed by NPCI with Mastercard and Visa and launched in September 2016, was designed as one interoperable QR code across card networks. EMVCo also publishes a merchant-presented QR specification used in many countries. For the switch, the lesson is to define one canonical payment payload and let every QR format and channel translate into it at the edge.

11. Digital wallets: where the money actually sits#

"Wallet" means very different things, and the differences decide who holds money, who carries risk and how the network treats the payment.

KindWhere the money isExampleWhat the network sees
Pass-through (token) walletStill on the card or in the bank account; the wallet holds only a tokenPhone wallets that store a card tokenA normal card authorisation, with a token instead of the card number
Stored-value (prepaid) walletIn the wallet provider's pooled bank account, as a liability to the userPrepaid app wallets, transit cardsTop-ups (bank or card payments into the pool), payouts (from the pool), and internal transfers that the network never sees
Bank app or UPI appIn the user's own bank accountPayment apps on an account-to-account railEvery payment as a switch transaction
On-device small-value walletA small balance moved from the bank account and mirrored on the phoneUPI LiteTop-ups and periodic reporting; small payments without the bank's core system

Pass-through wallets. These add security, not a new place for money. Published comparisons of Apple Pay and Google Pay describe two token models: in the Apple model, Apple does not store card information; the bank returns a device account number that the iPhone stores in a dedicated hardware chip, and at payment time the merchant passes this DAN to the bank. In the Google model, the card is stored on Google's servers and the phone holds a payment token; at payment time the merchant passes the token to Google, which looks up the card and passes it to the bank. Either way, for the network the wallet appears as a token BIN range plus a cryptogram (deep dive 7).

Stored-value wallets. Here the wallet company holds a pooled bank account (often an escrow or trust account) and keeps its own ledger of how much each user owns. Transfers between two users of the same wallet are just two ledger entries inside one company: instant, cheap and invisible to the national network. That is their strength and their weakness:

  • Strength. No bank calls per payment; the provider can offer instant, free transfers inside its own network.
  • Weakness: closed loop. A user of wallet A cannot pay a user of wallet B unless the two interconnect. Each wallet becomes a walled garden, and merchants must accept many wallets.
  • Risk. If the provider fails or mismanages the pool, users' money is at risk. Regulators therefore require the pool to be held at a bank, ring-fenced, and reconciled daily against the sum of users' balances, and limit balances for users who have not completed full identity checks (KYC: know your customer).

An account-to-account rail like UPI turned this model inside out: the "wallet" app holds no money at all, and every app can pay every other app's users because all of them speak to the same switch. That interoperability is the core reason a national switch beat closed-loop wallets in markets where it launched.

Ledger design for a stored-value wallet. A wallet provider's ledger is a classic double-entry system: every movement is a balanced set of entries, and each user's balance is the sum of their entries (with a cached balance for speed). The invariant that regulators care about is sum of user balances = balance of the pooled bank account, checked every day. The separate payment system case study covers double-entry ledgers in detail.

The PSP bank is a dependency, too. On an account-to-account rail, third-party apps connect through PSP banks, and a regulator can stop a bank's activities. Wikipedia's Paytm article notes that on 31 January 2024 the RBI ordered Paytm Payments Bank to stop most of its activities (from late February, later extended to 15 March 2024). For a network designer this is a reminder that handles and PSP sponsorship must be portable: the network should let a third-party app operate through several PSP banks, with users' VPAs migrated from one handle to another without breaking their payments, and with the routing table updated as data. A design where an app's identity is welded to one bank has a single point of regulatory failure.

Market concentration as a systemic risk. If one app carries most of a national rail's volume, an outage of that app is close to an outage of the rail. Wikipedia's UPI article notes that NPCI defined a 30% market-share cap for third-party apps in March 2021 (with a long compliance period and an alert system near 25–27%). Whatever one thinks of the policy, the engineering point holds: diversity of front ends is part of a network's availability.

12. Cross-border payments and foreign exchange#

Domestic rails stop at the border. Paying someone in another country needs three things that a domestic switch does not have: a way to reach the foreign bank, a currency conversion, and a way for the two countries' banks to settle.

The traditional path: correspondent banking over SWIFT. SWIFT, founded in 1973 and based in Belgium, is a messaging network: per Wikipedia it linked more than 11,000 financial institutions in over 200 countries and territories, exchanging over 32 million messages a day on average in 2015. It does not hold accounts or move money itself; it carries the payment instructions. The money moves through correspondent accounts: banks hold accounts at each other (or at a shared intermediary bank) in each currency. A US dollar payment from a bank in India to a bank in Kenya may hop through one or two correspondent banks, each debiting one account and crediting another, each taking a fee and some time.

How a SWIFT message travels is itself a nice example of store-and-forward reliability: the sending bank's message goes to a regional processor that validates it, a slice processor stores it before the sender receives an ACK (accepted) or NAK (rejected), the message is forwarded to the destination region, given an output sequence number, delivered to the receiving bank, and the receiving bank answers with a positive or negative user acknowledgement. Every step is stored before it is acknowledged, which is exactly the write-ahead discipline of deep dive 1.

The weaknesses are well known: Wikipedia's SWIFT article cites a 2018 Financial Times criticism that transfers "pass through multiple banks" and lack transparency on how much will arrive. SWIFT's response, gpi (Global Payments Innovation), adds end-to-end tracking with a unique reference and fee transparency; SWIFT has claimed half of gpi payments complete within 30 minutes.

Currency conversion, step by step. Suppose Sam in the US pays $100 to a seller in Europe who receives euros. A payment provider in the middle:

  1. receives $100 from Sam's bank into its US dollar account,
  2. sends the dollars to its account at a foreign-exchange provider,
  3. the FX provider's funding pool (a stock of currencies it bought in advance) gives, say, €88 for the $100, credited to the provider's euro account,
  4. the provider pays €88 to the seller's bank.

Behind the funding pool sits a layered market: retail FX providers top up their pools in the wholesale market (investment banks, commercial banks, FX firms), which in turn trades with the largest multinational banks at the top. For a payment network, the design lessons are: quote the rate and fee before the payer confirms; lock the quote for a short window (seconds to minutes); and record both currency amounts and the rate on the transaction, because reconciliation happens in both currencies.

The new path: linking fast payment systems. Instead of correspondent chains, two countries can connect their domestic instant rails through a gateway:

  • The payer's app asks for a quote: "₹10,000 to a Singapore account, how much arrives?" The FX provider returns a rate and fee, valid for a short time.
  • The payment flows over the payer's domestic rail to the gateway, across to the other country's gateway, and over that country's domestic rail to the payee's bank. Each domestic leg uses its own country's rules.
  • The FX provider (or a settlement bank) holds accounts on both sides: it receives rupees on one side and pays Singapore dollars on the other, then rebalances its positions in the wholesale market.

Wikipedia's UPI article describes such a link between UPI and Singapore's PayNow (work started in September 2021), and the multilateral Project Nexus, for which the Bank for International Settlements signed an agreement on 30 June 2024 with the central banks of Malaysia, Thailand, the Philippines, Singapore and India, aiming to interlink their domestic fast payment systems. A multilateral hub replaces n × (n − 1) / 2 bilateral links (45 for 10 countries) with n connections (10), the same reasoning that justifies a domestic switch.

What cross-border adds to the design.

ConcernDomestic railCross-border
Sanctions screeningRareRequired on every payment: names, countries, lists
Message formatDomestic formatUsually ISO 20022, translated at the gateway
SettlementOne central bank, one currencyTwo currencies, often a settlement agent per side
TimeoutsSecondsSeconds to minutes; time zones and operating hours differ
Refunds and disputesOne regulator's rulesTwo regimes, plus FX on the way back (the refund may be worth a different amount)
LimitsDomestic limitsForeign exchange and remittance limits, purpose codes

The rest of the design (idempotent transaction ids, a state machine with unknown states, reconciliation, net settlement) carries over unchanged. A good design keeps it that way: cross-border is a new edge adapter and settlement arrangement, not a different core.

Bottlenecks and Failure Modes#

Failure / hotspotImpactMitigation
A large remitter bank slows down or failsIts customers' payments time out; unknown outcomes pile up; retries flood the switchPer-bank circuit breaker, fast declines with a clear code, priority for reversals and checks, member targets on technical declines
Status-check or retry stormShared capacity exhausted; success rate collapses for everyone (as on 12 April 2025)Enforce check limits at the edge (3 checks, 90 seconds apart), separate quotas and worker pools, retry only at one layer, back-off with jitter
Credit leg timeout after a successful debitPayer debited, payee not credited; customer anger and regulatory penaltiesDeemed state shown as pending, active status checks, reversal well within T+1, settlement-file reconciliation as the final word
Duplicate request from a retryDouble debitOriginator transaction id as primary key at the switch; banks deduplicate on (transaction id, leg); reversals keyed by original id
Split brain between data centresTwo leaders process the same partition; possible double processingThird-site witness, majority-based leader election, fencing tokens on writes
Hot counter for a bank's net debit capOne row takes thousands of updates per second; latency and contentionSplit the cap into per-partition slices with periodic rebalancing
Payee PSP down (VPA resolution)Payments to all its handles fail even when banks are fineShort-lived cache for merchant resolutions, fast failure for others, PSP availability targets
Risk engine slow or downEither blocks all payments or lets fraud throughStrict timeout on the score, fallback rule set that is conservative for new payees and generous for known ones
Event stream to settlement lags or loses eventsSettlement disagrees with the switch; money not settledTransactional outbox, count checks between orchestrator and clearing engine, sum-to-zero assertion
Settlement cut-off skewSame payment counted in different cycles by different partiesOne authoritative cycle clock at the switch; temporary-break handling in reconciliation
Member endpoint compromisedFraudulent but validly signed messagesOut-of-band anomaly detection on members' traffic, per-member limits, confirmations outside the member's systems, fast suspension
Festival or salary-day peakLoad several times the daily averageEach site sized for full peak alone, admission control, on-device wallets for small payments, load tests at 2× forecast

What Interviewers Expect#

Mid-level. Draw the parties correctly: payer app, payer PSP, switch, payee PSP, remitter bank and beneficiary bank for the account-to-account rail; terminal, acquirer, network and issuer for cards. Explain debit-then-credit and why a failed credit needs a reversal. Use a transaction id as an idempotency key. Explain the difference between authorisation and settlement for cards. Give rough numbers (thousands to tens of thousands of payments per second) and a sensible storage estimate.

Senior. Treat timeouts as unknown outcomes with their own states, and explain status checks and reversals with deadlines. Explain nested timeouts and retry amplification. Describe clearing, net settlement with a worked example, and the settlement risk it creates (caps, collateral, guarantee funds). Design the switch as a partitioned, event-driven state machine with write-ahead state changes and an outbox. Discuss per-bank circuit breakers, rate limits per member and active-active data centres with synchronous replication. Know ISO 8583 at the level of message types, stand-in processing and reversals.

Staff and above. Reason about the network as an ecosystem: incentives (interchange, member success-rate targets, liability shifts), systemic risks (market concentration, a PSP bank stopped by a regulator, a compromised member), and the trade-offs between federated and central directories, deferred net and gross settlement, and star versus mesh topologies. Bring real incidents (the April 2025 status-check flood, the 2016 SWIFT heist) and explain what each implies for enforcement at the edge and out-of-band controls. Plan for growth: small-value offloading, cross-border links through a hub, ISO 20022 migration, and regulatory changes (fees, limits) as configuration rather than code.

Deep Dive: sizing the switch, tier by tierShow

The capacity section gave the totals. Here we turn them into machines, using the design capacity of 80,000 payments per second (about 2.5× the expected peak, so one data centre can carry the peak alone with room to spare).

In-flight payments (Little's law). The number of payments in progress at once equals the arrival rate times the time each one takes. At the 32,000 per second peak with an average of 2.5 seconds per payment (mostly bank time): 32,000 × 2.5 = 80,000 payments in flight. During a bank incident, where that bank's share of payments (say 15%) waits for the full 10-second leg timeout: 0.15 × 32,000 × 10 = 48,000 extra, so about 130,000 in flight. Each in-flight payment costs a database row, a timer and perhaps 2 KB of worker memory: about 260 MB across the cluster. Cheap, because the design is event-driven; a thread-per-payment design would need 130,000 threads.

Edge tier. 1 million messages per second at design capacity, each needing TLS processing and one signature verification; outgoing messages need one signature each.

  • Signature verification with a 2048-bit RSA key costs on the order of tens of microseconds of CPU per operation; elliptic-curve verification costs somewhat more per verify but signing is cheaper. Plan about 50 µs of CPU per verify and 0.5–1 ms per RSA sign, or move signing to faster elliptic-curve keys.
  • Signing 500,000 outgoing messages per second with RSA in software would need hundreds of cores, so signing is done with elliptic-curve keys, or with keys held in a cluster of network HSMs rated for tens of thousands of operations per second each (sized at 20–40 HSMs per site), or with session keys (sign a session, then authenticate messages with fast symmetric codes inside it).
  • Edge servers: with 32 cores each handling about 20,000 messages per second, about 50 servers per site at design capacity.

Orchestrator tier. 80,000 payments per second × 6 state changes = 480,000 state transitions per second. A worker on 16 cores handles about 5,000 payments per second (CPU for parsing, rules, building messages), so about 16–20 workers per site at design load, rounded up to 32 for headroom and failure, with 512 partitions spread across them.

Transaction store. 480,000 writes per second plus reads. With synchronous replication, each write costs about 2–5 ms of latency but not much throughput if batched. A shard on NVMe can sustain about 10,000–20,000 small replicated writes per second comfortably, so 48–64 shards, each a leader in one site and a synchronous follower in the other, plus asynchronous copies at the disaster-recovery site. Data per shard for 7 hot days: 15 TB / 64 ≈ 230 GB, which fits in fast storage with indexes.

Message log. 1 million messages per second × 3 KB = 3 GB/s raw at design capacity, about 600 MB/s after compression. A Kafka cluster of 30–40 brokers per site with replication factor 3 handles this, with retention of a few days before files move to object storage.

Risk engine. 80,000 scores per second at design load, each about 2 ms of CPU for a gradient-boosted tree model over 200 features, plus 5–10 feature reads: about 160 cores, so 10–20 servers per site, and a replicated in-memory feature store of 1–2 TB (velocity counters for hundreds of millions of accounts and devices).

Settlement. Small: one stream job aggregating completed payments into cycles, plus a relational database for positions and files. A single primary with a standby is enough; correctness matters, not scale.

Network. 10 Gbit/s of member traffic at peak, carried over redundant links to each site, plus cross-site replication traffic of a similar size. Members connect with at least two links from different carriers to each site.

Summary per site (each able to carry the full load).

TierSize
Edge (TLS, signature, rate limits)about 50 servers plus an HSM cluster
Orchestrators32 workers, 512 partitions
Transaction store64 shard leaders or followers
Message log30–40 brokers
Risk engine10–20 servers plus a 1–2 TB in-memory feature store
Routing and configa handful of servers; tables held in every orchestrator's memory
Settlementprimary plus standby

The point of this exercise is not the exact counts but the shape: the expensive parts are cryptography and the replicated transaction store, not the "business logic". Interviewers often expect the candidate to notice that signatures at a million messages per second are a real cost.

Deep Dive: the arithmetic of unknown outcomes, retries and utilisationShow

How many payments end unknown? Suppose each bank leg times out with probability p (the request or the reply is lost, or the bank is too slow). A payment has two legs, so roughly 2p of payments see at least one timeout. With p = 0.1% on a good day, 0.2% of 700 million is 1.4 million unknown outcomes a day. Most resolve within minutes through a late reply or one status check. If 2% of them are still unresolved after the allowed checks, about 28,000 a day go to reconciliation and possibly reversal. Every one is a customer whose money is "stuck", so cutting p is worth a lot: a bank that halves its timeouts halves its complaints.

Retry amplification as a formula. If each of k layers retries up to r times when it sees a timeout, and the failure rate is f, the expected number of requests reaching the bottom per user action is roughly (1 + r·f)^k for small f, and up to (1 + r)^k when f approaches 1. With k = 3 and r = 3:

Timeout rate fLoad multiplier
1%about 1.09
10%about 2.2
50%about 15.6
100%64

The danger is the feedback loop: more load causes more timeouts, which cause more retries, which cause more load. Once f passes a threshold, the system cannot recover until something cuts the retries. That is the mechanism behind most "retry storm" outages, and why the design limits retries to one layer and caps them with a budget.

Why sites run below 50%. In a simple queueing model (one server, random arrivals), the average time in the system is the service time divided by (1 − ρ), where ρ is utilisation. At ρ = 0.5 the wait doubles the service time; at ρ = 0.8 it is 5×; at ρ = 0.95 it is 20×. Real systems with many servers behave better than this single-server model, but the shape holds: latency rises sharply near full utilisation. Running each site at 40% normally means that if it suddenly receives the other site's load (80%), latency rises noticeably but the system stays stable. Running each at 70% would push the survivor past 100% during a failover, which is an outage.

Netting efficiency. For n banks with gross obligations G in a cycle, multilateral netting moves at most n settlement postings and a total of (1/2) × Σ|net_i| in value. The saving ratio is 1 − (Σ|net_i| / 2) / G. For two equal banks paying each other similar amounts, it approaches 100%; for a network where small banks mostly send and big banks mostly receive, it is lower. Shorter cycles reduce the net positions (and so settlement risk) but also reduce the netting saving, because fewer opposite flows fall in the same cycle. The cycle length is therefore a trade-off between liquidity cost and credit risk, decided by the central bank and the network together.

Settlement risk exposure. If a bank's net debit grows at a rate of d per hour during a cycle of length T hours, its peak exposure at cut-off is about d × T. A bank sending ₹2,000 crore net per hour with 4-hour cycles has a peak exposure of ₹8,000 crore before settlement. A net debit cap at, say, ₹5,000 crore would start declining that bank's outgoing payments in the fourth hour; doubling the number of cycles halves the exposure instead. These numbers are illustrative, but the relation (exposure ∝ rate × cycle length) is the one that drives the design.

Fraud model thresholds. Suppose the fraud rate is 1 in 10,000 payments and a model, at some threshold, catches 80% of fraud while flagging 0.5% of honest payments. Out of 1 million payments, 100 are fraud: 80 caught, 20 missed. Of the 999,900 honest ones, about 5,000 are flagged. So only 80 / 5,080 ≈ 1.6% of flagged payments are fraud. Declining all flagged payments would anger 5,000 honest people to stop 80 frauds. That is why the network uses step-up (a confirmation screen) for most flagged payments and hard declines only for the highest scores: step-up costs an honest user a few seconds, not a failed payment.

Deep Dive: disputes, chargebacks and regulatory deadlinesShow

Every payment network needs a way to fix payments that went wrong, and the regulator usually sets the deadlines. Disputes are a long-running workflow across several companies, so they are designed as state machines with timers, not as emails.

Account-to-account rail: failed and wrong payments. The RBI circular of 20 September 2019 (effective 15 October 2019) sets turnaround times for failed transactions across Indian payment systems. Its principle is that for a credit-push transfer where the payer was debited but the beneficiary was not credited, the credit must happen within the deadline, or the money must come back, otherwise a penalty is paid to the customer. For UPI it specifies:

CaseDeadlineCompensation if late
Payer debited, beneficiary not credited (fund transfer)If the credit cannot be made, auto-reversal by the beneficiary bank by T+1₹100 per day beyond T+1
Payer debited, no confirmation at the merchant (payment to merchant)Auto-reversal within T+5₹100 per day beyond T+5

The same circular sets T+5 for ATM cash not dispensed and T+1 for IMPS failures. Note that the circular puts the T+1 reversal on the beneficiary bank: it is the bank that received funds it could not apply. The switch's job is to make sure that bank knows (through the settlement file and break reports) and to track that the reversal happened.

The complaint path. A customer usually starts in their payment app. In UPI's published dispute process, complaints escalate from the app to its PSP bank, then to the customer's bank, then to NPCI, and finally to the banking ombudsman. Common complaint types include "debited but not credited", "transaction timed out but account debited", "paid to the wrong person" and "merchant did not deliver".

Automate the first step. Most "debited but not credited" complaints are already being fixed: the payment is in DEEMED or REVERSAL_PENDING, or the reversal has already happened and the customer has not checked. An automatic lookup by transaction id or RRN at the moment the complaint is raised answers most of them instantly ("Your ₹500 was returned to your account at 14:03 today, reference R123") and keeps human teams for real disputes.

Wrong-payee payments. A push payment to the wrong VPA is not a network failure: the money arrived where the payer sent it. The network cannot reverse it on its own, because that would take money from the recipient without consent. The fix is a request to the recipient's bank, which contacts the recipient. The design response is prevention: always show the resolved name of the payee before the PIN screen, and warn on first payments to new payees.

Card rails: chargebacks. Cards give the cardholder stronger reversal rights. In the US, as Wikipedia's chargeback article notes, credit cardholders have reversal rights under Regulation Z (Truth in Lending Act) and debit cardholders under Regulation E (Electronic Fund Transfer Act). The issuer raises a chargeback with a reason code; codes vary by network but fall into four broad categories:

CategoryExamples
TechnicalExpired authorisation, insufficient funds, processing error
ClericalDuplicate billing, wrong amount, refund never issued
QualityGoods not received as promised
FraudCardholder did not authorise the purchase

The network carries the chargeback from the issuer to the acquirer, the acquirer debits the merchant, and the merchant may contest it with evidence ("representment"), after which the network may arbitrate. Networks also police merchants with too many disputes: Wikipedia notes that from 1 April 2025 Visa merged five existing fraud and dispute programmes into a single Visa Acquirer Monitoring Program (VAMP). For the network's systems, chargebacks are clearing records with their own message types and deadlines, settled through the same net settlement as purchases (in the opposite direction).

Design checklist for dispute systems.

  • Every dispute links to the original transaction id and all party references.
  • Every state has a deadline timer; a missed deadline escalates automatically and is visible in metrics (regulators ask for these numbers).
  • Evidence (messages, logs, statements) is attached from the message log automatically, not collected by hand.
  • Outcomes become new transactions (refund, reversal, chargeback) so the ledger and settlement stay consistent.
  • Workflow engines that persist state and timers (see Pattern: Managing Long-Running Tasks) fit this far better than ad-hoc cron jobs.
Deep Dive: one payment, end to end, with a timeoutShow

Asha buys medicine for ₹1,240 at a pharmacy at 7:42 p.m. on a busy evening. The pharmacy shows a dynamic QR code on its billing screen.

  1. 19:42:05.000. Asha scans the QR. Her app parses upi://pay?pa=pharmacy@paybank&pn=City%20Pharmacy&am=1240.00&tr=BILL-88123. The app asks her PSP to resolve the payee; the screen shows "City Pharmacy (verified merchant)", which matches the shop's name. She enters her PIN; the app encrypts it, bound to the amount and a new transaction id OKB4F2... (the prefix names her PSP).
  2. 19:42:05.600. Her PSP checks the device binding (this phone, this SIM), runs its own velocity rules (third payment today, normal), signs the request and sends it to the switch.
  3. 19:42:05.630. The switch edge verifies the signature, checks the PSP's rate limit (well within quota) and passes the message to the orchestrator partition that owns this transaction id. The orchestrator inserts the transaction with state RECEIVED. In parallel: the risk engine scores it (known merchant category, normal amount, payee receives thousands of payments a day: low risk, 9 ms), and the routing service finds the payee's handle paybank. Because this is a verified merchant, a resolution cached 40 seconds ago is still valid, so no call to the payee PSP is needed. State: RESOLVED, then DEBIT_PENDING.
  4. 19:42:05.680. Debit request to Asha's bank. Its core system is busy (evening peak), but it verifies the PIN in its HSM, checks the balance and debits ₹1,240. Reply at 19:42:06.900. State: DEBITED, then CREDIT_PENDING.
  5. 19:42:06.910. Credit request to the pharmacy's bank. Tonight that bank is struggling: its success rate has dropped to 85% in the last minute, and this request gets no reply. At 19:42:16.910 the 10-second leg timer fires. State: DEEMED. Asha's app shows "Payment pending. Do not pay again. We will update you shortly." The pharmacy's billing system, which polls its PSP for the bill reference, shows "Pending".
  6. 19:42:17. The pharmacist hesitates. Their training (and the shop's software) says: a pending payment is not a failure; wait or take the customer's number. Asha does not pay twice.
  7. 19:43:47. First status check from the recovery service, 90 seconds after the timeout (the network rule). The pharmacy's bank has recovered and replies: "credited at 19:42:09, reference P77812". Its reply to the original credit request was lost inside the bank's overloaded gateway; the credit itself was applied.
  8. 19:43:47.050. State: SUCCESS. The orchestrator writes the final state and an outbox row in one transaction, and sends results to both PSPs. Asha's app shows "Paid ₹1,240 to City Pharmacy"; the shop's audio device announces the payment; the billing screen turns green.
  9. 19:44. The completed event reaches the clearing engine and is assigned to the current settlement cycle. Asha's bank's net position for the cycle goes down by ₹1,240; the pharmacy's bank's goes up by the same amount.
  10. Cycle cut-off. The settlement file lists the payment for both banks. Both reconcile it against their records: matched. The central bank moves the net amounts between the banks' settlement accounts, ₹1,240 being a tiny part of them.

What would have happened if the pharmacy's bank had replied "not credited" at step 7? The orchestrator would have sent a reversal; Asha's bank would have returned the ₹1,240 within seconds or minutes; her app would show "Failed. Money returned". The pharmacy, seeing "failed", would ask her to pay again, which is now safe. And if the bank had stayed silent through all three allowed checks, the payment would stay pending until the settlement-file reconciliation, with reversal by T+1 at the latest, and the customer could see a status on their app at every point.

The lesson of this walk-through: the 40 seconds of uncertainty were handled entirely by states, timers and rules, with no human, no double payment and no lost money.

Deep Dive: a 45-minute interview plan for this problemShow
MinutesWhat to do
0–5Clarify scope: switch or bank or app? Account-to-account, cards, or both? Scale, latency target, settlement model, reversibility, regulator deadlines
5–10Requirements and numbers: 700 M payments a day, 32,000 per second peak, about 12 messages per payment, switch p99 under 100 ms, 99.99% availability
10–20High-level design: parties and flows (push, collect, card authorisation), debit then credit, the switch as router and state machine, settlement afterwards
20–25Data model: transaction, legs, settlement positions; transaction id as idempotency key; shard by transaction id
25–40Deep dives chosen with the interviewer: timeouts and unknown outcomes, reconciliation and settlement, availability with two active sites and a witness, fraud scoring
40–45Bottlenecks and evolution: sick banks, retry storms, hot counters; small-value wallets, cross-border

Follow-up questions to prepare for.

  1. The credit leg timed out. What do you tell the payer? "Pending", never "failed"; then status checks and reversal.
  2. How do you stop a double debit when the PSP retries? Transaction id as primary key; banks deduplicate on (id, leg).
  3. Why not two-phase commit between the banks? Independent organisations, blocking on coordinator failure, and sagas with reversal are simpler and auditable.
  4. What does the switch store about users? As little as possible: handles, references, transaction records; not PINs, not full account details.
  5. How do banks actually get paid? Net settlement per cycle at the central bank; show the netting arithmetic.
  6. What if a bank cannot fund its net position? Caps, collateral, guarantee funds, suspension.
  7. A big bank's success rate drops to 40%. What happens? Circuit breaker, fast declines, priority for reversals, alerting, publish status.
  8. How would you have prevented the April 2025 outage? Enforce check limits at the edge, separate quotas, retry budgets.
  9. How do you keep fraud scoring from slowing payments? Run in parallel with resolution, strict timeout, fallback rules.
  10. How does a card payment differ? Authorisation hold now, clearing and settlement later; stand-in; chargebacks.
  11. How do you handle two data centres and a network partition between them? Witness, majority-based leadership, fencing.
  12. How would you add cross-border payments? Gateway, FX quote and lock, settlement agents, sanctions screening, ISO 20022.
Deep Dive: comparing rails, and why message formats matterShow

A designer should know where the real-time account rail sits among the other rails, because interviewers often ask "why not just use X?".

RailSpeed to customerSettlementReversibilityTypical useMessage style
Card networksAuthorisation in about 1–2 s; funds a day or two laterDeferred net, dailyChargebacks for weeks or monthsShops, online checkout, travelISO 8583 (binary)
Real-time account-to-account (UPI, Pix, FedNow)Seconds, 24/7Deferred net in cycles, or per payment in central-bank money, by systemFinal; refunds and disputesPerson to person, small merchants, billsCountry-specific formats; ISO 20022 in many systems
Batch credit transfers (US ACH)Next day (same day optional)Batches through an operatorReturns within rule windowsPayroll, bills, direct debitsFixed-width batch files
RTGS (large value)SecondsEach payment individually, in central-bank moneyFinalInterbank and high-value paymentsIncreasingly ISO 20022
Correspondent banking over SWIFTMinutes to daysThrough correspondent accountsHard; recall requestsCross-borderSWIFT MT messages, moving to ISO 20022

Batch rails in a little more detail. In the US ACH network, a company that pays salaries sends a file through its bank (the originating depository financial institution, ODFI) by a cut-off such as 7 p.m.; the ODFI forwards the batch to an ACH operator (the Federal Reserve's FedACH or the privately run EPN), which processes it around midnight and makes it available to the receiving banks (RDFIs), which apply it when they open in the morning. Same Day ACH has existed since 2018. Batch rails are cheap per payment and fine for payroll, but cannot serve a shop counter. That gap is exactly what real-time rails fill.

ISO 8583 versus ISO 20022. ISO 8583 is compact, fast to parse and universal in card authorisation, but its fields are short, its meaning varies by network and it carries little structured data (no rich remittance information, limited party details). ISO 20022 describes messages as a model (UML) from which XML (and other) syntaxes are generated, with rich, structured fields for parties, purposes and references. Wikipedia's ISO 20022 article notes that Australia's New Payments Platform (launched February 2018) uses it, that FedNow and the RTP network use it, that the Eurosystem moved its RTGS to T2 on ISO 20022 in March 2023, and that Fedwire Funds was scheduled to begin using it in July 2025. SWIFT is the registration authority for the standard.

For a switch designer the practical consequences are:

  • Bigger messages. An ISO 20022 XML payment message is several kilobytes, against a few hundred bytes for ISO 8583. At a million messages per second that is a real bandwidth and parsing cost; binary encodings of the same model or efficient streaming XML parsers matter.
  • Better data, better fraud and compliance. Structured names, addresses and purpose codes make sanctions screening and fraud models more accurate, and make reconciliation less fuzzy.
  • Translation at the edge. Most networks live with both for years: translate at the edge into one canonical internal model, and keep the core format-agnostic.
Deep Dive: variants of the problemShow

"Design a card network" (Visa-like) instead. The core changes: authorisation routing by BIN, ISO 8583 connections to thousands of processors, stand-in processing, a token vault, dual-message clearing with daily files, interchange calculation, and chargeback workflows. Availability is judged by the authorisation path; clearing can be hours late without customers noticing. The topology question (star with central sites versus mesh with edge processing) is a good senior-level discussion.

"Design the bank side" (a remitter or beneficiary bank's UPI gateway). The bank must answer debit and credit requests within the network's timeouts while its core banking system may be decades old and batch-oriented. Typical design: a fast front layer that verifies PINs (HSM), holds an in-memory shadow balance or places holds, and posts to the core system asynchronously; strict deduplication on transaction id; its own reconciliation against the switch's settlement file. Many bank-side failures come from the core system's peak capacity, which is why on-device wallets and network limits on non-payment calls help banks most.

"Design a payment app" (a third-party app on the rail). Device binding, multiple PSP sponsor banks, VPA management, a payment history built from the switch's results, offline-safe UX (never show "failed" for unknown), rewards and fraud warnings. The app does not move money; its correctness problem is showing the truth.

"Design a closed-loop network" (a transit card or a campus wallet). One company holds all balances: payments are ledger transfers inside one database, with a pooled bank account behind it. The hard parts move elsewhere: offline terminals (tap at a gate with no network, reconcile later), stored-value security on the card, and daily matching of the pool against user balances.

"Design an instant payment system run by a central bank" (FedNow- or Pix-like). The operator is also the settlement bank, so per-payment settlement in central-bank money becomes natural and settlement risk between banks disappears; the cost is that each participating bank must keep enough liquidity in its account at all times, around the clock, including weekends. Wikipedia notes FedNow charges institutions $0.043 per transaction and runs 24/7, unlike FedACH, which is closed on weekends and holidays.

Small scale (a country with 50 banks and 1 million payments a day). The same architecture shrinks to a few servers per site: about 12 payments per second on average and perhaps 100 at peak. The hard problems do not shrink: timeouts, reversals, reconciliation and settlement risk are identical. In an interview, saying so is a strong signal.

Deep Dive: how the network evolves from v1 to v3Show

v1: a working switch (first year, up to 1 million payments a day). A single primary database with a standby, a monolithic orchestrator, push payments by VPA and account, end-of-day settlement in one cycle, manual reconciliation of breaks, basic rules for fraud. A few dozen banks. The things that must be right from day one: transaction ids as idempotency keys, debit-then-credit with reversal, signed messages, encrypted PINs, the full message log. These are expensive to retrofit.

v2: national scale (tens of millions to hundreds of millions a day). Partitioned orchestrators and a sharded transaction store; two active data centres with a witness; per-member rate limits and circuit breakers; status checks with enforced limits; several settlement cycles a day with net debit caps; streaming reconciliation; a machine-learning risk engine with a feature store; collect requests, QR, intents and mandates; dispute workflow automation; public per-bank success-rate dashboards to push members to improve.

v3: the network as a platform (hundreds of millions to billions a day). On-device wallets to offload tiny payments; feature-phone and voice channels; credit lines and card-on-the-rail products; cross-border links through hubs; ISO 20022 internally; regulator-driven features (fees on some merchant categories, limits per category) as configuration; continuous chaos testing of bank failures and data-centre loss; market-concentration safeguards. Each step adds front ends and products, while the core (ids, state machine, settlement) stays the same, which is the mark of a sound initial design.

Key Takeaways#

  • The switch routes instructions, banks hold money. The network records outcomes and settles net positions later; it never holds customers' funds.
  • Debit first, credit second, reversal as the compensation. A real-time payment is a saga across independent banks, not a distributed transaction.
  • Unknown is a state, not an error. Timeouts lead to "pending", status checks with enforced limits, and reversals within the regulator's deadline; never tell a payer "failed" when the money may have moved.
  • One transaction id, everywhere. Created by the originator, enforced as a primary key at the switch and as a deduplication key at every bank, it makes retries safe and disputes traceable.
  • Netting turns billions of payments into a few hundred movements, but creates settlement risk that must be controlled with caps, collateral, guarantee funds and enough cycles.
  • Enforce rules at the edge. Per-member rate limits, status-check limits and priority classes are what stop one member's bug from becoming a national outage, as the April 2025 incident showed.
  • Availability is mostly about isolation. Two active sites with a witness, each able to carry the full peak, plus per-bank circuit breakers so a sick bank fails fast and alone.
  • The network sees what no bank can. Network-wide fraud features (payee velocity, mule clusters, device registrations) catch patterns invisible to individual banks; use step-up more than hard declines.
  • Cards and account rails differ in timing and reversibility. Cards authorise now, settle later and allow chargebacks; push payments are final and settle in cycles. Know ISO 8583's message types and stand-in processing.
  • Design the core once, add edges forever. QR codes, feature phones, on-device wallets, cross-border gateways and new message formats should all translate into the same core flow.