Skip to content

Payment system

A payment service takes a request from a merchant (“charge this customer 100.00 euros for this order”), asks a card network whether the charge is allowed, records the result, and keeps the books so that the merchant is paid the right amount later. The design problem is not speed. It is that the operation moves money, so the two mistakes that other systems forgive, doing it twice and forgetting it, are the two the design exists to prevent.

Functional requirements. Create a payment for a merchant. Look up the state of a payment. Refund a payment. Keep a record from which each merchant’s balance and each payout can be worked out. Subscriptions, fraud scoring, disputes and payouts to bank accounts are real and are left out, so that the lesson stays on the core.

Non-functional requirements. These are the targets we choose, not figures from a real service. A payment is charged at most once, however many times the request is sent. A payment that was charged is never lost from the books. The books can be checked against an outside record. A create call answers in under 1 second at the 99th percentile, most of which is the card network.

Scale. 8,100 payment attempts per second at the peak, of which about 20% are retries of an attempt already made.

Mental model. A payment system is a bank clerk who is handed the same slip several times by a customer on a bad line. The clerk keeps a book where every movement of money is written twice, once as taken from somewhere and once as put somewhere, never erased, and at the end of the day the book is compared with the card network’s own statement.

The requests per second lesson gives the method. The target is the load of the last stage in the lab, 8,100 attempts per second, and the table works backwards from it to the daily volume and forwards to the storage. Every assumption is in the table so that you can change it.

Quantity Working Result
Peak attempts per second the target 8,100
Average attempts per second, assuming the peak is 3 times the average 8,100 ÷ 3 2,700
Attempts per day 2,700 × 86,400 about 233 million
First attempts, which are the payments, if 80% of attempts are not retries 233 million × 80% about 187 million a day
Calls to the card network at the peak 8,100 × 80% 6,480 per second
Ledger entries per day, at 3 per payment 187 million × 3 about 560 million
Storage per day, at 1,000 bytes for a payment and 150 bytes for each of 3 entries 187 million × 1,450 bytes about 270 GB
Storage in 5 years 270 GB × 1,825 days about 494 TB
Idempotency keys held for 24 hours, at 1,000 bytes for a key and its saved reply 233 million × 1,000 bytes about 233 GB

The 3 for the peak, the 20% of retries and the byte sizes are assumptions. Three things follow whatever the exact values. The request rate is high but each request is small and simple: the work is not heavy computation. The data is large and only grows, because the ledger is never erased: 494 TB in five years is a sharded database and an archive, not one machine (storage and retention). And a fifth of the traffic is requests that must do nothing, which is a figure to keep in mind: 1,620 attempts per second, at the peak, that would each charge a card again if the design did not recognise them.

Two calls carry the traffic. The client makes up the key, as the idempotency keys lesson describes.

POST /payments Idempotency-Key: 4b0e8c1a-6f6d-4b7f-9d1f-2c6a1e0d9a11
{"merchant": "m_42", "amount": 10000, "currency": "EUR", "card": "tok_8f3k2"}
201 Created {"id": "pay_7Hq2", "status": "captured"}
GET /payments/pay_7Hq2
200 OK {"id": "pay_7Hq2", "status": "captured", "amount": 10000, "currency": "EUR"}

The amount is a whole number of cents, never a floating-point number. A payment has a state that only moves forward: pending (recorded, the card network not yet asked), then captured or failed. A payment whose call to the card network timed out stays pending until someone finds out what happened, which is the subject of the failure section below.

There are three tables, and the lab’s database holds the first two.

Table Key columns Meaning
payments id, merchant, amount, currency, status, created_at One row per payment. Its state is the only thing updated in place.
idempotency_keys key, request_hash, response, created_at One row per key: a fingerprint of the first request and the reply to send again.
ledger_entries id, transaction_id, account, direction, amount, created_at Append-only. Every payment writes several rows with the same transaction_id.

The lab starts with the simplest design that works. Each stage is designed for 3 times the load of the one before it, and the slider raises the load to 3 and 10 times its own design load, which shows where it runs out. Every figure is model output with illustrative inputs, and the model notes under the lab list what it leaves out.

A service that takes payments for merchants: it records each attempt, asks the card network to authorise it and keeps the books. Some of the attempts are retries, and a retry must never charge twice. Step through five stages, each adding the one thing the previous stage’s numbers called for, and raise the load to see what breaks.

Stage 1 of 5

Start simple: one database and one fee account

Design load of this stage: 100 req/s

What we add
API servers take a payment attempt, record it in one database, ask the card network to authorise it and update the platform’s fee account. Each attempt costs the database 3 queries (2 writes and 1 read of the payment’s status) and the fee account one update.
Why: the number that forced it
At 100 attempts per second the busiest part is the fee account, at 30% of the 333 updates per second it can do: it is one row, updated one transaction at a time, about 3 ms each. The database is at 8% of its 4,000 queries per second, with 300 asked.
What it costs
Cheap and easy to reason about: one place holds the state of every payment. The price is that every payment updates the same row in turn, and that nothing stops a payment sent twice from being charged twice.
What breaks next
At 3 times the load, 300 attempts per second, the fee account is at 90%: saturated. At 10 times it is at 300% and two thirds of the requests fail. Of the 300 attempts per second, 60 are retries, and each of them is a second charge.
Design load (100 req/s)
0.3 ms0.3 ms0.3 ms5 msMerchantsand appsHealthy<1%Payment APIHealthy1%PaymentsdatabaseHealthy8%Platform feeaccount (one row)Healthy30%Card network(external)Healthy1%
0.3 ms0.3 ms0.3 ms5 msMerchantsand appsHealthy<1%Payment APIHealthy1%PaymentsdatabaseHealthy8%Platform feeaccount (one row)Healthy30%Card network(external)Healthy1%

Each dot stands for many requests. The numbers show the real rate.

No bottleneck: every component has headroom.

Figures at this load

Busiest component
Platform fee account (one row)Healthy30% of its capacity
p95, whole request
327 ms
p99, whole request
468 ms
Requests served
100%100 req/s
Requests failed
0%0 req/s
Bottleneck
none
0 ms
Metrics
ComponentStateUtilisationOffered (req/s)Served (req/s)Rejected (req/s)p50p95p99
Merchants and appsHealthy<1%10010000 ms0 ms0 ms
Payment APIHealthy1%10010003.5 ms15 ms23 ms
Payments databaseHealthy8%30030003.5 ms15 ms23 ms
Platform fee account (one row)Healthy30%10010003 ms13 ms20 ms
Card network (external)Healthy1%100100069 ms300 ms461 ms
Traffic
100 req/s
Successful
100 req/s
Error rate
0%
Mean latency
131 ms
All stages at a glance

Each cell is the engine’s steady state for that stage at that load: the busiest component, how much of its capacity it uses, and the share of requests that fail.

All stages at a glance
StageDesign loadDesign load3× the design load10× the design load
1. Start simple: one database and one fee account100 req/s100 req/sPlatform fee account (one row): 30%none fail300 req/sPlatform fee account (one row): 90%none fail1K req/sPlatform fee account (one row): 300%67% fail
2. Add idempotency keys300 req/s300 req/sPlatform fee account (one row): 72%none fail900 req/sPlatform fee account (one row): 216%43% fail3K req/sPlatform fee account (one row): 720%95% fail
3. Replace the fee row with a double-entry ledger900 req/s900 req/sPayments database: 59%none fail2.7K req/sPayments database: 176%77% fail9K req/sPayments database: 585%99% fail
4. Split the payments database by merchant2.7K req/s2.7K req/sPayments database: 35%none fail8.1K req/sPayments database: 105%13% fail27K req/sPayments database: 208%92% fail
5. Read from replicas and reconcile with the card network8.1K req/s8.1K req/sPayments database: 65%none fail24K req/sPayment API: 152%58% fail81K req/sPayment API: 506%87% fail

Illustrative values, not benchmarks of any real product.

Model notes

Assumptions

  • Requests arrive at random, as a Poisson process, at a constant average rate.
  • Each node is one queue, served first-come first-served by several identical slots (instances × concurrency).
  • Service times are random with the stated mean; by default they are exponentially distributed.
  • Each node is analysed separately, with the traffic it receives treated as Poisson.
  • Every request is one attempt to pay. 20 attempts in every 100 are retries of an earlier attempt (a timeout, a double tap, a repeated delivery) and the other 80 are first attempts that do the work. The 20% is a teaching figure, not a measurement of a real service.
  • Every number (service times, capacities, the share of retries, the design loads) is illustrative model output, chosen to make the limit of each stage visible. None of them is a benchmark of a real database, ledger or card network.

Simplifications

  • Above capacity there is no steady state. The model switches to a fluid approximation: the node serves at capacity, its queue grows until it reaches its limit, and further requests are rejected.
  • Percentiles assume an exponential tail. A service-time variability other than exponential changes the mean wait but not the shape of the tail.
  • A node frees its slot as soon as it has done its own work, before waiting on the services it calls. Real thread-per-request servers hold the slot, so a slow dependency exhausts them faster than this model shows.
  • A request calls its dependencies one after another. Parallel fan-out is not modelled.
  • When a caller times out and gives up, the callee still finishes the work, so abandoned requests keep consuming capacity.
  • Retries add load. Their backoff and jitter decide when that load arrives, which only the per-request simulation shows.
  • Retry feedback is solved from the healthy starting point, so it finds one stable outcome. Systems that stay stuck in overload after the cause is gone are not shown.
  • A throughput limit (for example maximum writes per second) is modelled as slower service, not as a separate rate limiter.
  • A caller’s timeout counts the mean time its dependencies take, not their full distribution.
  • Latency percentiles for a whole request are estimated, over every request, including those that are rejected and fail quickly. The mean is exact, and the percentiles come from a gamma distribution that has that mean and the variance of the time spent in each component.
  • Each stage is shown in a steady state: the load is held and the engine says where queues build. A burst, a retry storm and a failover are not modelled; the retries are only counted as part of the load.
  • The idempotency store is drawn as its own component so that its load can be seen. In a design that saves the key and the payment in one transaction it is a table of the payments database, and its queries would be added to that database’s.
  • The card network is a single component that answers in about 100 ms and has room for 15,000 calls per second. Real providers set limits per merchant and answer in a wide range of times; declines, extra authentication steps and timeouts are not modelled.
  • The ledger is append-only: the three entries of a payment are written in one transaction of about 4 ms, 8 at a time on each of 6 instances. Entries that must be written on two shards, or in two regions, are not modelled.
  • Reconciliation is shown as continuous matching of each first attempt. Real reconciliation is mostly a batch over a settlement file that the card network publishes once a day, and what happens to a mismatch is not modelled.

Parameter values are illustrative. They are not benchmarks of any real product.

Stage 1, one database and one fee account. Each attempt costs the database 3 queries and the platform’s fee account one update. At 100 attempts per second the busiest part is the fee account, at 30% of the 333 updates per second it can do. It is a single row that every payment must update, one transaction at a time, about 3 ms each. At 3 times the load it is at 90%, and at 10 times it is at 300% and two thirds of the requests fail. The number that ends this stage is 333 updates per second on one row. There is also a problem the numbers do not show: 60 of every 300 attempts are retries, and each of them charges the card again.

Stage 2, idempotency keys. Every attempt carries a key, and an idempotency store answers the repeats. At 300 attempts per second, the 60 retries no longer reach the card network or the books. The fee account falls from 90% to 72%, and the database from 900 to 780 queries per second. The price is one lookup on every attempt, and a store that has to be exactly as reliable as the payment itself. Keys remove only the retries: at 3 times the load the fee account is at 216% and 43% of the requests fail.

Stage 3, a double-entry ledger. The fee row is replaced by appends. The three entries of a payment are written in one transaction and nothing is updated in place, so payments no longer wait for each other. At 900 attempts per second the ledger takes 720 payments per second at 6% of its 12,000 per second, where the fee row would be at 216%. The stage also gives the books their history, which the next sections use. At 3 times the load the payments database is at 176%, because it must answer 7,020 queries per second against 4,000, and 77% of the requests fail.

Stage 4, shards by merchant. The payments database becomes 5 shards of the same size, which can do 20,000 queries per second between them. The same 2,700 attempts per second that needed 7,020 queries per second on one database are now 35%. The price is that anything across merchants (a report, a search by card) touches every shard, and a transaction across two shards is no longer a plain database transaction. At 3 times the load, 8,100 attempts per second, the shards are asked for 21,060 queries per second against 20,000, and 8,100 of those are only reads of a payment’s status.

Stage 5, replicas and reconciliation. The status reads move to read replicas, and reconciliation workers compare the ledger with the card network’s report by reading the replicas, so that neither competes with payments. The shards fall to the 12,960 writes: 65%. The 2 replicas take 40,500 operations per second against 80,000, or 51%. The price is a status read that can be a moment behind. At 3 times the load, 24,300 attempts per second, the API servers are the first to run out, at 152% of their 16,000, and 58% of the requests fail. Behind them the shards are at 128%, the ledger at 107% and the idempotency store at 100%.

The module on idempotency explains the mechanism. A payment shows why each rule in it is needed.

The key and the payment are saved together. The service writes the key and a pending payment in one transaction, with a unique constraint on the key. If two requests with the same key arrive at the same moment, one insert wins and the other waits or fails, so only one payment exists. If the process dies after this transaction and before the card network is asked, the retry finds a pending payment under its key and carries on from there.

The card network gets a key too. The call from the service to the card network is itself a request that can be lost or time out. Providers such as Stripe accept an idempotency key on their own calls; the service passes the key of the payment, or one made from it, so that a retry of that call is recognised on their side as well. Without it the service’s key protects its own books and not the customer’s card.

A repeat gets the saved reply, and a different request is refused. The service stores a fingerprint of the first request. The same key with the same fingerprint gets the saved answer, including a saved failure. The same key with another amount is a client bug, and the right answer is an error, not the first reply (see the duplicate requests lesson).

Keys expire. Stripe says its keys can be removed once they are at least 24 hours old, and that a reused key then makes a new request. The 233 GB of the estimate is that 24-hour window. A retry that arrives after the window is a new payment, which is why clients must stop retrying well before it ends (see deduplication windows).

The first stage kept a balance in a row and updated it. The ledger replaces that with a record of every movement. In double-entry bookkeeping each transaction is written as entries on at least two accounts, and the debits equal the credits. Modern Treasury makes the point for developers: mutating a balance directly is simpler and more efficient, but it is more accurate to store immutable transactions and always compute balances from them, since a mutated balance is prone to errors that are hard to detect and reconcile.

A payment of 100.00 with a platform fee of 3% is one transaction of three entries.

Account Debit Credit
Card network receivable (money the network will pay us) 100.00
Merchant balance (money we owe the merchant) 97.00
Platform fees (our revenue) 3.00
Total 100.00 100.00

The two columns must be equal, and a transaction whose columns differ is rejected before it is written: that check is the whole point of the structure. A merchant’s balance is the sum of the credits minus the debits on its account. A refund is a second transaction that reverses the first: it does not delete it. A correction is another transaction. Nothing is updated, so there is no row that every payment must queue behind, which is what stage 3 shows, and the history needed to explain any balance is already there.

Two cautions. Reading a balance by summing every entry gets slower as the account grows, so real systems keep a running total derived from the entries (and can rebuild it from them). And the ledger and the payment state must change together: if they are in one database it is one transaction, and if they are two services, each write needs its own idempotency, with something like the transactional outbox between them, or a crash can leave a captured payment with no entries.

Even a correct design disagrees with the world sometimes. The card network keeps its own records of what it authorised and settled, and publishes a settlement report. Reconciliation compares three records: the payments table, the ledger, and that report, and lists the differences.

Payment Our ledger Settlement report What it means
pay_1 100.00 100.00 Matches.
pay_2 40.00 (missing) We think it was charged and the network does not: a call that failed after we recorded it, or a settlement still to come.
pay_3 (missing) 25.00 The network charged and we have no entry: a response we lost, the worst case for a customer.
pay_4 60.00 50.00 The amounts differ: a currency or fee rule, or a partial capture.
pay_5 30.00, 30.00 30.00 We recorded it twice and the network once: a duplicate that the key should have stopped.

The workers can find these rows and cannot settle them. Whether pay_2 should be retried, refunded or left for tomorrow’s report is a decision, made by a rule or a person, and its result is a new ledger transaction. That is also why reconciliation has to compare against something outside your own database: a ledger checked only against itself is always consistent, and says nothing about the card network. It runs mostly as a batch over a daily file, and the lab shows it as continuous matching of each payment, which is a simplification.

People ask for “exactly-once” payments. Tyler Treat’s argument is that exactly-once delivery is not available over a network, because a sender can never tell a lost message from a lost acknowledgement. The delivery semantics lesson gives the same choice: at-most-once can lose, at-least-once can repeat.

What a payment system builds instead has three parts. Retries, which make the delivery at-least-once, because losing a payment is not acceptable. Idempotent receivers, so that a repeat does nothing. And reconciliation, to catch what both missed. Together they have the effect of once.

A broker feature called exactly-once does not change this for the card. The replay and exactly-once lesson explains that such guarantees cover processing inside the system that offers them, for example a read, a transform and a write that all happen within one broker. Charging a card is a side effect outside any broker, and a request to the card network is exactly as repeatable as the network lets it be. The payment’s key is what makes it safe.

What happens if the card network does not answer

Section titled “What happens if the card network does not answer”

The service sent the charge and the call timed out. It does not know whether the card was charged. The two easy answers are both wrong: marking the payment failed may leave a charged customer with no order, and calling the network again without a key may charge twice.

What stops the damage: leave the payment pending, retry the same call with the same key so the network recognises it, or ask the network for the state of that payment by its reference, and apply the answer. If it cannot be found out, reconciliation finds the payment in the next report and a person or a rule decides. At the peak, 6,480 calls per second go to the network, so an outage of a few seconds leaves tens of thousands of pending payments to settle this way: the state has to be recorded before the call, not after.

What happens if the idempotency store loses its keys

Section titled “What happens if the idempotency store loses its keys”

Suppose the store restarts empty, or the key is kept in a cache that was flushed. A retry of an attempt that already succeeded looks new. At the peak that is 1,620 attempts per second that would charge again, and the customers who tapped twice are charged twice. The ledger shows the duplicates, and reconciliation finds them as in the pay_5 row, but they are found after the money moved.

What stops it: keep the key in the same durable database as the payment (a unique constraint is the last guard even if a faster store sits in front), keep keys for longer than any client retries, and give the card network’s own key as a second barrier.

What happens if the ledger and the payment disagree

Section titled “What happens if the ledger and the payment disagree”

A bug or a crash leaves a payment captured with no ledger entries, or entries for a payment that was rolled back. The merchant’s balance is wrong in a way no request will reveal. The ledger’s structure helps: a transaction whose debits and credits differ is rejected, and a periodic job can check that for every captured payment there is exactly one transaction. What repairs the difference is a new transaction that reverses or completes the wrong one, never an edit.

Decision What you gain What you pay When to choose otherwise
Idempotency key on every create A retry cannot charge twice A lookup on every attempt, a store to keep for 24 hours or more, a rule for a key reused with another request Never skip it for an operation that moves money; for a read or a set-to-a-value operation the key is unnecessary
Key and payment in one database The key and the work are saved together The payments database carries the key table’s load A separate fast store in front is acceptable if the database constraint stays the final guard
Double-entry, append-only ledger A full history, balances that can be rebuilt, no hot row, errors that can be detected More rows (3 per payment here), a balance that needs a running total A single prepaid balance with no accounting needs may do with a counter, at the cost of the history
Shard payments by merchant Capacity grows with shards: 5 shards give 20,000 queries per second Queries across merchants touch every shard; a very large merchant stays on one shard While one database carries the load, do not shard
Replicas for status reads and reconciliation Reads and scans stop competing with payments A status read can be a moment behind Read the shard when a customer has just paid and must see the result
Reconciliation against the card network Differences are found, including ones nobody expected Another system to run, and a process for what it finds Not optional when the money is real; its frequency and automation are the choices

An interviewer asks for this system in 45 minutes. A good answer starts from the failure (a request that may or may not have arrived), puts idempotency and the ledger in before scale, and says plainly that exactly-once delivery is not on offer. Write your answer before you read the strong one.

Interview question

Writing and reviewing an answer needs JavaScript.

The interviewer asks

Design the backend of a service that takes card payments for merchants. A customer taps “Pay” on a bad connection and the app sends the request three times. How do you charge them once, how do you keep the books, and how do you know the books are right?

Assume 8,100 payment attempts per second at the peak, of which about 20% are retries, and a card network that answers in about 100 ms and sometimes does not answer at all.

Write your answer first. The strong answer unlocks once you have written a real attempt.

0 of 80 characters written to unlock the strong answer

  • 8,100 attempts per second at the peak, with 20% retries, make about 233 million attempts and 187 million payments a day. The ledger grows by about 560 million entries and 270 GB a day, so 5 years is about 494 TB.
  • One fee row that every payment updates caps stage 1 at 333 updates per second: 90% at 300 attempts per second. Keys take the 60 retries off and bring it to 72%; a ledger of appends removes the row.
  • A payment’s key and its state are saved in one transaction, with a unique constraint on the key, and the key is passed to the card network too. Keys are kept for at least 24 hours.
  • A payment of 100.00 with a 3% fee is three entries, 100.00 = 97.00 + 3.00, and a refund or a correction is a new transaction. Reconciliation compares the ledger with the card network’s report and finds differences it cannot decide.
  • Exactly-once delivery over a network is not available: the design is retries, idempotent receivers and reconciliation.
  • Five shards give 20,000 queries per second (35% at 2,700 attempts per second). Replicas for reads bring the shards to 65% and the replicas to 51% at 8,100.

Next: Ride sharing, which finds the drivers near a point while 25,000 of them report their position every second.

Your progress

Built by GhaziAlibi.

© ShardCraft. All rights reserved.