"Design a payment system" usually gets one box called the payment service, an arrow to the payment processor, Stripe, and a payments table with a status column. The candidate adds that the API is idempotent. Then the interviewer asks the question the box can't answer: the call to the processor timed out, so was the buyer charged?
Nobody in your system knows. The processor may have charged the card and lost the reply, or never received the request. Waiting longer doesn't separate the two, as Idempotency and Exactly-Once Delivery explains. And it isn't rare. At 10 million payments a day, two calls each, one call in 10,000 left unanswered is 2,000 calls a day whose outcome nobody knows.
The money also moves on its own schedule, outside your system. The buyer's card is authorised at checkout, which holds the money, and captured when the order ships, which takes it. The processor pays the money into the marketplace's bank account days later, a step called settlement, and the marketplace pays the seller after that. At each step somebody else moves the money and sends you a message about it. Any of those messages can be late, repeated, out of order or missing.
Every call that moves money ends one of three ways: it happened, it didn't, or you don't know yet. A payment system is the machinery that turns "don't know" into one of the other two, without ever moving the money twice.
Three pieces do that work. Idempotency keys let you ask the processor the same question again safely. A state machine gives "unknown" a row, an owner and a deadline. And a double-entry ledger, checked line by line against the processor's own reports, catches whatever the first two missed.
Understanding the problem
The general method for this part of the interview is in The First Five Minutes: Requirements.
The system is the payment platform inside a marketplace such as Amazon or Airbnb. Buyers pay for orders. The platform takes the money through a payment processor such as Stripe or Adyen, the company that connects a business to the card networks and banks. It keeps a commission and pays the rest to sellers.
Four kinds of system go by this name, and they're designed differently.
- A processor itself, such as Stripe's own infrastructure, which connects to Visa and Mastercard. We call one. We don't build one.
- One business calling a processor from its checkout, as Ticketmaster does with Stripe. The marketplace's checkout does this to us.
- A wallet, where users keep a balance and send money to each other. Digital Wallet designs that one. A wallet has to refuse a transfer the balance can't cover, at the moment of the write. A marketplace mostly records money that arrives from outside.
- A marketplace's payment platform. It charges buyers through a processor, keeps the ledger, handles refunds and disputes, and pays sellers. This is the one we're designing.
Functional requirements
Core:
- Charge a buyer for an order, through an external processor. Authorise at checkout, and capture when the order ships.
- Keep a ledger that says how much each seller is owed, and where every amount is right now.
- Refund all or part of a payment, and take in chargebacks, where the buyer's bank takes money back after a dispute.
- Pay each seller their earnings, to their bank account, on a schedule.
Out of scope, deliberately:
- Fraud scoring. Another service decides whether to allow a payment before we're called.
- Stored balances and transfers between users, which belong to the wallet.
- Subscriptions, invoices and tax.
- Connecting to the card networks directly.
Non-functional requirements
- Scale. 10 million payments a day, and 1 million active sellers paid nightly. These are assumptions, sized for a large marketplace.
- Latency. Our part of a payment adds under 50 ms at p99, the latency 99 percent of calls beat, on top of the processor's own time. Deep dive 7 trades this for about 100 ms, to survive losing a region.
- Durability. An acknowledged payment, ledger entry or payout survives losing a machine or a zone. Deep dive 7 covers a region.
- Correctness. No order is charged twice, and no charge goes unrecorded, even when a call's outcome is unknown. Every captured amount is matched against the processor's settlement report within days.
Requirement 4 carries the design, so write it in those words. "Payments must be consistent" says nothing about the timeout, which is the case that charges a buyer twice.
The question is which number shapes the design: the
database's write load, or the calls with no answer.
Assumptions: the course's 5x peak, and 1 processor call
in 10,000 that ends with no answer. Rows per payment
are counted from the queries in section 1 and the
ledger in section 2, over the payment's whole life.
Payments
average 10M / 86,400 ≈ 116/s
peak 116 × 5 ≈ 580/s
Processor calls, an authorise and a capture each
peak 580 × 2 ≈ 1,160/s
Rows written per payment
authorise keys 2, payment 3, call 2,
outbox 2 = 9
capture keys 2, payment 2, call 2,
outbox 2, ledger 4 = 12
webhooks 2 stored, 2 marked done = 4
settlement a transaction, 3 entries = 4
balancer 2 transactions folded,
1 balance row = 3
─────────
= 32
peak 580 × 32 ≈ 18,600/s
Commits per payment, with the relay, settlement and
the balancer batching theirs
authorise 3, capture 3, webhooks 4 = 10
peak 580 × 10 ≈ 5,800/s
Calls with no answer
per day 10M × 2 / 10,000 = 2,000
─────────────────────────────────────────────────────────
As rows, the peak is past the course's 5,000 to 15,000
writes a second for one relational primary. As commits,
it's inside, near the bottom. One primary works only
while the batched writes stay batched, so it's the first
thing to load-test. The design problem is still the 2,000
calls a day whose outcome nobody knows.The set up
Core entities
- Payment. One order's charge: its amount, currency, seller and state.
- Processor call. One request to the processor: authorise, capture, refund or cancel, with the idempotency key it was sent with and what came back. This is the interesting one, because it's the row that can say "we don't know".
- Ledger account. A named bucket of money: a seller's earnings, the platform's commission, the money the processor owes us.
- Ledger transaction. A set of entries, each a debit or a credit to one account, that sums to zero.
- Payout. One transfer of a seller's earnings to their bank.
System interface
The callers are other services: the checkout and the order service. They prove who they are as services, as auth, sessions, JWT and OAuth describes.
POST /v1/payments
Idempotency-Key: ord_8812:pay:1
{ "order_id": "ord_8812",
"seller_id": "sel_77",
"amount": 249900,
"currency": "INR",
"commission": 24990,
"payment_method": "pm_1Qx..." }
→ 201 { "payment_id": "pay_901", "status": "AUTHORISED" }
→ 202 { "payment_id": "pay_901", "status": "AWAITING_BUYER",
"next_action": { "redirect_url": "https://..." } }
→ 202 { "payment_id": "pay_901", "status": "PENDING" }
→ 402 { "payment_id": "pay_901", "status": "DECLINED",
"reason": "insufficient_funds" }
→ 409 { "error": "order_has_live_payment", "payment_id": "pay_901" }
POST /v1/payments/pay_901/capture
Idempotency-Key: pay_901:capture
{ "amount": 249900 }
POST /v1/payments/pay_901/refunds
Idempotency-Key: pay_901:refund:1
{ "amount": 50000, "reason": "item_damaged" }
GET /v1/payments/pay_901
GET /v1/sellers/sel_77/balance
Events, to a topic the order service reads:
payment.authorised payment.failed payment.captured
refund.succeeded dispute.opened payout.paid
Four things to note.
Amounts are integers in the currency's smallest unit. 249900 is ₹2,499.00 in paise. Deep dive 5 shows why a floating point number can't hold money.
The key names a business step, not an HTTP call. pay_901:capture can only ever mean one capture of one payment, so a retry from any server, after any restart, carries the same key. Airbnb's payments team calls this entity-level idempotency, and gives payment-1234-refund as its example. The :1 on the charge is an attempt number. A buyer who switches cards makes a second attempt, with a new key, and gets 409 while the first attempt is still live.
202 is a normal answer. AWAITING_BUYER means the buyer's bank wants the buyer to approve the payment, and the checkout shows the bank's page. PENDING means the processor didn't answer in time, and the outcome isn't known yet. The checkout shows "confirming your payment", and the order service waits for payment.authorised or payment.failed. So the API never tells a caller "failed" when the truth is "don't know".
payment_method is a saved payment method from the processor, never a card number. It's saved for reuse with the buyer's consent, because section 1 sometimes has to authorise again without the buyer present. Deep dive 6 explains why tokens keep most of the system out of the card industry's audit.
High-level design
1. Charge a buyer: where does the call to the processor go?
A charge touches two systems, your database and the processor, and no transaction covers both. Every design in this section is a choice about the order of the writes, and what each crash in between leaves behind.
Authorise at checkout, capture at dispatch
An authorisation asks the buyer's bank to hold the amount on the card without moving it. A capture takes the held money. The marketplace authorises at checkout and captures when the order ships. Distributed Transactions and Sagas gives the reason: before capture, Stripe lets you cancel a payment at no cost, and after it you can only refund. An order that can't ship then costs nothing to undo.
Many card payments need the buyer to approve them in their bank's app, or on a page the bank shows, a check called 3-D Secure. The payment then waits on the buyer, and finishes when the buyer comes back or the processor's webhook arrives, as Ticketmaster describes.
The hold has a deadline. Stripe's documentation says an online card authorisation usually lasts 7 days, and when it expires the money is released and the payment is cancelled. So an order that hasn't shipped by day 6 needs a fresh authorisation. The service cancels pay_901 first, which frees the order's one live payment, then authorises pay_902 with the saved payment method, and the capture key becomes pay_902:capture. The buyer isn't there for that one, which is why the checkout saves the payment method rather than sending a one-use token. An authorisation without the buyer present is merchant-initiated, and Stripe's documentation says a Visa one of that kind lasts 5 days, not 7, so pay_902's hold on a Visa card runs out sooner.
Recording the call
The checkout's request has to leave your database and the processor agreeing: a row for every charge, and no charge without a row. So in what order do the writes go, and what does a crash between them leave behind?
Call the processor inside the database transaction
Open a transaction, insert the payment, call the processor, write the result and commit. If the call throws, roll back. It reads as one unit, which is why it's tempting.
It fails in two ways. The first is a crash after the processor took the money and before the commit. The rollback deletes the only record that the call was ever made. The buyer's money is held, and your database says no payment exists.
The second is the connections. Assume a processor call takes about a second. Each call holds a database connection and the payment row's lock for that whole second, so at 580 payments a second, about 580 connections sit idle waiting on the internet. Airbnb's payments team warns that network calls inside these database steps can cause "rapid connection pool exhaustion".
Record, call, record
Split the request into three steps. First, one transaction writes the payment and a processor_calls row with the idempotency key it's about to send, in state SENT. Then the call goes out, with no transaction open. Then a second transaction records the answer and moves the payment on.
Airbnb's idempotency library, Orpheus, splits each request this way, with no network calls in the database steps and no database work during the call. Airbnb reports five nines of consistency for its payments with it.
A crash now leaves a SENT row behind, which is a record that a call may have happened. A retry finds it and sends the same key, and the processor returns its first answer.
The cost is that row. If the client gives up and nobody retries, it stays SENT forever, with a charge at the processor that may or may not exist. Something has to own it.
A state machine that resolves its own unknowns
Question the premise that the request which starts a payment has to finish it. The request thread can die, the checkout can give up, and the buyer can close the tab. So make the payment a state machine stored in its row, where every state that isn't final has a deadline, resolve_by.
A resolver, a small background worker, scans for calls whose resolve_by has passed. For each, it asks the processor again, in ways deep dive 1 lists, and drives the payment to a final state. Brandur Leach's design for Stripe-style keys in Postgres suggests the same worker, called a completer, to push abandoned requests through to the end.
The timings keep the request thread and the resolver apart. The call to the processor times out after 10 seconds. The API then marks the call UNKNOWN and returns 202 PENDING, and the order service hears the result later as an event. resolve_by is 30 seconds after the call, so the request thread has given up before any resolver looks.
Each state has one meaning. CREATED has no call yet. AUTHORISING and CAPTURING have a call recorded and out. AWAITING_BUYER waits on the buyer's bank check, and the resolver cancels it if the buyer hasn't finished within a few minutes. AUTHORISED holds the money, and CAPTURED has taken it. DECLINED means the processor or the buyer said no, and CANCELLED means the hold was released, refused or lapsed.
Sized: about 2,000 calls a day go unanswered, so the resolver is one small worker. Without it, each of those is a buyer who may have paid for an order that never arrives.
What you give up. Callers must handle a third answer, and the checkout needs a "confirming" screen. Two resolver copies must never drive one payment at the same time, so each claims a row with a lease that runs out on its own, 60 seconds here. Airbnb gives each request an expiring lease on its key in the same way, and advises setting it longer than the call's timeout.
Which data store, and what actually forces it
The rate allows one primary, narrowly. The worksheet above gives about 5,800 commits a second at peak, inside what one relational primary takes, but about 18,600 rows. Four writes have to commit together, and that forces the choice. They're the payment's new state, its processor call's result, the ledger transaction for the money, and the event for the order service. The event is a row in an outbox table, which a relay publishes afterwards. If any one of the four lands without the others, a later reader sees money that moved with no record of why, or a record with no money.
So one Postgres database holds all of it, with a synchronous standby in a second zone. A commit returns only after the standby has the write in its write-ahead log, so losing the primary's zone loses no acknowledged payment. Choosing a Database puts payments and ledgers in a relational database for the same reason: several rows must change together and be right.
If the load outgrows one primary, the first thing to move is the stored webhook events. Storing one needs nothing atomic with a payment, so they can live in a database of their own.
The tables
payments (
payment_id text primary key,
order_id text not null,
seller_id text not null,
amount bigint not null, -- minor units
currency char(3) not null,
status text not null, -- CREATED, AUTHORISING, AWAITING_BUYER, ...
updated_at timestamptz not null
)
CREATE UNIQUE INDEX one_live_payment ON payments (order_id)
WHERE status NOT IN ('DECLINED', 'CANCELLED');
processor_calls (
call_id bigserial primary key,
payment_id text not null,
kind text not null, -- AUTHORISE, CAPTURE, REFUND, CANCEL
idempotency_key text not null unique,
processor_ref text, -- the processor's id for the object
state text not null, -- SENT, SUCCEEDED, FAILED, UNKNOWN, LOOKUP_ONLY
resolve_by timestamptz not null,
claimed_until timestamptz, -- the resolver's lease
claim bigint not null default 0
)
api_keys (
caller_id text,
idempotency_key text,
request_hash bytea not null,
response jsonb, -- replayed to a retry
primary key (caller_id, idempotency_key)
)
outbox (
event_id bigserial primary key,
payment_id text not null,
type text not null, -- payment.authorised, ...
body jsonb not null,
sent_at timestamptz
)
Five things to note.
An order has at most one live payment. The partial unique index covers every status except DECLINED and CANCELLED. A second attempt fails that insert, and the API returns 409, until the first attempt is declined or cancelled. Without it, a buyer who switches cards while the first attempt is PENDING gets two holds.
processor_calls.idempotency_key is written before the call is sent. It's pay_901:authorise:1, built from the call row, not from the caller's key, because one caller request can lead to several processor calls. The unique index means a second copy of the same call can't be recorded.
processor_ref is filled before the money moves. Stripe's documentation says to create the PaymentIntent, the object that tracks one payment, as soon as you know the amount. Creating one doesn't charge anything. So the service creates it, stores its id, and only then confirms it, which is the call that charges. If the confirm times out, the resolver already knows what to look up.
A call's state says what may happen next. SENT is recorded and out. SUCCEEDED and FAILED are the processor's answer. UNKNOWN ended with no answer, a timeout or a 5xx, and the resolver may send it again with the same key. LOOKUP_ONLY is a call whose key is close to expiring at the processor, so the resolver only looks the object up and never sends it again. A requires_action reply, the buyer's bank check, leaves the call SENT, with resolve_by moved a few minutes out.
api_keys is separate from processor_calls. One protects our API from a caller's retry. The other protects the buyer's card from our retry. Both are read on the primary, never a replica. Airbnb does the same with its keys, because a replica a few seconds behind can miss a stored response, and the retry then charges again.
The queries that carry the product
-- 1. Before the call that moves money: record it, in one commit.
-- pi_3Q... is the processor's payment object, already created,
-- which holds no money until it is confirmed.
UPDATE payments SET status = 'AUTHORISING', updated_at = now()
WHERE payment_id = 'pay_901' AND status = 'CREATED';
INSERT INTO processor_calls
(payment_id, kind, idempotency_key, processor_ref, state, resolve_by)
VALUES ('pay_901', 'AUTHORISE', 'pay_901:authorise:1', 'pi_3Q...',
'SENT', now() + interval '30 seconds');
-- 2. After the answer: move forward only, with the event, in one commit.
-- If the call's UPDATE changes 0 rows, roll back: another path has
-- already recorded the answer, or a newer claim owns the call.
-- If it lands but the payment's doesn't, and the payment isn't
-- already where the answer leads, keep the call's answer, skip the
-- event and raise a break for a person: it moved for another reason.
UPDATE processor_calls SET state = 'SUCCEEDED'
WHERE idempotency_key = 'pay_901:authorise:1'
AND state IN ('SENT', 'UNKNOWN', 'LOOKUP_ONLY'); -- the resolver adds AND claim = :mine
UPDATE payments SET status = 'AUTHORISED', updated_at = now()
WHERE payment_id = 'pay_901' AND status IN ('AUTHORISING', 'AWAITING_BUYER');
INSERT INTO outbox (payment_id, type, body)
VALUES ('pay_901', 'payment.authorised', '{...}');
-- 3. The resolver: claim calls past their deadline
UPDATE processor_calls
SET claimed_until = now() + interval '60 seconds', claim = claim + 1
WHERE call_id IN (
SELECT call_id FROM processor_calls
WHERE state IN ('SENT', 'UNKNOWN', 'LOOKUP_ONLY') AND resolve_by < now()
AND (claimed_until IS NULL OR claimed_until < now())
ORDER BY resolve_by LIMIT 100 FOR UPDATE SKIP LOCKED)
RETURNING call_id, idempotency_key, processor_ref, state, claim;
Of these, query 2 runs most often, at least twice per payment. Its WHERE clauses make it move forward only. Three paths can deliver the same answer: the request thread, the resolver and the webhook worker. The first to commit wins, and the others' call updates change 0 rows and roll back, so the outbox row is written once.
The interviewer will push on query 3, usually by asking what the resolver does when the processor still doesn't answer. Deep dive 1 answers that. The claim it takes fences our rows, not the call: the processor never sees the claim, and two resolvers that both send the call are safe only because both send the same key.
The events are facts in the past tense, such as "payment authorised", and the order service, notifications and finance all read them. That makes them history rather than work, by the test in Message Queues vs Event Streams, so they go to a log such as Kafka, keyed by payment.
2. Keep a ledger: who is owed what, and where is it?
Every capture, refund, dispute and payout changes how much each seller is owed. The finance team also needs to know where each rupee is: at the buyer's bank, owed by the processor, in the marketplace's bank account, or on its way to a seller. So how do you record money?
A balance column on the seller, updated on each event
UPDATE sellers SET balance = balance + 224910. It's one statement, and reading a balance is one row.
It breaks three ways. A retried event adds the money twice, and nothing in the row shows it. A balance that's wrong can't be explained, because the row keeps only the latest number. And money that has left one place and not arrived at the next isn't anywhere, so nobody can ask where it is.
Double-entry: append-only entries that sum to zero
Record each movement as a transaction of two or more entries, each a debit or a credit to one account, and require the entries to sum to zero. Money can't appear or vanish, only move between accounts. Entries are never updated or deleted. A mistake is fixed by a new transaction that reverses it. A balance is the sum of an account's entries, and it's kept on the account as a cache you can rebuild.
This is the staff answer on Idempotency and Exactly-Once Delivery, and Uber's and Stripe's ledgers both start from it. Uber's platform writes every money movement as an immutable order whose entries are checked to sum to zero before the write, and records an adjustment as a new order.
Each transaction carries the event that caused it in a unique source column, such as capture:pay_901. A replayed event fails that insert, so it can't post twice.
The cost is the balance cache. Every posting updates the account's balance row, so writes to one account wait in line, which deep dive 4 deals with. And this ledger still knows only about money inside the marketplace.
Give the outside world accounts too
Question the premise that the ledger records only what the marketplace owns or owes. Most of the time the money is somewhere else: captured but not yet paid by the processor, or sent to a seller's bank and not yet confirmed. Give each of those places an account. processor:receivable is what the processor owes us. bank:incoming is what the processor says it has paid us and our bank statement doesn't show yet. payouts:in_transit is what we've sent to sellers and not seen arrive.
These are clearing accounts. Money enters one when the first half of a movement happens, and leaves when the second half does, so each should return to zero for every payment within a known window. Stripe's Ledger uses the same idea, and says a correct flow leaves its clearing accounts empty: "If there is water stuck in the pipes, then you have a problem."
Sized: settlement adds 3 entries per payment, so half of a payment's 6 ledger entries exist only to record the processor paying us. In return, "is anything missing?" becomes a query: clearing balances that are older than their window and not zero. Deep dive 3 builds reconciliation on that.
What you give up. The settlement report has to be loaded into the ledger line by line, not just compared with it, and every line needs a reference that matches one of your payments.
The ledger tables
ledger_accounts (
account_id text primary key, -- seller:sel_77:pending, processor:receivable, ...
currency char(3) not null
)
ledger_transactions (
txn_id bigserial primary key,
source text not null unique, -- capture:pay_901, settlement:batch_412:line_9
posted_at timestamptz not null,
folded boolean not null default false -- set by the balancer; deep dive 4
)
CREATE INDEX unfolded ON ledger_transactions (txn_id) WHERE NOT folded;
ledger_entries (
entry_id bigserial,
txn_id bigint not null,
account_id text not null,
amount bigint not null, -- debit positive, credit negative, minor units
ref text, -- the payment or payout it belongs to
posted_at timestamptz not null
) partition by range (posted_at);
ledger_balances (
account_id text primary key,
balance bigint not null, -- the sum of every folded transaction's entries
updated_at timestamptz not null
)
The capture of pay_901 posts one transaction. The platform keeps a 10 percent commission.
source = capture:pay_901
processor:receivable +249,900 the processor owes us the price
seller:sel_77:pending −224,910 the seller is owed the rest
platform:commission −24,990 our commission
────────
0
When the processor's settlement report includes pay_901, with an assumed 2 percent fee, a second transaction clears the receivable: bank:incoming +244,902, platform:processor_fees +4,998, processor:receivable −249,900. Those are the 6 entries per payment. When the bank statement shows the batch's deposit, one transaction for the whole batch moves it from bank:incoming to bank:operating.
Three things to note.
The key is source, not the entry. One event is one transaction. A capture event delivered twice, or a settlement file loaded twice, fails on source and posts nothing.
ref is what clearing groups by. Summing processor:receivable by ref gives one total per payment, and any total that isn't zero after the settlement window is a break.
Entries never change, so the table only grows. The folded flag lives on the transaction's header row, not on its entries.
The question is what forces the ledger to split, if not the write rate. Each entry row, with its indexes, is assumed to take about 250 B. entries per day 10M × 6 = 60M bytes per day 60M × 250 B = 15 GB bytes per year 15 GB × 365 ≈ 5.5 TB ───────────────────────────────────────────────────────── The rate fits one primary for years. The size doesn't. Split by time, not by account: a transaction touches several accounts, and splitting by account would put one commit across machines.
So ledger_entries is partitioned by month. Recent months stay on the primary, and a monthly job moves older ones to a separate read-only Postgres that reconciliation and audits query. That's the storage ceiling in Partitioning and Sharding, reached long before the throughput one. Finance's warehouse gets the entries by change data capture, reading the database's log, so its reports never run on the primary.
3. Refunds and chargebacks: money going back
A refund is a request from us. A chargeback is a demand from the buyer's bank. They look alike in the ledger and behave differently everywhere else.
A refund is one more processor call, of kind REFUND, recorded and resolved like the others. Its key comes from the caller, pay_901:refund:1. The transaction that records the call locks the payment's row first, then checks that refunds so far plus this one don't exceed the captured amount. Two partial refunds sent at once can't refund more than was paid, because the second one waits for the lock, and its check then sees the first.
Before capture, the right call is CANCEL, which releases the hold for nothing. After capture it's a refund, and a refund can fail days after it was accepted, for example on a closed bank account. Stripe says that return can take up to 30 days and arrives as a refund.failed event. So SUCCEEDED isn't final for a refund, and its ledger transaction gets reversed by a new one when the failure arrives.
The refund's ledger transaction is the capture's in reverse: processor:receivable −50,000, and the seller and the commission accounts get the matching debits.
A chargeback arrives as an event from the processor, not as a call from us. A buyer tells their bank they didn't get what they paid for, and the bank takes the money back. Stripe's documentation says the disputed amount and a dispute fee are taken from your balance as soon as the dispute opens. Cardholders typically have up to 120 days from the payment to open one, and the bank's decision takes months after that.
In the ledger, the dispute moves the amount out of the seller's account into disputes:open, and the fee into the platform's costs. If the bank decides for the seller, a new transaction moves it back.
The hold before a payout, in section 4, covers most refunds. It can't cover a dispute that arrives up to 120 days later, so a seller's balance can go below zero, and the marketplace recovers it from the seller's next sales.
4. Pay sellers
A payout moves a seller's earnings from the marketplace's bank to theirs. It's the same problem as a charge, with the direction reversed: a call to a bank or a payout provider that can end in yes, no or unknown.
The hold from section 3 is an account, not a flag. A capture credits seller:sel_77:pending. Each night, a release job takes what each seller's pending account received on the day the hold window ended, say 7 days ago, and moves it to seller:sel_77:available. That's one transaction per seller per day, with a source such as release:sel_77:2026-11-01, so a day can't be released twice. A payout takes only what's available.
One seller's payout, end to end:
- The payout job reads the seller's available balance: the folded balance in
ledger_balances, plus the account's entries in transactions not yet folded. It reads both in one statement, or one REPEATABLE READ transaction, so a fold that commits between two reads can't count an entry twice or not at all. - In one commit, it posts a transaction moving that amount to
payouts:in_transit, inserts apayoutsrow with the keypayout:sel_77:2026-11-08, and writes an outbox row. The key includes the date, so tonight's payout for this seller can exist once. - The outbox relay sends the transfer to the payout provider with that key.
- When the provider reports the transfer paid, a transaction clears
payouts:in_transitagainstbank:operating.
Step 4 isn't the end. Stripe's payout documentation says a failed payout is marked failed within 5 business days, and that some payouts that fail show as paid first. So a payout reported failed after it was paid gets a reversing transaction, back to the seller's available account, and the seller's bank details are flagged for them to fix. The original entries stay as they were.
At 1 million sellers, that's up to 1 million payouts a night. Sent over a 4-hour window, that's about 70 a second, which is easy.
Deep dives
Deep dives 1 and 3 come up in nearly every version of this interview, and 2 and 4 in most.
1. The unknown outcome: charging exactly once
Exactly-once charging is two things working together. Idempotency keys make it safe to send the same call twice. And something has to find out what happened when no answer comes back, without guessing.
Three ways to find out
When a call to the processor ends without an answer, the resolver has three ways to learn what happened.
Send it again with the same key. If the first request reached the processor, the processor returns the response it saved, so the retry can't charge twice. Stripe keeps a key for at least 24 hours, so this works inside that window. One exception: Stripe also saves a 500 against the key, and returns that 500 to every retry. A retry turns a lost reply into an answer, but not a 500.
Look up the object. Stripe's guidance for a 500 is to treat the outcome as indeterminate and to retrieve the object. That's why processor_ref is filled before the call that charges. The resolver fetches the PaymentIntent and reads its status.
Wait for the webhook. The processor tells you anyway, which deep dive 2 covers.
When the window runs out
The key protects you for 24 hours. After that, Stripe says to stop retrying with either the old key or a new one, and to establish the outcome from the object and the events instead. So the resolver resends with the same key at growing intervals for the first hours, and looks the object up whenever it has a processor_ref. After about 20 hours it moves the call to LOOKUP_ONLY, and from then on it only looks, which is always safe.
If the processor never answers a lookup, the kind of call decides what happens next. An authorisation that was never captured releases on its own: the hold lapses within 7 days, Stripe marks the payment canceled, and the first lookup that gets through reads that. A capture or a refund moved money, so the processor's settlement report will list it, and reconciliation settles the call from that line. A person reviews anything neither settles.
When the processor is down
Requests to a processor that's failing should stop quickly, behind a circuit breaker, as circuit breakers, bulkheads and backpressure describes, and a marketplace with a second processor can send new authorisations there. That never applies to a call whose outcome is unknown, because only the processor that received it can say whether it charged. And a capture or a refund has to go to the processor that holds the authorisation.
2. Webhooks, and events that arrive out of order
The processor tells you about things you didn't ask for, and about things you asked for that finished later. A buyer finishes their bank's check. A refund fails. A dispute opens. A payout is returned. It sends these as webhooks, HTTP calls to an endpoint you register.
Stripe's documentation gives the delivery rules. It retries an event it couldn't deliver for up to three days, with growing gaps. It may deliver the same event more than once. And it doesn't promise any order. Each event is signed with a keyed hash over its body and a timestamp, so the endpoint can check who sent it and refuse an old one replayed. The endpoint should return 2xx at once and do the work afterwards, from a queue.
So how do you apply events that can repeat and arrive in any order?
Apply each event's payload as it arrives
Verify the signature, read the new status from the event body, write it to the payment, and return 200. It's short, and it works in testing, where events arrive one at a time.
It breaks on order. Say charge.refunded arrives, and then a delayed payment_intent.succeeded from earlier. The second write sets the record back to succeeded, and the refund is gone from it. A duplicate event posts its ledger transaction twice, unless source stops it. And a handler that does the work before answering is slow when traffic spikes, so the processor times out, retries, and the spike gets bigger.
Store the event, then apply it forward only
Verify the signature, then insert the event with its id as the primary key, and return 200. A duplicate fails the insert and is dropped. A worker applies stored events through the state machine, with the forward-only updates from query 2, so an event that would move a payment backwards changes nothing. The stored events are a queue of work, not history, in the sense Message Queues vs Event Streams uses.
The cost is everything a status doesn't capture. Two partial refunds, ₹200 and then ₹300, each send a charge.refunded event whose body is the charge with its running amount_refunded: ₹200, then ₹500. Neither event changes the payment's status, so the forward-only rule can't order them. If the ₹500 event arrives first, a handler that copies amount_refunded sets it back to ₹200 when the late one lands. Ordering by the event's timestamp doesn't help, because Stripe records it in whole seconds and says not to use it for order.
Treat each event as a prompt to look
Question the premise that the event body is the truth. Use the event only as a sign that an object changed, here the charge, ch_3Q.... The worker fetches the object's current state from the processor and applies that. Stripe's documentation points this way: its newer "thin" events carry a reference to the object rather than a copy, and its example handlers fetch the latest version.
Now order doesn't matter. Both refund events lead to the same fetch of the charge, which returns ₹500 refunded, and applying the same state twice changes nothing.
What you give up: one extra read per event against the processor's rate limit. The processor sends several events per payment, so subscribe only to the event types the system uses.
Webhooks aren't the only signal either. Stripe stops pushing an event after its three days of retries, but its API still lists undelivered events from the last 30 days, so an endpoint that was down can ask for what it missed. Past that, only the resolver's lookups and reconciliation recover them.
3. Reconciliation: checking the ledger against the processor
The processor sends a settlement report for each payout it makes to you. Adyen's settlement details report is a good example of the shape. It lists each settled payment, refund and chargeback with the processor's reference and the merchant reference you sent, plus lines for fees and one line for the batch's payout to your bank. You can have one generated for each batch or each day.
Reconciliation loads it into the ledger. It doesn't just compare against it.
- Match. Each payment or refund line is matched to a
processor_callsrow by the processor's reference, or by the merchant reference, which is the payment id we sent. Each chargeback line is matched to its dispute event, and each fee line posts toplatform:processor_fees. - Post. Each matched line becomes a ledger transaction with
source = settlement:<batch>:<line>, and it clearsprocessor:receivablefor that payment. Loading the file twice posts nothing new. - Check the bank. The report's payout line has to match a deposit on the marketplace's bank statement, and one transaction per batch then moves the amount from
bank:incomingtobank:operating. - Report what didn't clear. Every clearing balance that isn't zero by its deadline is a break, with an age and an owner.
The breaks fall into a few kinds, and each points at a different fault. A payment or refund line with no call of ours means something outside this system moved money on our account, such as a refund made by hand in the processor's dashboard. A line that matches a call we hold as UNKNOWN or LOOKUP_ONLY settles it, because the money moved. A call of ours that succeeded, with no line after the window, is money the processor hasn't paid. A line whose amount differs is a partial capture, a fee we didn't expect, or a currency conversion. Most can be fixed by a rule, and the rest go to a person.
The resolver turns most unknowns into answers within minutes. Reconciliation is the last way an unknown capture or refund becomes known, and the only way to find a call you thought you knew and got wrong.
It takes days, even at the largest scale. Stripe's Ledger takes in 5 billion events a day, and reports that 99.99 percent of dollar volume is fully ingested and verified within four days. So the requirement says "within days", and the alerts measure how old each break is, not how many there are.
4. How many servers, and the hot accounts
The payment service holds no state, so it scales with calls in flight. At peak, 1,160 calls a second that each take about a second means about 1,160 calls open at once, a few instances for a service that doesn't hold a thread per call. The processor's rate limit, agreed with the processor, caps the useful size first.
The trouble on the database is that some writes all land on the same rows. Every capture posts to processor:receivable and platform:commission, so each of those two accounts takes a posting from every payment.
The question is whether updating a balance row on every posting can keep up, and how many rows a split needs. The lock on the row is held until the commit returns. Postgres sends a standby only log it has already flushed, so the two flushes run one after the other. The course's figures: a 0.3 ms flush, a 1.5 ms round trip between zones, and 25 ms to the nearest region. Standby in another zone lock held 0.3 + 1.5 + 0.3 ms ≈ 2.1 ms postings/s 1 / 2.1 ms ≈ 480 Standby in another region, deep dive 7 lock held 0.3 + 25 + 0.3 ms ≈ 25.6 ms postings/s 1 / 25.6 ms ≈ 39 Needed on each hot account at peak = 580 Rows a split needs, the smallest k with k × rate ≥ 580 in one region 580 / 480 ≈ 1.2, so k = 2 → 960/s across regions 580 / 39 ≈ 14.9, so k = 15 → 585/s ───────────────────────────────────────────────────────── One locked row can't take 580 postings a second in either setup. A split can, but its size depends on where the standby is: 2 rows per hot account in one region, 15 across regions. These lock times are floors, so the k needed is higher.
Lock the account's balance row on every posting
Each posting updates ledger_balances for every account it touches, in the same commit. Balances are always exact, which is why it's tempting. The worksheet rules it out in either setup.
Split each hot account into sub-accounts
Give processor:receivable and platform:commission k balance rows each, and send each posting to one at random. The balance is the sum of the rows. This is the split-key move from contention and hot keys, with k the smallest number that covers the load: 2 within one region.
The cost is that k depends on how long a commit takes. Adopt deep dive 7 and each commit waits for another region, so each hot account needs 15 rows, and more, since the worksheet's lock times are floors. And a seller whose sale goes viral needs a k of its own before anyone has noticed it.
Don't update balances when you post
Question the premise that a posting has to update a balance. A wallet refuses a transfer the balance can't cover, so it has to read the balance as it writes. This ledger never refuses a posting because of a balance. A capture is posted because the processor took the money. So a posting only inserts its entries, which share no row with other postings, and no lock is taken. A commit across regions still waits 25 ms, but no posting waits for another, so the commit time stops setting a limit.
A balancer, one worker, folds new transactions into ledger_balances about once a second. It claims a batch of unfolded transactions with FOR UPDATE SKIP LOCKED, adds their entries up per account, updates each account's balance once, and marks the transactions folded, all in one commit. A transaction still open when it runs isn't visible to it, and is folded on a later pass, so none is skipped. Uber reports a 10x gain in throughput for its high-traffic entities from writing to them in serialized batches.
Modern Treasury hit the same problem: its bank settlement account appears on most transactions, and contention for its one balance row made write latency spike. It now locks an account only for entries that need an immediate answer, and queues the rest to be folded in, at a p90 of 1 second.
What you give up. A balance is about a second behind its entries. The payout job reads the folded balance plus the account's unfolded entries in one snapshot, so it never pays from entries it didn't count. Anything that has to refuse based on a balance, such as a wallet's transfer, needs the locked path back, and that's Digital Wallet's design, not this one.
5. Money in minor units, and more than one currency
Every amount in this system is an integer count of the currency's smallest unit, with a three-letter currency code beside it. Stripe and Adyen both take amounts this way.
The question is what type holds an amount. The ledger's
one rule is that every transaction sums to exactly zero,
so test that rule on the capture from section 2.
As floating point numbers, in rupees, in posting order
2,499.00 − 2,249.10 − 249.90 = 0.0000000000000853
the same three in another order = 0
As integers, in paise
249,900 − 224,910 − 24,990 = 0
0.10 added ten million times, as floating point
= 999,999.99983898
─────────────────────────────────────────────────────────
The float passes or fails the zero-sum check depending
on the order of the sum, and drifts as amounts are added
up. Amounts are integers.The smallest unit isn't always a hundredth. Adyen's currency table gives the yen and the won no decimal places, and the Bahraini and Kuwaiti dinars three. Processors don't always agree with ISO 4217, the international standard for currency codes and their decimals, either: Adyen's table marks four currencies where its decimals differ from the standard. So each processor adapter keeps its own table and converts at the edge, and inside the system an amount is in ISO minor units.
Splitting money leaves remainders. Three sellers sharing ₹100.00 get ₹33.33 each, and one paisa is left. The split rule names the account that gets the remainder, so the transaction still sums to zero.
A ledger transaction never mixes currencies. A conversion is two transactions, one per currency, through an exchange account in each, so each currency sums to zero on its own.
6. Card data, and keeping it out of scope
The Payment Card Industry Data Security Standard (PCI DSS) applies to anyone who stores, processes or transmits card data. Stripe's integration guide says a business that handles raw card numbers may have to meet more than 300 security controls in PCI DSS.
So the card number never reaches the payment platform. The checkout page loads the processor's own payment fields, the buyer's card goes straight from the browser to the processor, and the page gets back a saved payment method, pm_1Qx.... Every service here stores and sends that token. Stripe's guide calls these low-risk integrations, because card data doesn't pass through your servers.
A marketplace that routes payments between two processors needs a vault, its own or a third party's, so that both can charge one card. The vault is the only part in full scope, and everything else still sees tokens.
7. Losing a region
The design so far runs in one home region, with a synchronous standby in a second zone. A whole region failing is the case Multi-Region and Disaster Recovery works through for a checkout. It concludes that payments need a recovery point of zero, meaning no acknowledged write is lost, while data that can be rebuilt can lose seconds.
So a payment's commit has to reach another region before it returns. That page moves payments to a database that commits by quorum across regions, such as Spanner or CockroachDB. Postgres can do the same with a quorum of synchronous standbys: any 2 of one in a second zone and one in each of two other regions. At least one copy then always lands outside the home region, and losing any one standby doesn't stop commits. Requiring one named standby in another region instead would stop every payment whenever that link failed.
Either way, each commit waits about 25 ms for the nearest other region, and every region holds a full copy of the payments and the ledger.
That breaks the 50 ms budget, and this design accepts it. The authorise path commits three times: once for the key and the payment, once before the call and once after. So it waits about 77 ms on commits alone, and the budget becomes about 100 ms at p99. The call already waits about a second on the processor, so the buyer won't notice, but the requirement has to say it.
The ledger can afford it only because of deep dive 4. With a locked balance row, each hot account would need 15 rows.
The failover itself creates unknowns. Calls in flight when the region died have keys in the database and no recorded answer. So before the new region takes payments, its resolver runs over every call still SENT, UNKNOWN or LOOKUP_ONLY, with the same keys, against the same processor. The processor sits outside both regions, and its records didn't fail over. In this design the resolver and reconciliation already do that every day, and a failover is a busy day for them.
8. How do you know it is working?
During an incident you need four answers fast: are payments succeeding, are unknowns piling up, is money clearing, and does the ledger still balance.
- Authorisation success rate, per processor. A drop at one processor alone is that processor, not your buyers.
- Calls not final, and the age of the oldest. A rising age means the resolver is stuck.
- Clearing balances past their window, by account and by age. This is reconciliation's output.
- The sum of all entries, per currency. It must be zero, checked every hour, and anything else is a page.
Label metrics by processor, currency and kind of call, never by payment. One payment's history belongs in the logs, as Observability sets out.
Final design
One payment, end to end:
- The checkout collects the card in the processor's own payment fields and gets a saved payment method. It calls
POST /v1/paymentswith the keyord_8812:pay:1, which the API stores with its response inapi_keys. The order can have only one live payment. - The payment service creates the processor's payment object and stores its id. In one commit it writes the payment as
AUTHORISINGand aprocessor_callsrow with the keypay_901:authorise:1, then sends the authorisation. - The processor answers, and one commit records the answer, moves the payment forward and writes an outbox row. If the buyer's bank asks for approval, the payment waits in
AWAITING_BUYER. With no answer in 10 seconds, the API returns202 PENDING, and the resolver asks again with the same key onceresolve_bypasses. - The order ships, and the order service calls capture with
pay_901:capture. The same record, call, record runs, and the commit that records success also posts the ledger transaction: the receivable, the seller's pending account and the commission. - Webhooks arrive, are checked for their signature, and are stored by event id. A worker fetches each object's current state from the processor and applies it forward only.
- Each day, reconciliation loads the settlement report and the bank statement. It posts each matched line, which clears
processor:receivablefor that payment, matches each batch's payout to the bank, and reports every clearing balance still open past its window. - The balancer folds newly committed ledger transactions into
ledger_balancesabout once a second. Each night the release job moves earnings past the hold window from pending to available. - The payout job posts each seller's available balance to
payouts:in_transit, with a payouts row and an outbox row in one commit. The relay sends it with its key, and the provider's answer clears or reverses it. Every service reports to telemetry, labelled by processor and currency, never by payment.
The numbers behind the shape: about 5,800 commits and 18,600 rows a second at peak keep one Postgres primary, but only while the batched writes stay batched. 5.5 TB a year of ledger entries is what splits it, by month. About 2,000 calls a day end with no answer, and each one is resolved with the key it was sent with, or lapses on its own. A locked balance row takes at most 480 postings a second, and 39 once commits cross regions, against 580 on each hot account, so postings don't update balances.
What is expected at each level
How interviewers turn what they see into these levels is in How a System Design Interview Is Scored.
Mid-level
Breadth matters more than depth at this level, and it's fine to be led.
You should call an external processor, explain authorise and capture, and send an idempotency key with each call. You should store payments in a relational database such as Postgres, and say why a payment can't be lost.
You aren't expected to raise clearing accounts, hot accounts or currency exponents without being asked. You are expected to answer sensibly when asked "the processor call timed out, what do you do?" A good answer retries with the same key, and doesn't mark the payment failed.
Senior
You drive the structure, and three things should come up without prompting.
The order of writes around the processor call. Record the key, call, record the answer, and say what a crash at each point leaves behind.
A ledger in double-entry. Append-only entries that sum to zero, a unique source per transaction, and balances computed from entries.
Reconciliation against the settlement report. What you match on, and what happens to a line that doesn't match.
Two things are disqualifying: marking a payment failed because its call timed out, and a balance column updated in place as the only record of money.
Staff+
A correct design is still the bar. A staff+ answer also decides what not to build.
Make "unknown" a state with a deadline and an owner, and return it to callers as 202 PENDING, so no layer turns it into a guess.
Put the processor and the banks in the ledger as clearing accounts, so a missing step is a balance that didn't return to zero.
Price the hot account. 480 postings a second on one locked row against 580 needed, 39 across regions, and take the balance update off the posting because nothing here refuses a posting on its balance.
Use the same machinery for a lost region. The resolver and reconciliation already settle unknowns every day, so a failover adds a run, not a new system.
Be able to say what you would not build. No distributed transaction with the processor, because none exists. No ledger sharded by account while one primary takes the commits. No balance checks at write time in a ledger that never refuses a posting. No card vault unless you route across processors. No real-time reconciliation when the processor's report arrives once a day. A team could spend a quarter on any one of these.
Sources
The figures about named companies and processors come from these, all read for this page. The marketplace's sizes, rates and timings are assumptions, worked through where they're used.
- Jon Chew and Ninad Khisti, Avoiding Double Payments in a Distributed Payments System, Airbnb, 2019. The three steps around a call, entity-level keys, leases longer than the call's timeout, keys on the primary database, and five nines of consistency.
- Brandur Leach, Implementing Stripe-like Idempotency Keys in Postgres, 2017. Recording state between calls to other systems, a lock on each key that expires, and the suggestion of a completer that finishes abandoned requests.
- Stripe documentation on calls. Idempotent requests and low-level error handling give the 24 hour keys, the saved
500s and the rule against a new key. Also the PaymentIntent lifecycle, placing a hold for the 7 day authorisation and the 5 day merchant-initiated one, webhooks for retries, duplicates, order and signatures, and processing undelivered events for the 30 days. - Stripe documentation on money going back and out. Refunds, how disputes work and the payout object, plus currencies and the integration security guide on PCI DSS.
- Ilya Ganelin, Ledger: Stripe's system for tracking and validating money movement, 2024. Double-entry, clearing accounts that should end empty, 5 billion events a day, and 99.99 percent of dollar volume verified within four days.
- Nimish Sheth, Manas Kelshikar and Dhirendra Kumar Singh, Zero-Sum by Design: 10 Years of Uber's Payments Platform, Uber, 2026. Immutable money orders checked to sum to zero, adjustments as new orders, and serialized batch writes for high-traffic entities.
- Matt McNierney, How We Built Ledgers for High Throughput, Modern Treasury, 2024. The bank settlement account as a hot account, locking only entries that need it, and the queued path at a p90 of 1 second.
- Adyen documentation: the settlement details report and its line types, and currency codes for minor units and where Adyen differs from ISO 4217.