Systemsfor Aravinda
0 / 78 core
Week 10 · Case studies

Design a payment system

2 hours · core path

Read first: Idempotency and the exactly-once myth, Transactions and isolation, The outbox pattern and sagas

In one sitting

A timeout is not evidence that the charge failed. The client retries with the same idempotency key, the books are a set of ledger entries, and a webhook leaves through an outbox written in the same transaction. When the provider's answer is missing, reconciliation asks what happened instead of charging again.

The failure you are designing against is a double charge. The call to the card provider timed out. You do not know whether the money moved. A retry that simply calls again will charge a second time if the first call actually worked, and a retry that gives up will leave a charge the customer sees on a statement and your books never record. Both of those are the same bug: treating an unknown as a no.

Stripe’s published API takes an idempotency key the client generates, stores the key with the outcome, and returns that outcome on a retry. The published guidance keeps keys on the order of 24 hours, not as a permanent archive. Brandur Leach’s writeup of the pattern adds the parts people skip: a fingerprint of the parameters so the same key with a different request is an error, a lock so two concurrent retries do not both run, and recovery points around the call you cannot roll back. The writeup of that pattern is worth reading beside this design. What follows puts a ledger and an outbox on that skeleton. It does not invent their traffic.

Requirements

The user is a customer paying a merchant through your platform. You are in the middle. A card provider is outside.

It must:

  • Take money for one purchase at most once, including when the client retries and when your process crashes.
  • Record why any balance changed, as entries you can add up, and refuse a charge that would drive a spendable account negative.
  • Tell the merchant the payment succeeded, and still have a record of that fact if the notify call fails.
  • End in a state you can explain when the provider times out: succeeded, failed, or still pending. Pending is a real state.

Non-goals:

  • Being a bank. Settlement law, reserves, and scheme rules are constraints you acknowledge, not a design you fake.
  • Storing raw card numbers. You store a token the provider gave you. Secrets stay out of logs.
  • Foreign exchange, tax, and marketplace splits beyond a single transfer from a buyer side to a merchant side. Fees can be a third entry in the same transaction when you are ready. They are not the hard part today.
  • A global multi-region ledger. One database is the right answer at the rate below. Say so.

Latency assumption: the customer waits on this call. Budget a couple of seconds because the provider is slow, and do not add a chain of internal services in front of that wait. The provider timeout is 2 seconds. Assumption. Your own extra work is a couple of local transactions around it.

Estimation

Assumptions:

  • 2 million payments per day. An interview assumption, not a company’s volume.
  • Peak is 5 times the average, the top of the usual 2x to 5x band, because a sale is spiky.
  • The provider call is 300 ms at p50 and you give up at 2 seconds.
  • One payment stores about 1 KB across the payment row, two ledger entries, the idempotency row, and the outbox row. The ledger is kept. Idempotency keys are kept 7 days, which is longer than the 24-hour published guidance, so a slow client still replays inside a week.
  • A webhook body is about 1 KB.

A day is 86,400 seconds. A year of seconds is about 3e7, roughly 347 days, so a 365-day year is the number used below and the shortcut year is a bit short.

average rate = 2e6 / 86,400 = 23 payments per second
shortcut / 1e5 = 20 per second
peak, assumption 5x = 116 per second

in flight, ordinary = 23 * 0.3 s = about 7 provider calls
peak ordinary       = 116 * 0.3 s = about 35
peak, all stuck at the 2 s timeout = 116 * 2 = about 230 in flight

storage per day = 2e6 * 1 KB = 2 GB
365 days        = about 730 GB of rows
times 3 replicas = about 2.2 TB

webhook bandwidth at peak = 116 * 1 KB = about 116 KB/s

Twenty-three payments a second is not a scale problem. Little’s law is the useful line: concurrency is rate times time. The incident is the timeout. If every call hangs for 2 seconds and you also retry each one blindly, you double the provider load at the moment the provider is already sick. The design refuses that retry. Bandwidth is noise. A million payments a day would be about 12 per second. You are at twice that average. You will still get the system wrong if the crash window is wrong.

One database holds 2 TB of replicated ledger without drama. Transactions across two account rows are available because you still have one database. Sharding the ledger on day one is how you invent a distributed transaction for a rate a single primary can do.

High-level design

flowchart LR
  payer[Payer]
  api[Payment service]
  keys[Idempotency key]
  ledger[Ledger entries]
  outbox[Outbox]
  provider[Card provider]
  publisher[Outbox publisher]
  merchant[Merchant]
  recon[Reconciler]
  payer --> api
  api --> keys
  api --> provider
  api --> ledger
  ledger --> outbox
  outbox --> publisher
  publisher --> merchant
  recon --> provider
  recon --> ledger

The client sends the key, the amount, the currency, the merchant, and a cart id. The service locks that key, calls the provider only if this attempt has not reached the provider before, and writes the ledger and the outbox in one local transaction after a known success. The publisher reads the outbox and calls the merchant. The reconciler scans pending payments whose provider call is unresolved.

The provider is not a participant in your database transaction. You cannot roll it back, and you should not pretend a two-phase commit with a card network is available. Recovery points are how you live with that.

Deep dive

The key, the lock, and the fingerprint

The client generates the key, a UUID is the usual choice, and writes it down before the first request. If the process dies before the request, nothing was charged, and the retry uses the same key. If the client generates a new key per click, your server cannot see that the two calls are one purchase. Persist first.

The server’s first local transaction inserts the key if absent, with a fingerprint of the parameters: amount, currency, merchant, cart id. Same key, same fingerprint, and you already have an outcome: return it. Same key, different fingerprint: reject. Do not charge 40 under a key that already charged 20. Two requests that both see the key as absent are the race. The insert is the lock. The loser waits on the winner’s row. If the winner is still in progress after 2 seconds, the loser returns “retry this same key” and does not start a provider call. Waiting forever holds a thread. Starting a second call is the double charge.

A second fence, because clients are imperfect: a unique constraint on merchant plus cart id for any payment that is pending or succeeded. A fresh UUID for the same cart hits that constraint and returns the existing payment. The idempotency key stops transport retries. The cart id stops a new key for the same purchase. You want both. Idempotency as a concept is the key. The cart constraint is the business rule next to it.

Keys live 7 days in this design, then they are deleted. A retry after that is a new charge. Tell the client. Do not keep every key forever, and do not use the 24-hour published number as if a longer window were free of a choice. Seven days is an assumption sized to cover a weekend of reconciliation, not a law.

Entries, not a balance you overwrite

The source of truth is a set of ledger entries. Each entry names an account, a direction, an amount, and the payment id. A payment of 40 from buyer to merchant is two entries in one transaction: buyer minus 40, merchant plus 40. The payment’s entries sum to zero. Money did not appear. If the transaction rolls back, neither entry remains. A cached balance column, updated in that same transaction, is a convenience for reads. You can rebuild it by summing entries. If the column is all you have, a bug in an update has nothing to be checked against.

The lost update is the column’s bug. Start at 100. Two charges of 40. Both read 100, both write 60. One charge vanished and the column looks calm. Entries do not have that bug: both inserts of minus 40 commit and the sum is 20, which is what happened.

The invariant bug is different. Start at 50. Two charges of 40. Entries without a check both insert, and the sum is minus 30. You did not lose an update. You broke “a spendable account does not go below zero.” Inside the transaction, lock the account row, sum the entries, and insert only if the result stays non-negative. The second transaction waits, sees 10, and rejects. The cached column moves with the insert. A nightly job sums every account and compares the column. A mismatch is an incident, not a quiet drift.

At 23 per second the row lock is cheap. It serializes payments for one account, which is what the invariant requires. It does not serialize the whole ledger.

Do this write only after you know the provider succeeded. If you ledger first and the provider then fails, you have given the merchant money the customer did not pay, and you are into a compensation. Recovery points avoid that order.

Recovery points and the timeout

Separate what a local transaction can undo from the call you cannot undo.

1. Client has stored the key. No call yet. Crash: retry the same key.
2. Local transaction: key row, payment pending, fingerprint.
   No ledger entries. Commit.
3. Call the provider, passing your payment id.
4. Known success. Local transaction: two ledger entries,
   payment succeeded, key outcome stored, outbox row inserted.
   Commit. Then respond to the client.
5. Known failure. Local transaction: payment failed, key outcome stored.
   No ledger entries. Commit. Respond.
6. Timeout or a dropped connection. Leave pending.
   Do not ledger. Do not call the provider again yet.

Crash after step 4’s commit and before the response: the client retries, the key has an outcome, you return it. No second charge.

Crash after the provider succeeded and before step 4: the retry or the reconciler sees pending, asks the provider about that payment id, hears success, and runs step 4. It does not call the charge endpoint again. The provider result is the recovery point. You recorded that you were about to call, you called, you record that you finished. A retry continues from the point you reached.

Timeout, step 6, is the case you do not get to treat as a failure. The reconciler picks up pending rows older than the timeout. It asks the provider by the payment id you sent. Confirmed success runs step 4. Confirmed absence marks the payment failed. Provider unreachable leaves the row pending, backs off, and alerts if pending crosses an hour. Assumption on the hour. It never mints a new charge to “clean up.” A circuit breaker around the provider keeps a dead dependency from holding every thread while this queue of unknowns drains. Open the breaker, fail new checkouts as “try later,” and let reconciliation finish the ones already in flight.

Respond to the customer only after step 4 or step 5 has committed. If you say success first and then crash, the customer saw a receipt and your books have a hole. Reconciliation can fill the hole, and you should still not claim success early.

The outbox

Step 4 inserts an outbox row in the same transaction as the ledger. A publisher reads the outbox and sends the merchant webhook. If you commit the payment and then publish, a crash in between loses the notify. If you publish and then roll back the payment, the merchant hears about a charge that does not exist. That dual-write hole is why the outbox sits inside the commit. The publisher is at-least-once. The merchant dedupes on payment id. A dead publisher means webhooks lag and the payment row is already the truth. The merchant can read the payment by id. The webhook is a hint that the row changed.

Do not put the provider call inside that transaction. Holding a database transaction open across a 300 ms external call, or a 2 second timeout, is how you run out of connections at a rate of 23 per second the moment the provider slows down. The recovery point is two short transactions and a call between them.

Tradeoffs

Choice What you gain What you spend
Client-generated key, stored with the outcome A retry returns the first result and does not charge again The client must persist the key, and you must store keys for the replay window
New key on every click Simple client code Double charge, and the server cannot see it
Ledger entries plus a locked check against the sum You can rebuild a balance and you cannot lose an update or go negative quietly A lock per account, and a nightly comparison you have to actually run
Balance column as the only record A fast read Lost updates, and no way to explain a number
Ledger only after a known provider success You do not pay the merchant for a failed card A timeout stays pending until reconciliation
Ledger before the provider call The books move quickly You compensate when the provider says no, and compensations fail too
Outbox row in the success transaction The notify cannot commit without the payment, or the reverse A publisher to operate, and an at-least-once webhook
One database for both accounts One transaction, entries sum to zero, no saga A later shard forces a clearing account and a second step
Blind retry on provider timeout The happy path looks shorter Double charge when the first call had succeeded

Failure modes

  • Provider timeout, client retries, server calls the provider again. Symptom: two charges on one statement, one payment id in your books or, worse, two. The key, the pending state, and the lookup by payment id are the fix. A retry storm during a provider incident multiplies this. The breaker and the “do not call again while pending” rule are what stop it.
  • Client mints a new key because the first response was lost. Symptom: the key logic looks correct in tests and production still double-charges. The cart-id constraint is the backstop. The real fix is the client store.
  • Same key, different amount, and you run the new amount. Symptom: a bug in the client replays a key and changes the price. Reject on fingerprint mismatch.
  • Two workers both see the key as new. Symptom: two provider calls, one key. The insert has to be the lock, not a check-then-act.
  • Success response sent before the ledger commits, then a crash. Symptom: a receipt with no entries. Reconciliation fills in, and you still told the user a fact you had not made durable. Commit first.
  • Outbox publisher is down. Symptom: merchants complain that webhooks stopped, balances are correct, support can read the payment. Lag, not data loss. If the webhook was the only record, you built it backwards.
  • Balance column updated without entries. Symptom: the nightly sum does not match, and you cannot see which payment did it. The column is a cache. The entries are the record.
  • Hot merchant, one account row, a sale. Symptom: that row’s lock waits, other merchants are fine. That is the invariant working. Do not drop the lock to make the sale faster and go negative.
  • Reconciler marks pending payments failed because the provider status call failed. Symptom: you later find charges you called failures, and a naive retry charges again. Unreachable means stay pending.

Durability of the ledger commit is the bar for success. Consistency of the two entries is the local transaction: both or neither. The provider and the ledger are not one atomic system. They are two systems and a reconciler. Say that plainly. Anyone who promises exactly-once across your database and the card network is selling a checkbox the network did not sign.

In the interview

First five minutes: the double charge, the key the client stores first, the ledger of entries, the outbox in the same commit as success, and reconciliation on timeout. Give the rate, about 20 a second, and say the hard part is the crash window, not the QPS. Mention that one database is enough and is why the two entries can share a transaction.

Skip card-network internals, tax tables, and a tour of fraud models. Name fraud as a check you can put before step 3. Do not design it unless they ask.

The question that follows is “the provider timed out.” Walk steps 2, 3, and 6, and say you ask the provider about the payment id you already sent. If they ask about a lost update on the balance, show 100 minus 40 twice becoming 60. If they ask about going negative, show the lock on a start balance of 50.

Check yourself

The provider call times out and the client retries with the same key. What do you refuse to do, and what do you do instead?

You refuse to send a second charge while the first result is unknown. The payment stays pending. You ask the provider whether that payment id exists. A confirmed success writes the ledger once. A confirmed miss marks the payment failed. Silence leaves it pending.

Two charges of 40 read a balance column of 100 and both write 60. How do ledger entries behave on the same race?

Both minus-40 entries exist and the account sums to 20. The column lost an update because the second write replaced the first. Entries accumulate. They still need a locked check if the account is not allowed to go negative, which is a different bug from the lost update.

Why is the webhook row inserted in the same transaction as the ledger entries?

A commit followed by a publish can crash in the gap, and a publish followed by a rollback notifies the merchant about a payment that rolled back. One transaction makes the entry and the outbox row appear together. The publisher can then send at least once, and the merchant dedupes on payment id.

The client generates a fresh idempotency key for the retry. Where does your key logic stop helping, and what second constraint still catches it?

The server sees a new key and treats it as a new purchase. That is correct behavior for a new key and a disaster for a sloppy client. A unique constraint on the merchant and the cart id, for payments that are pending or succeeded, rejects the second attempt and points at the payment you already have.

Based on: Stripe idempotency keys; Brandur Leach, idempotency recovery points; Designing Data-Intensive Applications, Kleppmann and Riccomini.