Courses System design · Part 6 · Case study 5
Case Study: A Payment Flow
In this design, speed is not the most important thing; correctness is. A user charged twice, or a shop that took the money but never recorded the order, is a problem no cache or load balancer can solve. This case study shows how a few simple ideas reduce those risks.
1. Requirements
Functional:
- A user pays for an order with a bank card through an outside payment gateway.
- The shop knows which orders are paid, so it can ship them.
- Refunds when an order is cancelled.
Non-functional:
- No order is ever charged twice.
- No money is left without an owner: every amount the bank took is linked to an order.
- Every change can be traced (who, when, why).
2. Numbers
- 500,000 orders a day: about 6 payments a second, maybe 100 during a sale.
- These numbers are small for a relational database. So we use a relational database with transactions: here correctness matters more than scale (SQL or NoSQL lesson).
3. API and flow
Bank gateways usually work like this:
- The payment service gets a payment token from the gateway and sends the user to the bank’s page.
- The user enters the card and PIN on the bank’s page.
- The bank sends the user back to our return URL, with the result.
- We verify with the gateway that the payment really happened. Only after this step is the payment final.
POST /payments {orderId, idempotencyKey} → {redirectUrl}
GET /payments/callback?token=... (return from the bank)
POST /refunds {paymentId, amount, idempotencyKey}
4. Data model
Payments, with a status column:
created → waiting for bank → confirmed
↘ failed
↘ unknown (no answer)
A status may only change in the allowed directions, and every change is also written to a history table.
A double-entry ledger: every movement of money has two rows that add up to zero: “500,000 less in the customer account” and “500,000 more in the shop account”. Rows are never edited or deleted; a mistake is fixed with a correcting row. This is the log idea again: a full, append-only history. The sum of all rows must always be zero; if it is not, something went wrong.
5. High-level picture
- The order service calls the payment service with
orderIdand an idempotency key. - In one transaction, the payment service stores the key (with a unique constraint) and creates the payment with status “created”. Then it gets a token from the gateway.
- After the return and the verify step, in one transaction: it sets the status to “confirmed” and writes the two ledger rows.
- An “order X is paid” event goes onto a queue, so the order service and the notification system can do their part.
6. Deep dive: where things go wrong
The user presses the button twice
Both requests carry the same idempotency key (the client made it once for this order). The second one hits the unique constraint and gets back the first payment. One payment, not two.
The gateway does not answer
The verify request was sent, but no answer came. Was the money taken? We do not know. So the status is “unknown”, not “failed”. If we called it failed and the user paid again, they might pay twice.
A worker later asks the gateway about unknown payments (“what is the status of token X?”), with doubling waits and jitter. If the gateway is fully down, a circuit breaker stops the pointless calls, and the payment page shows “the gateway is temporarily unavailable” instead of making the user wait.
The user closes the browser after paying
The money was taken, but the return to our site never happened. The payment stays “waiting for bank”. The same worker asks the gateway about payments that have stayed in this state for more than a few minutes, and confirms them.
The server crashes in the middle
Because the status change and the ledger rows are written in one transaction, either both happened or neither did. The database guarantees this with its write-ahead log.
Reconciliation
Every night the bank provides a list of all the day’s transactions. A nightly job compares it with our ledger:
- In the bank’s list but not in our ledger: we took money for an order we never recorded. It must be checked, and recorded or refunded.
- In our ledger but not in the bank’s list: we treated a payment as confirmed that never happened.
Reconciliation is the last safety net: any error that slipped through all the layers above is found here.
7. Trade-offs
- Correctness versus speed: every step waits for a confirmation, and a payment takes a few seconds. Here we pay that price gladly.
- Synchronous versus asynchronous: the payment itself is synchronous (the user waits for the result), but the follow-up work (notifications, stock, accounting) is asynchronous, through a queue.
- Storing cards: keeping card numbers brings heavy security and legal duties. It is better if the card is only entered on the bank’s page and we never see it.
Labs used
Write-ahead log · Retries · Circuit breaker · Message queue · Replication