SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
  • Design Ride Sharing (Uber/Lyft)
  • Design a Payment System
  • Design Ticket / Hotel Booking
  • Design a Search Engine
  • Design Google Maps
  • Design a Collaborative Editor (Google Docs)
  • Design a Metrics and Monitoring System
  • Design a Distributed Message Queue (Kafka-like)
  • Design an E-commerce System (Amazon)
  • Design a Content Recommendation System (YouTube/Netflix)
System Design/Case Studies/Hard
Interview case study

Design a Payment System

Move money correctly: idempotency, a double-entry ledger, reconciliation and no lost or double charges.

⏱ 38 min readHard case studyAdvanced25 cross-questionsHas visualizer
Prompt60-sec answer45-min plan1 Clarify2 Estimate3 API + Data4 Design5 Deep dives6 Scale7 Wrap upCross-questionsVariationsScoringMistakesCheat-sheet

StartThe prompt and what is really being tested

The interviewer says

“Design a payment system.”

It is short on purpose. Your first job is to make it specific.

What they checkWhy it matters
Pinning down the scope“Payment system” can mean a card network, a wallet, or a platform that sits between merchants and a payment provider. A strong candidate asks which one, and says out loud that raw card numbers must never touch our servers.
Correctness when things time outThe hard question is not throughput. It is: the call to the payment provider timed out, so did the customer get charged? The interviewer wants idempotency keys, a status check, and a sweeper, not a hopeful retry.
Modelling moneyWhole numbers in the smallest unit, an immutable double-entry ledger, and balances you can always recompute. A single balance column that you update in place is the classic weak answer.
Consistency across systems you do not ownYou cannot run two-phase commit with a bank. The interviewer wants a state machine, a transactional outbox, compensations (void or refund) and idempotent consumers.
Proving it is right afterwardsReconciliation against the provider settlement file, alerts, and a way to repair differences without rewriting history. This is what separates a design from a system that is run in production.

TL;DRThe whole design in 60 seconds

We build a payment platform that lets merchants take payments through one or more external payment providers (PSPs). Correctness matters more than speed: money must never be created, lost or charged twice. Every request carries an idempotency key, every change to money is an immutable double-entry ledger entry written in the same database transaction as the payment state, and a daily reconciliation job proves our books match the provider's.

  • Scale is small, correctness is not: 1M payments a day is only about 12 a second, about 100 at peak. One well-run primary database with a synchronous replica is enough at first. The difficulty is what happens when a call fails halfway.
  • No double charge: the client sends an Idempotency-Key, we store it with the request hash and the result in the same transaction as the payment, and we pass our own key on to the provider. A repeat returns the saved answer.
  • Unknown outcome: if the provider call times out, the payment becomes PENDING, not FAILED. A sweeper asks the provider "what happened to payment X?" until it knows, and never retries a charge without the same key.
  • The ledger: integers in minor units, immutable entries, debits equal credits in every transaction, balances derived. Refunds and fixes are new entries, never edits.
  • Events and webhooks: a transactional outbox publishes payment events, and signed webhooks with retries tell merchants. No two-phase commit with outside parties.
  • Proof: compare the provider's settlement file with our ledger every day, classify every difference, and repair with new entries and a human review queue.
💡How to use this page
Read the 60-second answer first. Then work through steps 1 to 7 in order, and try each step yourself before reading the model answer. Finish with the cross-questions: say your answer out loud, then open the model one.

PlanA 45-minute plan

4
3
5
8
15
7
3
Minutes per step (total 45). A guide, not a rule: move time to the part the interviewer cares about.
StepMinutesWhat to get done
1. Clarify4Pay-in or payouts too, which payment methods, who holds card data, refunds, and what the guarantees are.
2. Estimate3Payments per second, provider calls in flight, unknown outcomes per day, ledger size, and the hot-merchant limit.
3. API and data5Create payment with an idempotency key, the state machine, the ledger tables.
4. High-level design8Gateway, payment service, idempotency, risk, provider adapters, ledger, outbox, webhooks, reconciliation.
5. Deep dives15Exactly-once effect, the ledger, consistency with the provider, reconciliation, and security.
6. Scale and failures7Provider outage, our database failover, a hot merchant, and stuck payments.
7. Wrap up3Recap, the trade-offs, and what you would add next.

Step 1Clarify requirementsabout 4 min

🤔
Pause. Try it yourself first
You have 60 seconds. Write five questions that change the design. Hint: who touches the card number, what happens if the provider does not answer, can a payment be partly captured or refunded, and how do we prove our numbers are right?

Questions to ask, and why

AskWhy you ask itTypical answerHow it changes the design
Are we building the card network and the bank, or a platform that sends payments to an external provider (PSP)?Building a network is a different company. A platform integrates with providers and owns the ledger and the merchant experience.A platform. We integrate with one or more PSPs and we do not build the card network.Our hard problems are idempotency, the ledger, reconciliation and provider failures, not card routing.
Pay-in only, or payouts to merchants and refunds too?Payouts move real money out and need their own safeguards and a bank file.Pay-in, refunds and payouts to merchants. Disputes are mentioned, not fully built.The ledger has accounts for merchant balances and payouts, and refunds are first-class.
Which payment methods: cards, wallets, bank transfers?Each has a different flow, delay and failure mode. Bank transfers settle in days.Cards and wallets first, through the PSP. Bank transfers are an extension.A payment is a state machine that can wait for async results, not one blocking call.
Who handles raw card numbers?Storing them puts our whole company in scope for strict card-industry rules (PCI DSS) and is a huge risk.Never us. Card data goes straight from the browser to the PSP, and we only hold a token.Hosted fields or a PSP-hosted form, tokens in our database, and a much smaller security scope.
May a payment be authorized first and captured later, and can it be partly captured or partly refunded?Two steps and partial amounts multiply the states and the ledger entries.Yes to authorize then capture, and yes to partial refunds.A richer state machine, and amounts tracked per payment (authorized, captured, refunded).
What must be guaranteed if the provider does not answer in time?This is the core question. A timeout does not mean the charge failed.The customer must never be charged twice, and we must never lose track of a charge.An idempotency key end to end, a PENDING state, a status inquiry, and a sweeper.
How do merchants learn the result: polling, webhooks, or both?Webhooks are delivered at least once and can arrive late or out of order.Both. Webhooks with signatures and retries, plus a GET to check the truth.An outbox, a webhook dispatcher, and merchants told to treat the API as the source of truth.
How many payments, and what are the latency and availability targets?It sizes the database and tells us whether we need sharding at all.1M payments a day, about 100 a second at peak. Create-payment 99.99% available. Most of the latency is the provider.A single primary per region is enough at first. Sharding by merchant is a later step.
Multiple currencies, tax and fraud?Each adds large amounts of work that can fill the whole interview.One currency per payment, no conversion. Fraud is a call to a risk service. Tax is out of scope.Currency is stored with every amount. We keep a clean place to call a risk score.

Write the scope on the board

Functional (must do)
  • •Create a payment with a payment-method token, and authorize and capture it
  • •Refund a payment, fully or partly
  • •Tell merchants the result with signed webhooks, and let them read the state with an API
  • •Pay out merchant balances on a schedule
  • •Reconcile with the provider every day and report differences
Non-functional (how well)
  • •Correct: money is never created, lost or charged twice. Strong consistency for the ledger
  • •Available: 99.99% for create-payment (about 53 minutes of downtime a year)
  • •Durable: no accepted payment is lost, even if a node or a zone fails
  • •Latency: our own work under 200 ms. The provider call dominates the rest
  • •Auditable: every change to money is recorded and cannot be edited
  • •Secure: no raw card data on our systems, and a small PCI scope
Out of scope (say it)
  • •Building a card network, an acquiring bank or a fraud model
  • •Currency conversion, tax, and invoicing
  • •A full dispute and chargeback workflow (we mention how it posts to the ledger)
  • •Merchant onboarding and KYC checks (a real system must do them; they shape the data, not this design)
🎤
Say it out loud
“Let me confirm the scope. We are a payment platform on top of external payment providers, not a card network. Card numbers never touch our servers: the browser sends them to the provider and we keep a token. We support authorize, capture, refunds and merchant payouts, with webhooks for results. The guarantee is that a customer is never charged twice and we never lose a charge, even if the provider times out. I will assume 1 million payments a day, about 100 a second at peak, and 99.99% availability for creating a payment. Currency conversion, tax, fraud models and the full dispute flow are out. Does that match?”

Step 2Estimate the scaleabout 3 min

🤔
Pause. Try it yourself first
On paper: payments per second, how many provider calls are in flight, how many outcomes are unknown each day, how big the ledger gets, and what limits one very busy merchant.

Assumptions (say them first)

AssumptionValue
Payments per day1 million (all numbers here are illustrative assumptions)
Peak rate100 payments per second for a few minutes
Provider call timeabout 0.8 s on average, and we give up after 5 s
Calls with an unknown outcome (timeout, dropped reply)0.1% of payments
Ledger entries per payment4 (the payment itself, plus the fee and the merchant share)
Row sizespayment 1 KB, ledger entry 200 B, event 500 B, idempotency record 1 KB
Events and webhooks per payment2
Idempotency keys kept for7 days
Time one transaction holds a merchant balance row lockabout 10 ms

The arithmetic, line by line

WhatMathsResult
Average payments per second1,000,000 ÷ 86,400about 12 per second
Peak versus average100 ÷ 12about 8 times
Provider calls in flight at peak100 per second × 0.8 s, and 100 × 5 s if the provider stallsabout 80 normally, up to 500 in a stall
Unknown outcomes per day1,000,000 × 0.1%1,000 a day (about 1 every 90 seconds)
Ledger growth1,000,000 × 4 entries × 200 B800 MB a day
Payments and events growth1,000,000 × 1 KB, and 2,000,000 × 500 B1 GB and 1 GB a day
Total growth per year(0.8 + 1 + 1) GB × 365, then × 3 copiesabout 1 TB a year, 3 TB with 3 copies
Database writes at peak (about 10 rows per payment)100 per second × 10about 1,000 writes per second
Idempotency table7 days × 1,000,000 × 1 KBabout 7 GB (small, can sit in the main database)
Webhooks to send2,000,000 ÷ 86,400about 23 per second on average
Hot merchant limit if every payment updates its balance row1 second ÷ 10 msabout 100 updates per second on one row
Daily settlement file to reconcile1,000,000 rows × 200 Babout 200 MB
Downtime allowed at 99.99%365 × 24 × 60 × 0.0001about 53 minutes a year
What the numbers tell us about the design
  • •The load is tiny (12 a second, 1,000 writes at peak). One primary with a synchronous replica is enough, and sharding can wait. This is a correctness problem, not a throughput problem.
  • •About 1,000 payments a day end with an unknown outcome. At that volume, any design that does not handle it correctly loses or doubles money every single day.
  • •A stall can put 500 provider calls in flight, so we need timeouts, a limit on concurrent calls per provider, and a circuit breaker.
  • •A merchant row that every payment updates caps at about 100 a second. The busiest merchant would hit it first, so the balance must be derived from entries, not updated in place.
  • •The ledger grows by 800 MB a day, so partition by month and keep history immutable. Reconciliation reads a 200 MB file once a day, which is cheap.
🎤
Say it out loud
“Let me do the maths. A million payments a day is about 12 a second and 100 at peak, so about a thousand database writes a second. That is small, one primary with a synchronous replica handles it, and storage grows by about 1 TB a year. What stands out is not the load. About 0.1% of calls end with an unknown outcome, so about 1,000 a day, and a design that mishandles them loses or doubles real money daily. Also, a single merchant balance row updated by every payment tops out near 100 a second, so I will derive balances from ledger entries instead.”

Step 3Define the API and the data modelabout 5 min

🤔
Pause. Try it yourself first
Write the call that creates a payment, and say what the client must send so a retry is safe. Then sketch the three tables where a mistake costs real money: payments, idempotency keys, and the ledger.

Endpoints

MethodPathRequestResponseNotes
POST/v1/paymentsIdempotency-Key header + { amount, currency, paymentMethodToken, merchantOrderId, capture: true | false }201 { paymentId, status } or 202 when still pendingAmount in minor units as an integer (1999 means 19.99). Same key and same body returns the saved response. Same key and a different body returns 422. A request still in flight returns 409. The merchant comes from the API key.
GET/v1/payments/{id}none200 { status, amountAuthorized, amountCaptured, amountRefunded, events }The source of truth for merchants. Webhooks are only hints. Scoped to the merchant, so another merchant gets 404.
POST/v1/payments/{id}/captureIdempotency-Key + { amount? }200 { status }Captures all or part of an authorized amount. A second capture over the authorized amount returns 409.
POST/v1/payments/{id}/refundsIdempotency-Key + { amount, reason }201 { refundId, status }The total refunded can never exceed the amount captured. The check and the write happen in one transaction.
POST(merchant URL) payment.succeededsigned webhook { eventId, type, data }2xx from the merchantSigned with HMAC and a timestamp. Retried with backoff for days. Delivered at least once, so merchants dedupe by eventId.
GET/v1/balancenone200 { available, pending, currency }Derived from ledger entries and cached for a few seconds. Never a column that is updated in place.

Data model

paymentsTypeWhy it is there
payment_id, merchant_id, merchant_order_ididsUnique on (merchant_id, merchant_order_id) so one order cannot become two payments.
amount, currencybigint, textWhole numbers in minor units. Never floating point.
statusenumCREATED, PENDING, AUTHORIZED, CAPTURED, FAILED, VOIDED, REFUNDED. Only legal transitions are allowed.
amount_authorized, amount_captured, amount_refundedbigintChecked in the same transaction as any change, so refunds cannot exceed captures.
psp_name, psp_reference, our_referencetextOur reference is saved before we call the provider, so a lost reply can always be looked up.
version, created_at, updated_atint, timestampsOptimistic locking, and the data for the stuck-payment sweeper.
idempotency_keysTypeWhy it is there
merchant_id, keyuniqueA unique constraint is what makes a repeat safe, even when two requests race.
request_hashtextDetects the same key with a different body (422).
status, response_code, response_bodyenum, int, jsonIN_PROGRESS or DONE, and the saved answer to replay.
created_attimestampOld keys are removed after about 7 days.
ledger_accounts and ledger_entriesTypeWhy it is there
account_id, type, currencyidsExamples: customer funds in transit, PSP clearing, merchant payable, platform fee revenue, refunds.
txn_id, entry_ididsEntries of one business event share a txn_id.
account_id, direction, amountid, enum, bigintA debit or a credit. For every txn_id the debits add up to the credits.
payment_id, created_atid, timestampLinks an entry to its payment. Entries are append-only: no UPDATE and no DELETE.
Create a payment (one database transaction)
BEGIN;
INSERT INTO idempotency_keys (merchant_id, key, request_hash, status)
VALUES (:m, :key, :hash, 'IN_PROGRESS');          -- unique: a repeat fails here
INSERT INTO payments (payment_id, merchant_id, merchant_order_id, amount, currency,
                      status, our_reference)
VALUES (:id, :m, :order, :amount, :cur, 'CREATED', :ourRef);
INSERT INTO outbox (event_id, type, payload) VALUES (:e, 'payment.created', :json);
COMMIT;
-- Only now call the PSP, passing our_reference as the PSP idempotency key.
📝Which store, and why
Payments, idempotency keys, ledger entries and the outbox all need real transactions, unique constraints and strong consistency, so a relational database with a synchronous replica is the right fit. At 1,000 writes a second and 1 TB a year it does not need sharding at first. We partition the ledger by month, and when one primary is no longer enough we shard by merchant id so a merchant and its ledger stay together. A key-value store would make the unique constraints and the multi-row ledger transaction hard to guarantee.
🎤
Say it out loud
“Creating a payment is a POST with an Idempotency-Key header, the amount in minor units as an integer, a payment-method token and the merchant's order id. I keep four tables in one transactional relational database: payments with a state machine, idempotency keys with a unique constraint and the saved response, an append-only double-entry ledger where debits equal credits, and an outbox for events. We save our own reference and the idempotency record in a transaction before we call the provider, so a lost reply can always be looked up later.”

Step 4Draw the high-level designabout 8 min

🤔
Pause. Try it yourself first
Draw the boxes between a merchant's request and the provider. Where is the idempotency check? Which box is the only one allowed to write money? What happens to the answer if the provider never replies?
Payment system: high-level design
🛒MerchantAPI key, webhook URL
→↓HTTPS
🚪API gatewayauth, rate limit
→↓Idempotency-Key
Payment service
🔁Idempotency layerunique key + saved reply
💳Payment state machine
📒Ledger servicedouble entry, append only
Outside parties
🛡️Risk servicescore, velocity
🏦PSP adaptersroute, retry, fail over
Events
📤Outbox + relay
📨Event bus
🔔Webhook dispatchersign, retry, back off
Back office
🧹Stuck-payment sweeperasks the PSP
⚖️Reconciliationsettlement file vs ledger
💸Payout service
Data
🗄️Primary DB + sync replica
🔐Token vault at PSPwe never hold card data
One payment service owns the state. The ledger is the source of truth for money. Events leave through an outbox. Reconciliation checks everything against the provider.
ComponentWhat it does
API gatewayAuthenticates the merchant's API key, applies rate limits, and rejects bad input early.
Idempotency layerStores the key with the request hash and the saved reply. A repeat returns the saved reply. A different body returns 422. A request still in flight returns 409.
Payment state machineOwns the status of a payment and allows only legal transitions, with a version number to stop two writers clashing.
Risk serviceReturns a score and rules (velocity, amount limits). We only call it. Its model is out of scope.
PSP adaptersOne adapter per provider. They route by cost and success rate, apply timeouts and a circuit breaker, and pass our idempotency key on.
Ledger serviceThe only writer of money. It posts balanced, immutable entries in the same transaction as the payment state change.
Outbox, event bus and webhook dispatcherPublish events reliably, deliver signed webhooks at least once with backoff, and let other systems react.
Stuck-payment sweeper and reconciliationAsk the provider about payments that stay PENDING, and compare the daily settlement file with our ledger.
Token vault (at the PSP)Holds the real card data. We store only a token, which keeps our security scope small.
Write path (follow one request)
  1. The merchant sends POST /v1/payments with an Idempotency-Key, the amount in minor units and a payment-method token.
  2. The gateway authenticates and rate-limits. The payment service inserts the idempotency record, the payment (CREATED, with our reference) and an outbox row in one transaction. A repeated key stops here and returns the saved reply.
  3. The risk service is asked for a score. A high score declines the payment with a clear reason, and the ledger is untouched.
  4. The adapter calls the PSP with our reference as the PSP's idempotency key and a 5 second timeout. The payment moves to PENDING first, so a crash now leaves a trail.
  5. On success, one transaction sets the payment to CAPTURED (or AUTHORIZED), posts the balanced ledger entries, stores the PSP reference, saves the reply on the idempotency key and writes an outbox event.
  6. On a timeout the payment stays PENDING and we return 202. The sweeper resolves it later by asking the PSP.
  7. The relay publishes the outbox event and the webhook dispatcher tells the merchant with a signed request, retried until it succeeds.
Read path (follow one request)
  1. The merchant calls GET /v1/payments/{id} (or reads its webhook).
  2. The payment service reads the payment from the primary or a recent replica, scoped to the merchant.
  3. It returns the status and the captured and refunded amounts, which always agree with the ledger.
  4. Balances come from summing ledger entries, cached for a few seconds. They are never read from a column that is updated in place.
  5. If the status is PENDING, the response says so. The merchant should wait for the webhook or poll, and must not create a new payment.
🎤
Say it out loud
“Here is the picture. A merchant calls our gateway. The payment service first writes an idempotency record, the payment in CREATED and an outbox row in one transaction, so a repeat of the same key just gets the saved reply. Then it asks the risk service, and calls the PSP through an adapter with our own reference as the PSP's idempotency key. When the PSP answers, one transaction updates the payment, posts balanced ledger entries and writes an outbox event. If the call times out, the payment stays PENDING and a sweeper asks the PSP later. Events go out through the outbox to signed webhooks, and a daily job reconciles the PSP file with our ledger.”

Step 5Deep dive into the hard partsabout 15 min

🧠The pattern for every deep dive
Problem → options → pick one → say why → say what it costs. Interviewers score the reasoning more than the choice.
5.1

Exactly-once effect with at-least-once reality

The problem: The customer double-clicks. The merchant's server retries after a network error. Our call to the PSP times out. In every case the same request can arrive twice, and the invariant is: one order produces at most one charge. The worst case is the timeout, where we cannot tell if the money moved.

OptionHow it worksGoodBad
Hope: retry on errorIf the call fails, call again.Nothing to build.A timeout often means the charge happened. A retry then charges the customer twice. This is the classic bug.
Our own idempotency key onlyStore a key per request in our database and return the saved answer on a repeat.Stops duplicates from the merchant and the double-click.Does not protect the call to the PSP. A timeout followed by our own retry still creates a second PSP charge.
Idempotency key end to endOur key guards our API. We also send a derived key (our reference) to the PSP, which returns the same result for the same key.A retry of the PSP call is safe. Covers the timeout case when the PSP supports keys.Depends on the PSP honouring keys, and its keys expire after some time.
Inquiry before retryBefore any retry, ask the PSP for the status of our reference. Only create a new charge if the PSP has none.Works even with a PSP that has weak idempotency. Resolves unknown outcomes.More calls and some delay. The inquiry API must be reliable and fast.
Pick
Keys end to end, a PENDING state for unknown outcomes, and an inquiry by our reference before any retry

The invariant is one order, at most one charge. We enforce it in three places. A unique constraint on the idempotency key stops duplicate requests from merchants. The same reference, sent to the PSP as its idempotency key, stops duplicate PSP charges. And an unknown outcome is never turned into FAILED: the payment stays PENDING until the PSP tells us what happened.

The key and the result are saved in the same transaction as the payment state, so we can never have a payment without its key, or a key without its payment. Two requests racing with the same key are separated by the unique constraint: the second sees IN_PROGRESS and gets 409.

What the retry looks likeWhat we do
Same key, same body, first request doneReturn the saved reply (same status code and body). No new charge.
Same key, same body, first request still running409 and Retry-After. Do not start a second call.
Same key, different body422. The key is for one request only. Never guess which body was meant.
New key, same order idA unique constraint on (merchant, order id) returns the existing payment. One order, one payment.
Our call to the PSP timed outMark PENDING. Ask the PSP about our reference. Only if it has no record, retry with the same reference.
⚠️Never turn a timeout into FAILED
A timeout means "we do not know". Showing "failed" invites the customer to pay again, and then both charges succeed.
🎤
Say it out loud
“The invariant is one order, at most one charge. I enforce it three ways. A unique idempotency key on our API, saved with the payment in one transaction, so a repeat gets the saved reply. The same reference sent to the PSP as its idempotency key, so a retried PSP call cannot charge twice. And a timeout never becomes failed: the payment stays pending, and before any retry we ask the PSP about our reference. If the PSP has no record we retry with the same key, and if it has one we adopt its result.”
5.2

The ledger: modelling money so it cannot go wrong

The problem: Money must be stored so that nothing is created or lost, every number can be explained, and mistakes are fixed without hiding them. A single balance column that we update in place can drift, lose history, and break under concurrent updates.

OptionHow it worksGoodBad
One balance column per accountUPDATE accounts SET balance = balance + :x.Simple and fast to read.No history. A bug or a race corrupts it silently, you cannot tell why it is wrong, and every payment fights for the same row.
Transaction log, balance derivedStore each change as an immutable row. The balance is the sum of the rows.A full history. Fixes are new rows. Easy to audit and replay.Summing is slow at scale unless you keep a cached or periodic balance.
Double-entry ledgerEvery business event posts at least two entries: a debit on one account and a credit on another, equal amounts, in one transaction. Debits always equal credits.A built-in check: if the sums differ, something is wrong. Every unit of money has a source and a destination.More rows and a chart of accounts to design. Needs discipline.
Event sourcing for everythingStore events for the whole payment system and rebuild state from them.Total history and replay.Heavier to build and query, and not required to get a correct ledger.
Pick
An append-only double-entry ledger in the same database transaction as the payment state, with balances derived and cached

The invariants are: entries are never changed or deleted, debits equal credits for every transaction, and balances are derived from entries. A bug can then be found (the sums will not match), explained (follow the entries) and fixed (post a correcting entry). Money is a whole number of minor units, with the currency next to it. A payment, its fee, a refund and a payout each post entries inside the transaction that changes the payment, so the books and the state cannot disagree.

A merchant's balance row would be a hot spot if every payment updated it: at about 10 ms per update that is about 100 a second. So we write only entries (inserts do not contend), compute balances by summing, and keep a cached balance refreshed every few seconds or by a batch. A payout checks a conservative balance.

EventDebitCreditAmount (example)
Customer pays 20.00, fee 0.60PSP clearing 20.00Merchant payable 19.40, Platform fee 0.602000 = 1940 + 60
Refund 5.00 to the customerMerchant payable 5.00PSP clearing 5.00500
Payout 14.40 to the bankMerchant payable 14.40Payout in transit 14.401440
Fee correction found in reconciliationPlatform fee 0.10Merchant payable 0.1010 (a new entry, the old one stays)
Post a capture (all in one transaction with the status change)
BEGIN;
UPDATE payments SET status = 'CAPTURED', amount_captured = :amt, version = version + 1
 WHERE payment_id = :id AND version = :seen AND status = 'AUTHORIZED';  -- 0 rows: stop
INSERT INTO ledger_entries (txn_id, account_id, direction, amount, payment_id) VALUES
  (:t, :pspClearing,   'DEBIT',  2000, :id),
  (:t, :merchantPay,   'CREDIT', 1940, :id),
  (:t, :platformFee,   'CREDIT',   60, :id);
-- a deferred check (or a test) that SUM(debits) = SUM(credits) for :t
INSERT INTO outbox (event_id, type, payload) VALUES (:e, 'payment.captured', :json);
COMMIT;
🎤
Say it out loud
“I would keep money as an append-only double-entry ledger. Amounts are integers in minor units. Every event posts balanced entries, debits equal to credits, in the same transaction as the payment status change, and entries are never edited. Balances are derived by summing, with a cached balance, so a busy merchant does not become a hot row that caps us near a hundred updates a second. A mistake is fixed with a new correcting entry, and if debits and credits ever differ, we know something is wrong.”
5.3

Staying consistent with systems we do not own

The problem: A payment touches our database, the PSP, the merchant's server and other internal systems. We cannot run one transaction across them. Our commit can succeed while publishing the event fails, the PSP can charge while our reply is lost, and a webhook can arrive twice or out of order.

OptionHow it worksGoodBad
Two-phase commit across partiesA coordinator asks everyone to prepare, then commit.All or nothing in theory.The PSP and the bank do not take part. Locks are held while waiting, and a coordinator crash blocks everyone.
Dual writeWrite to the database, then publish the event in code.Easy.If the process dies between the two, the database and the event disagree. The classic way to lose an event.
Transactional outbox + state machineWrite the change and an outbox row in one local transaction. A relay publishes the row at least once. Each step has an explicit state, and failures are fixed with compensations (void or refund).Local transactions only. No lost events. A crash resumes from the state.Consumers see duplicates and must dedupe. State machines and compensations take care to design.
Event sourcing as the logMake the event log the source of truth, with state derived from it.Natural history and replay.A larger change of the whole system. Not needed for this problem.
Pick
Local transactions, a transactional outbox, an explicit state machine and compensations, with idempotent consumers

Each hop gets its own guarantee. Inside our database we use one transaction for state, ledger entries and the outbox row. Between us and the PSP we use idempotent calls and a status inquiry, and a compensation if a later step fails: a void before capture, a refund after. Between us and everyone else we use the outbox: events are published at least once, in order per payment, and every consumer dedupes by event id.

Webhooks follow the same rule. We sign them (HMAC with a timestamp so they cannot be replayed), retry with backoff for days, and tell merchants that delivery is at least once, so they must dedupe by event id and treat GET /payments/{id} as the truth. See Saga, Outbox and Compensating Transactions for the building blocks.

StateHow we get hereWhich way out
CREATEDRequest accepted and savedPENDING when we call the PSP, FAILED if risk declines
PENDINGPSP call started or outcome unknownAUTHORIZED, CAPTURED or FAILED once known (sweeper or webhook from the PSP)
AUTHORIZEDPSP holds the fundsCAPTURED, or VOIDED if the merchant cancels or the hold expires
CAPTUREDMoney is ours to settleREFUNDED (partly or fully), or a dispute
FAILED, VOIDED, REFUNDEDFinalA correction is a new entry, never a status rewind
🧠Why not 2PC here?
Two-phase commit needs every party to cooperate and to lock resources while it waits. A payment provider will not do that for you, and a stalled coordinator would hold up payments. A state machine with compensations is slower to reason about, but it keeps working when one party is down.
🎤
Say it out loud
“We cannot run a transaction across the PSP and the merchant, so I use local transactions and make every hop safe to repeat. Inside our database, the state change, the ledger entries and an outbox row commit together. A relay publishes events at least once, and consumers dedupe by event id. With the PSP we rely on idempotent calls and a status inquiry, and if a later step fails we compensate: void before capture, refund after. Webhooks are signed, retried with backoff, and merchants are told to dedupe and to treat the GET endpoint as the truth.”
5.4

Proving it is right: reconciliation and repair

The problem: Even a careful design drifts: a reply is lost, a webhook never arrives, a provider changes an amount, a bug posts the wrong entry. We need to find every difference between our books and the provider's, and fix it without rewriting history. Nobody should learn about a missing charge from an angry customer.

OptionHow it worksGoodBad
Trust our own databaseAssume the ledger is right.Nothing to build.Silent errors pile up for months and are found by auditors.
Real-time checks onlyCompare each payment with the PSP as it happens.Fast feedback.Cannot see what the PSP settles later, fees, adjustments or payments it recorded that we did not.
Daily settlement reconciliationLoad the PSP settlement file and match it to our ledger by PSP reference and amount. Classify every difference and route it.Catches all kinds of drift. The standard practice in finance.A day of delay, and a team to handle the exceptions.
Reconciliation plus sweepers and alertsAdd a sweeper for payments stuck in PENDING, and alerts on rates (unknown outcomes, mismatches, ledger imbalance).Most problems are found within minutes, and the rest by the daily job.More moving parts to keep healthy.
Pick
Daily settlement reconciliation, plus a stuck-payment sweeper and alerts, with repairs as new entries

The sweeper asks the PSP about every payment that stays PENDING more than a few minutes, using our reference. That is why we save the reference before the call: without it there is nothing to look up. The daily job compares the settlement file with the ledger and sorts each row into: matched, missing at the PSP, missing in ours, amount differs, duplicate, or settles on the next day. Each class has a default action, and anything that is not routine goes to a human queue.

Repairs are new ledger entries (an adjustment, a refund, a reversal), never edits. We also watch simple health numbers, such as the share of unknown outcomes and the sum of all ledger debits minus credits, which must always be zero. Disputes and chargebacks post to the ledger the same way.

Difference foundUsual causeAction
In our ledger, not in the PSP fileOur entries without a real charge, or the file is lateAsk the PSP. If no charge, reverse our entries and tell the merchant.
In the PSP file, not in our ledgerWe gave up after a timeout, but the PSP chargedCreate the payment from the PSP data, or refund if the order is gone.
Amount differsPartial capture, fee, rounding or a currency issuePost an adjustment entry and find the cause.
Two charges for one orderA retry without an idempotency keyRefund the extra charge, and fix the missing key.
On the next day's fileCut-off timeWait a day. Not an error.
🧠Play with it
The visualizer below runs a day of ten payments against a settlement file with seeded problems. Turn off "we saved our reference" or "the retry sent an idempotency key" and watch which rows become impossible to match.
🎤
Say it out loud
“A careful design still drifts, so I would prove it daily. Every payment gets our own reference saved before we call the PSP, so a lost reply can always be looked up. A sweeper asks the PSP about anything stuck in pending. Each day we match the settlement file to the ledger by reference and amount, and classify each difference: missing at the PSP, missing in ours, amount differs, duplicate, or next-day settlement. Routine ones are fixed by rules, the rest go to a person, and every repair is a new ledger entry, never an edit. We also alert if debits ever differ from credits.”
5.5

Security, compliance and provider failover

The problem: A payment system is a prime target and is subject to strict rules. We must keep sensitive data out of our systems, limit who can do what, and keep taking payments when one provider is down, without sending a payment twice.

OptionHow it worksGoodBad
Store card numbers ourselves, encryptedCollect card data, encrypt it, and send it to the PSP from our servers.Full control of the flow.Our whole company falls into the strictest scope of the card-industry rules (PCI DSS), and a breach is catastrophic.
Hosted fields or a PSP-hosted pageThe browser sends the card data straight to the PSP, which returns a token. We only see the token.Card numbers never touch our systems. A much smaller scope.Less control of the form's look, and a dependency on one PSP's token format.
Our own vault with tokensA separate, isolated vault service stores card data and gives out tokens.Portable between PSPs.That vault is in full scope and must be built and run to the highest standard.
Several PSPs with routingRoute each payment by cost, success rate and method, and fail over if one is down.Higher availability and negotiating power.Failover must not double-charge. Tokens may be tied to one PSP.
Pick
Hosted fields with PSP tokens, least privilege everywhere, and several PSPs behind adapters with careful failover

A real payment system must meet card-industry and privacy rules, and they shape the design: keep card data out of our systems, encrypt what we do hold (customer details, bank accounts) with keys in a KMS, keep secrets out of code, log every sensitive action in an audit log, and give each service and person only the access they need. These are design constraints, not a claim that any particular system is compliant.

For failover, the rule is: never send the same payment to a second PSP until we know the first one did not charge. If PSP A times out, we ask A about our reference first. Only a definite "no record" allows a retry, with a new reference, on PSP B. Routing uses a circuit breaker per provider, and tokens that are tied to one PSP stay with it.

ControlWhat it does
Tokenization at the PSPWe keep a token. The card number never reaches our network.
Encryption and key managementSensitive fields encrypted at rest with keys in a KMS, rotated, and with access logged.
Least privilege and separation of dutiesSupport staff cannot move money. Payouts need a second approval. Service accounts have narrow scopes.
Audit logEvery change of money, role or setting is recorded and tamper-resistant.
Rate limits and velocity checksStop card testing and runaway merchants. Alert on odd patterns.
Signed requests and webhooksHMAC signatures and timestamps stop forged or replayed calls.
🎤
Say it out loud
“The first security decision is that card numbers never touch us: hosted fields send them to the PSP, and we keep only a token, which keeps our compliance scope small. Everything sensitive we do store is encrypted with keys in a KMS, secrets stay out of code, every money action is audit-logged, and access is least-privilege with a second approval for payouts. For availability I would use several PSPs behind adapters with a circuit breaker each, but with one hard rule: never try a second provider until the first has told us it did not charge.”
VisualizerReconcile a day of payments against the provider's fileStep through ten payments checked against the settlement file. Then turn off “we saved our own payment reference” or “the retry sent an idempotency key” and watch which rows turn into duplicates or become impossible to match.
We saved our own payment reference before calling the PSP
Our retry sent the same idempotency key to the PSP
Our ledger has 10 payments for the day. The PSP settlement file echoes our reference, and each row is matched on that reference and the amount. Amounts are shown in money (minor units ÷ 100).
OrderOur ledgerPSP fileResult
ord-10112.00 capturedP-9001 · 12.00Matched
ord-10245.00 capturedP-9002 · 45.00Matched
ord-10325.00 capturedP-9003 · 25.00Matched
ord-10480.00 capturedP-9004 · 75.00Amount differs
4 of 11 rows checked
Clean
3
matched, auto-fixed or timing
Needs a person
1
cannot be fixed by a rule
Net difference
−5.00
PSP minus our ledger
ord-104: Amount differs. The PSP captured less than we recorded (maybe a partial capture or a fee). Post a new adjustment entry. Never edit the old one.

A simplified model with fixed data and no random numbers. With our reference saved before the call, the timed-out ord-106 matches and the sweeper fixes it. Without it, ord-106 and the PSP row become two rows nobody can join. With no idempotency key on the retry, the PSP charges ord-103 twice. The net difference is “money in the PSP file minus money we booked as captured”, before any repair. Errors can cancel each other out in a total, so we also count the rows that need a person.

Step 6Scale, bottlenecks and failuresabout 7 min

🤔
Pause. Try it yourself first
Run a bad day. What happens when the PSP stalls for two minutes? When our primary database fails over? When one merchant is half of all traffic? When 1,000 payments a day are stuck?

What breaks first, and the fix

BottleneckFix
A slow PSP ties up threads and connections (up to 500 calls in flight)A hard timeout, a limit on concurrent calls per PSP, a circuit breaker, and a bulkhead so one provider cannot starve the others.
One merchant's balance row updated by every payment (about 100 a second cap)Insert-only ledger entries, derived balances with a cached copy, and batch posting for very busy merchants.
Ledger table growth (800 MB a day)Partition by month, keep recent partitions on fast storage, and archive older ones. Entries are immutable, so archiving is safe.
Database writes (about 1,000 a second at peak)One primary is fine to start. Then add read replicas for GETs, and shard by merchant id when a single primary is no longer enough.
Webhook backlog when merchants are downA per-merchant queue with exponential backoff for days, a cap on retries, and a dashboard so the merchant can replay events.
The daily reconciliation jobStream the 200 MB file, match by an indexed PSP reference, and run it per PSP in parallel.

What if a part fails?

FailureHow the design copes
The PSP times outPayment stays PENDING. We ask the PSP about our reference. If it has no record we retry with the same key. The customer is told it is processing, not that it failed.
The PSP is fully downThe circuit breaker opens. New payments route to another PSP (a new reference, only after the first call is known not to have charged). If there is none, we return a clear error, and do not queue charges silently.
Our primary database fails overA synchronous replica takes over with no committed data lost. In-flight requests retry with their idempotency keys. Payments left PENDING are picked up by the sweeper.
We crash after the PSP charged but before we saved the resultThe payment is PENDING with our reference. The sweeper asks the PSP, finds the charge and completes the state and ledger entries.
The event bus is downEvents stay in the outbox table. The relay publishes them when the bus returns. No payment is blocked.
A merchant's webhook endpoint is downRetries with backoff for days. The merchant can read the truth from the API, and replay events from a dashboard.
What to monitor
  • •Share of payments in PENDING more than 5 minutes, and the age of the oldest
  • •Success, decline and error rate by PSP, with provider latency at p50 and p99
  • •Ledger check: total debits minus total credits (must be exactly zero), checked every minute
  • •Idempotency hits (repeats) and 422 mismatches, and the unknown-outcome rate
  • •Reconciliation: rows matched, auto-fixed and sent to a person, and the net money difference
  • •Webhook delivery: backlog, retries, and merchants that have been failing for hours
Security and abuse
  • •Card data never touches our servers (tokens only), and our scope stays small
  • •Merchant API keys are scoped, rotated, stored hashed, and rate-limited
  • •Webhooks are signed with a timestamp so they cannot be forged or replayed
  • •Sensitive fields are encrypted with keys in a KMS, and secrets are never in code or logs
  • •Payouts need approval and velocity limits. Every money action is audit-logged

Step 7Wrap upabout 3 min

A payment platform on external providers: one transactional database holding payments, idempotency keys, an append-only double-entry ledger and an outbox. An Idempotency-Key guards our API and, as our reference, the provider call. Unknown outcomes stay PENDING until the provider says what happened. Events go out through the outbox, and a daily reconciliation proves our books match the provider's.

Trade-offs you made

DecisionWhat we gainWhat it costs
A relational database with strong consistencyReal transactions, unique constraints and a ledger you can trustA harder path to very large scale (sharding by merchant later)
An append-only double-entry ledgerHistory, an automatic check that debits equal credits, and easy auditsMore rows, a chart of accounts to design, and derived balances
PENDING for unknown outcomesNever a wrong FAILED, and no double chargeCustomers wait, and a sweeper and reconciliation must run well
State machine and compensations instead of 2PCWorks with parties that will not join a transactionMore states to design and test, and refunds instead of rollbacks
Hosted fields with PSP tokensA small security scope and no card data to loseLess control of the form and some lock-in to token formats
Multiple PSPsAvailability and better pricesFailover logic that must never double-charge, and more to reconcile
If we had more time, we would…
  • •Shard the database by merchant id, with a separate ledger per shard group and sagas for cross-shard transfers
  • •A proper dispute and chargeback flow, posting to the ledger and tracking deadlines
  • •Multi-currency with explicit rates, rounding rules and a revaluation process
  • •A rules engine for routing PSPs by cost and success rate, with automatic tuning
  • •Self-service merchant tools: webhook replay, reconciliation reports and balance history
🎤
Say it out loud
“To recap: a payment platform on top of external providers. One transactional database holds payments, idempotency keys, an append-only double-entry ledger and an outbox. An idempotency key protects our API, and our own reference protects the provider call, so a retry cannot charge twice. A timeout leaves the payment pending until we ask the provider. Events leave through the outbox, and a daily reconciliation proves our books match. The trade-offs are strong consistency over easy scaling, and honest pending states over fast but wrong answers. Next I would shard by merchant and build the dispute flow.”

Q&ACross-questions (25)

💡How to practise
Cover the answer. Say yours out loud in 30 to 60 seconds. Then open the model answer, the follow-up, and the weak answer to see what to avoid. Use Open all at the top for a quick read.
Warm-upProbingCurveballWarm-up = basics. Probing = tests depth. Curveball = changes the problem.

Duplicates and unknown outcomes

The heart of the interview. Show that you treat a timeout as unknown, and that every retry is safe.

The ledger and money

Show that you can model money so mistakes are visible, and that you know where it gets hot.

Consistency with the provider and the outside world

Where the senior candidates separate themselves: multi-step failures and honest trade-offs.

Curveballs and operations

Changed requirements, security, testing and growth.

What ifIf the interviewer changes the problem

A change in requirements is a test of whether you understand why your design looks the way it does.

New requirementWhat changes in the design
Add payouts to bank accountsA payout service posts a payout-in-transit entry, sends a bank file or API call with an idempotency key, and clears the entry when the bank confirms. Failed payouts reverse the entry. Approval limits and a conservative balance check protect against overpaying.
Add disputes and chargebacksA dispute is a new state and a set of ledger entries that move the amount (and the fee) out of the merchant's payable account into a held account, with deadlines for evidence. Winning or losing posts the final entries. Nothing is edited.
Support many currenciesAmounts carry a currency, ledger accounts exist per currency, and a conversion is its own balanced transaction with a rate and a position account. Reconciliation is per currency and per provider.
Bank transfers that settle in daysMore PENDING time, and a state for waiting. We rely on webhooks and polling, and reserve the merchant's funds only after the transfer clears. The sweeper and reconciliation matter more.
Marketplace: split one payment between several sellersOne payment, several credit entries in the same transaction (one per seller plus the platform fee). Refunds and disputes must be split in the same proportions. Payouts are per seller.
The interviewer asks for 99.999% availabilityActive-active regions with each merchant homed in one region, synchronous replication inside it, and a fenced failover. Say honestly that strong consistency and five nines pull against each other, and that a short pause on one merchant is better than a split ledger.
Data must stay in one countryShard and route by region so a merchant's payments, ledger and backups live in its region. Cross-region reporting uses aggregates, not raw rows.
Add subscriptions and retries of failed cardsA scheduler creates payments with deterministic idempotency keys (subscription id and billing date). A retry policy (days, backoff) and customer notifications handle declines. The scheduler is a separate service.

ScoreHow answers are judged

AreaWeakGoodGreat
RequirementsStarts drawing at once. Never asks who touches card data or what a timeout means.Asks about methods, refunds and card data, and sets the scale.Also names the guarantees (never double-charge, never lose a charge), sets the scope boundary with the provider, and says what is out of scope.
EstimationNo numbers, or a huge QPS guess that justifies sharding.Gets payments per second and storage and sees that the scale is small.Shows that unknown outcomes (about a thousand a day) and the hot merchant row, not throughput, drive the design.
CorrectnessRetries on error, or says a transaction makes it exactly once.Idempotency keys, a state machine and a PENDING state.Walks the timeout case end to end, uses our reference as the provider's key, an inquiry before retry, and a sweeper, and explains where exactly-once effect begins and ends.
Money modelA balance column updated in place, or floats.Integers in minor units and an immutable ledger.Double-entry with balanced transactions in the same commit as the state, derived balances, hot-account handling, and fixes by new entries.
Consistency and recoveryA distributed transaction across everyone, or a dual write.An outbox and idempotent consumers.Outbox, saga with compensations, signed webhooks with retries, daily reconciliation with a classified difference list, and repair by new entries.
Trade-offs and operationsPresents one design as obviously right.Compares options and mentions monitoring.Names the cost of every choice, states what is cut for 45 minutes, covers provider failover that never double-charges, security scope and what to alert on.

AvoidCommon mistakes on this question

MistakeDo this instead
Treating a timeout as a failure and letting the customer pay againA timeout is unknown. Keep PENDING, ask the provider by our reference, and tell the customer it is processing.
Retrying a charge without an idempotency keySend our reference as the provider's key on every attempt, and check the status before any retry after a long gap.
A balance column that is updated in placeAn append-only double-entry ledger with derived balances, so history and checks exist.
Floats for moneyIntegers in minor units with the currency stored beside them.
A dual write: save, then publish in codeA transactional outbox, so the event and the change commit together.
Two-phase commit with the payment providerLocal transactions, idempotent calls and compensations (void or refund).
Storing card numbersHosted fields and tokens, so card data never reaches our servers.
No reconciliation, or comparing only daily totalsMatch row by row against the settlement file and count rows needing a person, because errors can cancel in a total.

Revise60-second revision sheet

  • ✔The scale is small: 1M payments a day is about 12 a second, 100 at peak. Correctness is the problem.
  • ✔Idempotency: key + request hash + saved reply, unique in the database, in the same transaction as the payment. Same key, different body is 422.
  • ✔Timeout = unknown: stay PENDING, ask the provider by our reference, and never turn it into FAILED on a guess.
  • ✔Money: integers in minor units, with the currency stored beside them.
  • ✔Ledger: append-only double entry. Debits equal credits. Balances are derived. Fixes are new entries.
  • ✔One transaction: payment status, ledger entries and the outbox row commit together.
  • ✔Across parties: outbox, state machine, compensations (void before capture, refund after). No 2PC.
  • ✔Webhooks: signed, retried with backoff, at least once. Merchants dedupe and treat GET as the truth.
  • ✔Reconcile daily: settlement file vs ledger by reference and amount. Classify differences and repair by new entries.
  • ✔One line: “One order, one payment; one transaction, one balanced ledger entry; and when we do not know, we ask, we never guess.”

Read these topics next

Idempotency→

The idea behind every retry in this design.

Outbox Pattern→

How an event is published without losing it.

SAGA Pattern→

Multi-step work and compensations across parties.

Exactly-Once Processing→

What exactly-once can and cannot mean.

ACID Transactions→

The guarantees the ledger transaction relies on.

Transaction Isolation Levels→

What two concurrent payments can see of each other.

Audit Logs→

The tamper-resistant record of every money action.

Key Management (KMS)→

How sensitive fields are encrypted and keys are protected.

← Previous
Design Ride Sharing (Uber/Lyft)
Next →
Design Ticket / Hotel Booking