Design a Payment System

How to design a payment platform that charges cards through an external processor exactly once, keeps a ledger, and reconciles with the processor.

Case study30 minLesson 6 of 8
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A payment platform lets online shops charge their customers' cards through one API. The platform sends each charge to an external card processor, records the result, keeps track of how much money each shop is owed, and pays the shops out.

This question is asked because it reverses the usual trade-off: most designs give up some consistency to stay available, while a payment system must stay correct even if that means rejecting requests. The difficulty comes from not knowing what happened. A call to the processor can time out after the card was charged, a notification can arrive twice or late, and the books must always balance. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a payment system.

You

Are we a platform that shops call and that uses an external card processor, or are we building the processor itself?

Interviewer

You are a platform. Shops call your API, and a third-party processor talks to the card networks. You keep a fee and pay the rest to the shops.

You

How many payments a day do we handle, and do we need refunds?

Interviewer

About 5 million a day, averaging $40. Yes, refunds are needed, and shops are paid out daily.

You

Then my priorities are to never charge a customer twice, never lose an acknowledged payment, and keep books that show exactly what each shop is owed. If I have to choose, I will reject a payment before I risk a double charge.

The functional requirements are to charge a card through the processor, report the status of a payment, refund all or part of a payment, keep a ledger of what each shop is owed, and reconcile with the processor every day. The non-functional requirements are that the card is charged at most once however often a shop retries, that no acknowledged payment is lost, that every movement of money can be audited for years, that a normal request is answered in about 2 seconds, and that correctness matters more than availability. The service stops waiting for the processor after 5 seconds.

Fraud detection, currency conversion, the bank transfer that pays shops and storing raw card numbers are out of scope. The processor gives the platform a token in place of the card number.

Estimate the scale

5 million payments a day is 5 million ÷ 86,400 ≈ 58 payments a second on average. Sales days can reach 10 times that, about 600 a second. One relational database handles that rate.

If 1 processor call in 1,000 times out, then 5,000 payments a day start with an unknown result, so the design must treat unknown outcomes as a normal daily case.

Estimate: Ledger growth

Each payment writes 3 ledger lines of about 200 bytes. How much ledger data do you hold after 7 years, as auditors may require?

You know
  • 5 million payments a day
  • 3 lines per payment, about 200 bytes each
  • Lines are never deleted
  • Keep 7 years

Show the working
  1. Lines per day: 5 million × 3 = 15 million
  2. Bytes per day: 15 × 106 × 200 B = 3 GB
  3. Per year: 3 GB × 365 ≈ 1.1 TB
  4. Seven years: 1.1 TB × 7 ≈ 7.7 TB

Estimate 7.7 TB (anything from 2 TB to 30 TB is a good answer)

Recent months stay in the main database, and closed periods move to cheaper storage that can still be queried.

Your turn: Define the API

Write the endpoints for charging a customer and checking a payment. How can the shop retry safely after a timeout?

Compare with a model answer

Creating a payment and creating a refund both carry an idempotency key chosen by the shop. A retry with the same key returns the original payment instead of creating a new charge.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API for shops
POST /v1/payments          Idempotency-Key: ord-5521-try
  body: { "amount": 4000, "currency": "USD", "card_token": "tok_...", "order_ref": "5521" }
  201 { "id": "pay_88", "status": "succeeded" }
  201 { "id": "pay_88", "status": "processing" }      outcome not known yet
  402 { "id": "pay_88", "status": "failed", "reason": "card_declined" }
  409 Conflict      a request with this key is still running
  422 Unprocessable the same key was used with a different body
 
GET  /v1/payments/{id}
  200 { "id": "pay_88", "status": "succeeded", "refunded": 0 }
 
POST /v1/payments/{id}/refunds   Idempotency-Key: ref-5521-1
  body: { "amount": 1500 }
  201 { "id": "re_9", "status": "processing" }
 
Webhooks we send to shops:  payment.succeeded, payment.failed, refund.succeeded

The API decision to argue is the processing response. When the processor does not reply in time, the platform does not know whether the card was charged, so it says the outcome is not known yet and the shop learns it from a webhook or by polling. Answering "failed" would make the shop ask the customer to pay again.

Your turn: Model the data

Which records do you need for a payment, its history and the money it moves? Which may be updated, and which may only be appended to?

Compare with a model answer

A payment row holds the status, which changes only through allowed transitions, and a uniquely constrained idempotency key. An append-only history records each status change. An append-only ledger holds entries that sum to zero within each transaction.

Model the data

Payments, keys, ledger
payments
  payment_id      VARCHAR(32) PRIMARY KEY
  merchant_id     BIGINT
  amount_cents    BIGINT
  status          VARCHAR(16)   -- created | processing | succeeded | failed | refunded
  processor_ref   VARCHAR(64) NULL
  idem_key        VARCHAR(64)
  request_hash    CHAR(64)      -- detects a reused key with a new body
  UNIQUE (merchant_id, idem_key)
 
payment_events                  -- append-only history
  payment_id, seq, from_status, to_status, source, created_at
 
ledger_entries                  -- append-only, never updated
  entry_id        BIGINT PRIMARY KEY
  txn_id          BIGINT        -- entries of one txn sum to zero
  account         VARCHAR(64)   -- "processor_receivable", "merchant:42"
  amount_cents    BIGINT        -- debit positive, credit negative
  created_at      TIMESTAMP

Money is stored as integer cents, never as floating point, because floating point cannot represent most decimal fractions exactly.

The writes are small and transactional: insert a payment with its key, change the status only from the expected old status, and write all of a payment's ledger lines or none. That calls for a relational database with ACID transactions, run as a single leader with a synchronous replica. A horizontally scaled key-value store gives up these transactions, and 600 payments a second does not need one.

Your turn: High-level design

Sketch the boxes: the shop's request, the call to the processor, how late results come back, and what checks the books every day.

Compare with a model answer

A payment service backed by one database calls the processor. A webhook handler applies results that arrive later, and a reconciler compares the daily settlement file with the ledger.

High-level design

One database holds the payments and the ledger, so a status change and its ledger lines commit together. Results reach it through the processor's reply and through its webhooks.Shop's server to API gateway (POST /payments); API gateway to Payment service; Payment service to Card processor (charge, key); Card processor to Webhook handler (webhook), asynchronous; Webhook handler to Payments and ledger DB (apply event); Payment service to Payments and ledger DB (state + ledger); Settlement files to Reconciler (daily file); Reconciler to Payments and ledger DB (compare).Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBSettlement filesReconcilerPOST /paymentscharge, keywebhookapply eventstate + ledgerdaily filecompare

request and replyasynchronous message

One database holds the payments and the ledger, so a status change and its ledger lines commit together. Results reach it through the processor's reply and through its webhooks.

The diagram does not show the webhooks sent to shops. Each is written to an outbox table in the same transaction as the status change, and a separate sender delivers it with retries, so a crash delays a notice instead of losing it.

A charge, a timeout, a retry and a late webhookUse the arrows or ← → keys
  1. A charge, a timeout, a retry and a late webhook, step 1Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBSettlement filesReconciler
    status
    -
    customer charged
    0

    1The shop sends POST /payments for $40 with the idempotency key ord-5521-try.

  2. A charge, a timeout, a retry and a late webhook, step 2Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBpay_88 createdSettlement filesReconciler
    status
    created
    customer charged
    0

    2One transaction inserts the key and the payment pay_88 with status created. The unique constraint on the shop and key stops a duplicate request from creating a second payment.

  3. A charge, a timeout, a retry and a late webhook, step 3Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorkey pay_88Webhook handlerPayments andledger DBSettlement filesReconciler
    status
    processing
    customer charged
    0

    3The service moves the payment to processing before it calls the processor, so a crash leaves a record that says the processor must be asked. The charge request carries pay_88 as its own idempotency key.

  4. A charge, a timeout, a retry and a late webhook, step 4Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorchargedWebhook handlerPayments andledger DBSettlement filesReconciler
    status
    processing
    customer charged
    $40

    4The processor charges the card, but its reply is lost. After 5 seconds the service stops waiting, so the money has moved and the platform does not know it.

  5. A charge, a timeout, a retry and a late webhook, step 5Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBSettlement filesReconciler
    status
    processing
    customer charged
    $40

    5The service answers 201 processing instead of failed. The shop's HTTP client already gave up after 3 seconds, so it never sees this answer.

  6. A charge, a timeout, a retry and a late webhook, step 6Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBkey seenSettlement filesReconciler
    status
    processing
    customer charged
    $40

    6The shop retries with the same key. The key already exists, so the service returns the stored payment, which is still processing, and creates no new charge.

  7. A charge, a timeout, a retry and a late webhook, step 7Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerevent evt_7 newPayments andledger DBSettlement filesReconciler
    status
    processing
    customer charged
    $40

    7A webhook arrives saying that pay_88 succeeded. The handler checks the signature and stores the event id, so a redelivery of the same event is ignored.

  8. A charge, a timeout, a retry and a late webhook, step 8Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBsucceededSettlement filesReconciler
    status
    succeeded
    customer charged
    $40
    ledger sum
    0

    8One transaction changes processing to succeeded, but only if the payment is still processing, and writes 3 ledger lines of +4000, −3880 and −120 cents that sum to zero.

  9. A charge, a timeout, a retry and a late webhook, step 9Shop's server to API gateway; API gateway to Payment service; Payment service to Card processor; Card processor to Webhook handler, asynchronous; Webhook handler to Payments and ledger DB; Payment service to Payments and ledger DB; Settlement files to Reconciler; Reconciler to Payments and ledger DB.Shop's serverAPI gatewayPayment serviceCard processorWebhook handlerPayments andledger DBSettlement filesReconciler
    status
    succeeded
    customer charged
    $40
    matched
    yes

    9The next day the settlement file lists pay_88 at $40. The reconciler finds a matching payment and matching ledger lines, so no person has to look at it.

1 / 9

Deep dives

Idempotency keys from the shop to the processor

An idempotency key lets a client repeat a request any number of times with the same effect as sending it once. The idempotency lesson covers the pattern, and three details decide whether it works in a payment system.

The first is to write the key in the same database transaction as the payment. With the key in a cache and the payment in the database, a crash between the two writes would let a retry create a second payment.

The second is to scope the key to the shop and to store a hash of the request body next to it. If the same key arrives with a different amount, the shop has a bug, and the service returns 422 instead of silently charging the old amount.

The third is to pass a key to the processor as well, here the payment id pay_88. If the processor's reply is lost and the service retries, the processor recognises the key and returns the first charge's result. Every hop that can be retried needs its own key.

The payment state machine and unknown outcomes

A payment is in exactly one state, and only certain moves between states are allowed.

FromToTriggered by
createdprocessingthe service is about to call the processor
processingsucceededthe processor's reply, a webhook or a status query
processingfaileda definite decline, or the processor confirming that it has no such charge
succeededrefundeda refund for the full amount succeeds

Each move is a conditional update, for example SET status = 'succeeded' WHERE payment_id = 'pay_88' AND status = 'processing'. If the processor's reply and its webhook race each other, the second update changes zero rows.

Payments that stay in processing are expected, so a sweeper job handles them. It asks the processor about every payment that has been in processing for more than a minute, using the idempotency key. A payment may move to failed only when the processor says it has no charge with that key, and that answer can race with the original request still in flight. The sweeper therefore waits longer than the processor's own timeout before it believes "not found", or it resends the charge with the same key.

Double-entry ledger or a balance column

A balance column per shop is easy to update but cannot be audited: when a balance is wrong, nothing records which payment made it wrong.

A double-entry ledger records every movement of money as entries whose amounts sum to zero. For the $40 payment, with a 3% platform fee of $1.20, the entries are:

AccountAmount (cents)Meaning
processor_receivable+4000the processor owes the platform $40
merchant:42−3880the platform owes the shop $38.80
platform_fees−120the platform earned $1.20

The sum is +4000 − 3880 − 120 = 0. Three rules make the ledger trustworthy.

  • Every transaction must sum to zero, which the service checks before it commits. Money then only moves between accounts and is never created or lost.
  • Entries are only appended. A mistake is corrected with a new reversing transaction and never by editing a row, so the history stays a complete audit trail.
  • Balances are derived data. A shop's balance is the sum of its entries. It can be cached in a row that is updated in the same transaction, but the entries are the source of truth.

Webhooks, retries and reconciliation

The processor delivers webhooks at least once and not always in order. The handler first verifies the signature. Then, in a single transaction, it stores the event id under a unique key and applies the event through the state machine, and only after the commit does it return 200. A repeated event hits the unique key and changes nothing. If the handler crashes before the commit, it never returns 200, so the processor sends the event again. Events that arrive out of order are harmless, because an illegal move changes zero rows.

Retries to the processor use exponential backoff with random jitter and the same idempotency key. Never retry on a second processor while the outcome on the first is unknown, because processors do not share idempotency keys and both could charge the card.

Reconciliation is the safety net behind everything else. Each day the processor publishes a settlement file listing what it actually charged and refunded. The reconciler matches each line to a payment by reference and amount.

When a mismatch appears, there are three possible responses, and the table summarises them. The usual design repairs mismatches that have one known cause and queues the rest for a person.

What to do with a reconciliation mismatch
OptionGood atBad atPick it when
Fix automatically Usual defaultIt is fast, and a missed webhook is repaired by applying the processor's state through the normal state machine.Repairing the wrong cause can hide a real bug.The mismatch has one known cause and one safe repair.
Queue for a personA person checks the case before any money moves.It is slow and costly, and 1 mismatch in 10,000 lines is 500 cases a day.The amounts differ, or the processor charged something the platform never recorded.
Trust our recordsIt needs no work.Errors accumulate until a payout is wrong.Never, because comparing with the processor is the purpose of reconciliation.

Bottlenecks and failures

The first limit is the database leader. If traffic grew another 10 times beyond the sales-day peak of 600 payments a second, it would reach 6,000 payments and 18,000 ledger lines a second, which is too much for one leader. The fix is to partition by merchant_id, so that all transactions of one shop stay on one partition. Platform-wide accounts such as platform_fees become hot rows, so each partition keeps its own copy and reports add the copies together.

When a component dies, the rule is to stop accepting payments rather than guess, because lost sales cost less than a double charge.

Component that failsWhat happensWhat the design does
A payment server, in the middle of a callThe payment stays in processing.The sweeper asks the processor by key and finishes the payment.
The database leaderWrites stop until the synchronous replica is promoted, usually within a minute.The API returns 503 in the meantime. Synchronous replication means no acknowledged payment is lost.
The processorCharges time out or fail.The API returns clear errors and stops retrying after a few attempts. It does not switch processors for payments with an unknown outcome.
The webhook handlerThe processor keeps retrying its events.The sweeper's status queries resolve the payments in the meantime.
The reconcilerMismatches are found later than usual.It is rerun over the missed days before any payout is made.

What a strong answer sounds like

LevelWhat the answer does
JuniorCalls the processor, saves the result and retries on failure, and adds an idempotency key only when prompted.
MidUses idempotency keys correctly, defines payment states, handles webhooks and stores money as integers.
SeniorTreats a timeout as unknown, passes keys to the processor, uses a double-entry ledger, reconciles every day and explains why correctness comes before availability here.
The charge times outStrong answer
Interviewer

Your call to the processor times out. What do you do?

You

A timeout means I do not know the outcome, so the payment stays in processing. I retry with the same idempotency key, so the processor returns the first result instead of charging again. If that also fails, the shop is told the payment is processing, and a webhook or a status query settles it later.

Interviewer

And if the webhook never arrives?

You

A sweeper asks the processor about every payment stuck in processing for more than a minute, and the daily reconciliation catches anything still wrong. All of these go through the same state machine.

Follow-up questions

How do refunds work?

A refund is its own record with its own idempotency key and its own states, linked to the original payment. When the processor confirms it, the platform writes reversing ledger entries. The total of partial refunds may not exceed the original amount.

How would you support authorize now and capture later?

For goods that ship later, the platform authorizes the card first, which reserves the funds, and captures the money when the order ships. This adds the states authorized and captured to the state machine. Authorizations expire after some days, so a job must capture or release each one in time.

Could an eventually consistent database be used?

It should not be used for payments and the ledger. The insert of the key and the change of status must be atomic, and an acknowledged write that is lost is lost money. A shop's dashboard can still read from a replica that is a few seconds behind, because it only displays data.

What happens when a customer disputes a charge?

A dispute, also called a chargeback, arrives from the processor some weeks after the payment, and it takes the money back from the platform. The platform records it as a new event on the original payment with reversing ledger entries, and it either recovers the amount from the shop's balance or deducts it from the next payout. The shop can submit evidence through the platform, and if it wins, another set of entries reverses the loss.

How are shops paid out?

A daily payout job sums each shop's ledger balance for payments that the processor has already settled, and it creates one payout record for that amount. The record carries its own idempotency key, so a retried job cannot pay the same shop twice. The job runs only after reconciliation for that day has finished, so that a payout is never based on payments the processor disagrees with.

Self-review: payment system0 of 13

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure