GOAT EngineerPreparing your learning space…

System Design · Interview breakdown · Free article

Design a Payment System (Stripe, PayPal)

Charge a buyer once when she taps twice and the reply is lost, capture 200 million holds in a night that survives a crash, apply events that arrive late and out of order, account for every cent, and find the one charge nobody made. Built one step at a time, with experiments you can run.

A payment system takes money from a buyer’s card for an order, tells the shop whether it arrived, and keeps an exact record of who is owed what, usually by calling a processor such as Stripe. The checkout page makes an idempotency key when it loads, and the API claims that key with a unique insert before any work, so a second tap gets the first answer. Each order may have only one attempt that has not failed. The API saves the attempt before calling the processor, sends the attempt’s ID as the processor’s key, and keeps no transaction open during the call. A lost reply leaves the attempt unknown, and a sweeper looks it up instead of charging again. A nightly batch of workers captures the day’s holds in leased chunks under one rate limit. Webhook events are verified, stored and answered at once, then applied only as allowed moves between states. Every movement of money is one balanced ledger posting with a unique effect key, and a reconciler matches every line of the processor’s payout report against the ledger.

Difficulty: Hard. Reported in interviews at OpenAI, Checkout.com, Adyen. Also asked as Design Stripe, Design a payment gateway, Design PayPal, Design a payment system with daily batch capture.

Practise one part of it on a canvas that tests your design: Charge a Card Exactly Once.

How do you design a payment system?

A payment system takes money from a buyer’s card for an order, tells the shop whether the money came, and keeps an exact record of who is owed what. It rarely talks to the card networks itself. It calls a payment processor, such as Stripe or Adyen, which asks the buyer’s bank to approve the charge and later moves the money. Charging a card once looks like one API call. The work is making sure it happens exactly once. Replies get lost and servers die mid-call. The money arrives days later, less fees, in one lump.

  1. Pay: Pay $120. Anya taps Pay twice while the spinner spins. She must be charged once.
  2. Authorized: Hold: $120. The processor places a hold, and its reply can be lost on the way back.
  3. Captured: Captured 02:14. Tonight, 200 million holds must become charges before any of them expires.
  4. Confirmed: Refund $30. Events about the payment arrive late, twice, or in the wrong order.
  5. Paid out: Deposit $193.10. The bank gets one net sum, and every cent of it must be explained.
One payment, start to finish. The system does this 200 million times a day.

Picture Anya buying a lamp and a pack of bulbs from Hugo’s ceramics shop, on an online marketplace where thousands of small shops sell. The order comes to $120. She taps Pay on Monday at noon, and a few seconds later the page says the order is placed. Hugo’s share reaches his bank account at the end of the week.

Interviewers like this problem because the traffic is not the hard part. The hard part is that two systems, ours and the processor’s, must agree about money, and they share no database. Every step crosses a network that can lose the reply. A candidate who treats a timeout as a failure, or a webhook as the whole truth, charges someone twice.

Here is the design in brief. The checkout page sends Pay with a key it made when the page loaded, and the Payment API inserts that key before doing anything else. The API saves a payment attempt in PostgreSQL. Then it asks the processor to authorize $120, sending the attempt’s ID as the processor’s idempotency key. The processor puts a hold on Anya’s card. A nightly batch of workers captures the day’s holds, which turns them into charges. The processor reports each change as an event to a webhook intake, which stores it before answering. Workers apply each event only where it follows from the payment’s current state, and post each movement of money once to a double-entry ledger. A reconciler matches the processor’s daily report against the ledger, line by line.

The rest of this page is about the moments that design has to survive.

The first is a lost reply. Anya taps Pay at 12:00:00. The processor places the hold at 12:00:01.8. At 12:00:01.9 a deploy kills the server that was waiting for the answer. Anya sees an error, reloads the page and pays again. If our side decides the first attempt failed, it asks for a second hold. Now $240 of Anya’s credit is held for a $120 order, and nothing on our side knows the first hold exists.

The second is the morning after. The bank receives $193.10 from the processor. Our ledger expected $212.50. Inside those $19.40 there is a charge that will be paid on Friday, and one charge nobody on our side made. Nothing in the system looks broken.

What is the interviewer testing?

Most candidates reach a working answer quickly: an API, a payments table, a call to a processor such as Stripe, and a webhook that marks the payment paid. That answer is right, and a mid-level answer often stops there.

The interviewer then pushes on the gaps between systems. The buyer taps twice. The processor’s reply never arrives. The nightly capture dies halfway. An event comes twice, or before the one it follows. Someone asks where a cent went. A senior answer uses idempotency keys at both ends, treats a lost reply as unknown, applies events through a state machine and keeps a double-entry ledger. A staff answer also builds the capture batch to resume without a person, posts each movement of money once by an effect key, and reconciles every line against the processor’s report.

Spend most of the deep-dive time on the lost reply and on the ledger. The capture batch is the usual follow-up when the interviewer frames the problem as authorize now, charge in a daily batch. How to run a round has the time plan for a 45 to 60 minute round and a 15-minute screen.

What should you ask before drawing anything?

Four questions change the design. Ask them in the first two minutes. If the interviewer leaves one open, say your assumption out loud.

Are we the processor, or do we call one?
Assume we call one. We are the payment system of an online marketplace, and a processor such as Stripe talks to the card networks for us. If the interviewer wants you to be the processor, the same patterns face the other way, and the section on other names says what changes.
When does the money move?
Assume the card is authorized at checkout, which puts a hold on it, and captured in a nightly batch once the order is ready to ship. A shop that cannot ship releases the hold instead of refunding a charge.
How many payments, and how fast?
Assume 200 million payments a day, with an evening peak of 10,000 a second. Checkout should answer within about 2 seconds, most of which is the processor’s own time.
Cards only, in one currency?
Assume cards, in US dollars, stored as whole cents. Wallets, bank transfers and currency conversion are out of scope, and the answer says where they would plug in.

Functional requirements

On the board: Functional requirements
1. Charge a buyer once for an order
   authorize at checkout, capture nightly
2. Show each payment’s state to buyer, shop
3. Refund all or part of a payment
4. Ledger: who is owed what, reconciled
out: card networks, fraud, FX, subscriptions

Say it, don’t write it: Moving money is one call. The requirements are really about never doing it twice, and always knowing where it is.

Three groups use the system. Buyers pay and ask for refunds. Shops, like Hugo’s, see which orders are paid and receive their share each week. The marketplace’s finance team needs to know, to the cent, where every dollar is.

  1. Charge a buyer once for an order: authorize the card at checkout, and capture the money in a nightly batch once the order is ready to ship.
  2. Show each payment’s state to the buyer and the shop: processing, authorized, captured, partly refunded, refunded or declined.
  3. Refund all or part of a captured payment.
  4. Keep a ledger of who is owed what, and reconcile it every day against the processor’s reports.

Out of scope

  • Connecting to card networks and banks, which the processor does
  • Fraud scoring, beyond a note on where the check sits
  • Currency conversion, and payment methods other than cards
  • Subscriptions and saved cards
  • How shops are verified and signed up

Non-functional requirements

On the board: Non-functional requirements
• 200M payments a day, 10k a second at peak
• Never charge twice, never lose a charge
• Checkout answers in about 2 s
• Every cent explained; records never edited
• Card numbers never touch our servers

Say it, don’t write it: At 10,000 a second the traffic matters, but the promise that decides the design is exactly once.

  • About 200 million payments a day, and 10,000 a second at the evening peak.
  • A buyer is never charged twice for one order, and no charge the processor made is ever missing from our records.
  • Checkout answers within about 2 seconds, most of which is the processor’s own time.
  • Every cent can be explained, and no financial record is edited after it is written.
  • Card numbers never reach our servers or our logs.

Two numbers are worth working out now, because each decides a piece of the design. The first is the write rate. 200 million payments a day is 200,000,000 ÷ 86,400, about 2,315 a second on average, and the peak is 10,000. Each payment writes about ten rows: its key, its attempt, two changes of state, its events and its journal entries. At the peak that is 100,000 row writes a second. That is more than we want one database primary to carry. So the data is split across several PostgreSQL primaries by order ID, and everything about one order lives on the same one. An order is the unit whose rules must be checked together, so it is the unit that stays together.

The second number is how many calls are waiting on the processor at once. An authorization takes about 2 seconds. At 10,000 a second, 10,000 × 2 = 20,000 calls are in flight at any moment. If a slow processor makes every call wait out a 10-second timeout, that becomes 10,000 × 10 = 100,000. A design that held a database transaction open during the call would need that many open transactions. PostgreSQL allows 100 connections by default. So no transaction stays open across a call to the processor, and the lost-reply deep dive builds the design around that rule.

The other numbers appear in the deep dive that needs them. They are illustrative interview targets, not measurements of any real company.

Core entities

On the board: Core entities
Key(buyer, key, request hash, reply)
Attempt(order, cents, state, processor ref)
Event(event id, type, raw body, applied)
Entry(posting, account, ±cents), sum = 0
Payout line(ref, gross, fee, net)

Say it, don’t write it: An attempt exists before anything is sent, and a ledger posting is keyed by the movement of money it records.

Follow Anya’s $120 through the records. When her checkout page loads, it makes an idempotency key, k1, for this attempt to pay. Pay sends k1 with the order ID. The API inserts k1 into the key table with a hash of the request. Then it saves a payment attempt, P1, with the order, the amount in cents, 12,000, and the state sending. P1’s ID is the key it sends to the processor. The processor answers with its own reference for the charge, ch_A, and P1 records it.

The processor’s events land in the event table under their own IDs. When the capture is confirmed, the ledger records a posting: four entries that say where the $120 went, whose amounts sum to 0. Each day the processor’s payout report arrives, one line per charge, refund and fee, and each line is matched to a posting.

RecordWhat it holdsWhy it is separate
Idempotency keyThe caller’s key, a hash of the request, its state and the saved replyA repeated request gets the first answer instead of doing the work again
Payment attemptOrder, amount in cents, currency, state, the processor’s referenceWritten before the processor is called, so a crash never leaves a call we have no row for
EventThe processor’s event ID, its type, the raw body, and whether it has been appliedStored before we answer the processor, so a crash never loses one
Ledger posting and entriesAn effect key such as ch_A:capture, and entries of account and signed centsThe only record of money: never edited, and each effect posted once
Payout lineThe processor’s reference, gross, fee, net, and the payout it belongs toWhat reconciliation matches against the ledger

Amounts are whole cents in an integer column, with the currency beside them, so $120 is 12,000. Floating point cannot hold 0.1 exactly, and a sum of many such values drifts. Some currencies have no cents at all, the Japanese yen among them, so the number of decimal places comes from the currency, never from the code.

The one distinction that matters: an attempt records what we asked for, and a posting records what we know happened. P1 can be sending, authorized, unknown or declined. A posting exists only once money has moved.

API

On the board: API
POST /payments   Idempotency-Key: k1
  {order_id, card_token} → {id, state}
GET /payments/{id} → state
POST /payments/{id}/refunds  Idempotency-Key
POST /webhooks/processor   (signed)

Say it, don’t write it: Every call that moves money carries a key the caller made, so a retry can never become a second payment.

The buyer’s page calls three endpoints, and the processor calls one.

CallReturnsWhy it looks like this
POST /payments with the header Idempotency-Key: k1 and {"order_id": "o_981", "card_token": "tok_…"}{"id": "P1", "state": "authorized"}, or "processing" while the answer is unknownThe key makes a second tap safe; the amount comes from the order service
GET /payments/P1The state, and what the buyer should seeHow the page learns the answer after a lost reply
POST /payments/P1/refunds with its own key and {"amount": 3000}{"id": "R1", "state": "pending"}A refund moves money too, so it has its own key
POST /webhooks/processor, called by the processor200 once the event is storedThe signature is checked on the raw body, and the work happens after the answer

Three fields are there on purpose. The key comes from the caller, because only the caller knows that two requests are the same attempt. The amount does not come from the page, because a page can be edited, so the API reads it from the order. And the card arrives as a token. The processor’s own payment form, loaded in a frame on our page, collects the card number and hands the page a token that only the processor can use. So the number never reaches our servers.

Step 1: authorize the payment

Anya taps Pay. The Payment API inserts k1, reads the order’s amount, and saves attempt P1 in the sending state, in one short transaction. Then, with no transaction open, it asks the processor to authorize 12,000 cents, sending P1’s ID as the processor’s idempotency key. The processor asks Anya’s bank, which puts a hold of $120 on her card. The API saves the answer, authorized, and the page shows the order as placed.

An authorization is a promise to pay. Nothing has moved yet. $120 of Anya’s available credit is set aside until the money is captured or the hold is released.

The interactive version of this example is available when JavaScript loads.

So far only the page that asked hears the answer. The next step handles news that arrives later.

Step 2: learn what happened

The processor does more than answer the request. It also sends events about each payment, such as a capture succeeding or a refund failing, to a webhook intake. The intake checks each event’s signature, stores it in the payments database and answers 200. Workers read the stored events and move each payment to its new state. Anya’s page and Hugo’s dashboard ask the API for the current state.

The interactive version of this example is available when JavaScript loads.

No money has moved yet. The next step captures it and records who is owed what.

Step 3: capture, refund and record the money

Hugo marks the order ready to ship. That night, a batch of workers captures the day’s authorized payments, which turns each hold into a charge. When a capture is confirmed, the workers post it to the ledger: where the $120 went, entry by entry. In the same transaction they write a row to an outbox table. A relay sends that row to the order service, which marks the order paid. A message in an outbox is sent “if and only if the database transaction commits” (microservices.io). So the order service never hears of a payment the ledger does not have.

On Tuesday morning Hugo finds he has no bulbs left. Support calls the refund endpoint for $30. The API asks the processor to refund it with the refund’s own key, and the refund’s event posts to the ledger the same way.

The interactive version of this example is available when JavaScript loads.

With steady traffic this already works. The deep dives take it through six moments: a second tap, a lost reply, a capture batch that dies, events in the wrong order, a cent nobody can explain, and a deposit that does not match.

Anya taps Pay twice. How do you charge her once?

At 12:00:00 Anya taps Pay. The spinner spins. At 12:00:01.2 she taps again, because nothing seemed to happen. The two requests leave her phone 1.2 seconds apart. The load balancer sends them to two different servers, A and B.

The first design treats every request as new. Server A creates attempt P1 and asks the processor to authorize $120 with key P1. Server B creates attempt P2 and asks with key P2. The processor sees two different keys, so it sees two purchases. Anya’s card gets two holds of $120. Both attempts are authorized in our records, so tonight’s capture takes $240. The processor’s idempotency keys cannot help here. They protect against one request sent twice, and these are two requests that happen to want the same thing.

The servers cannot tell these two apart. Only the phone knows that the second tap is the same attempt as the first, so the phone has to say so. When the checkout page loads, it makes a random key, k1, and sends it with every Pay for this attempt. A second tap, or a retry after a dropped connection, carries the same k1.

The second design uses the key like this: look up k1, and if it is not there, do the work and then save k1 with the reply. Walk the two taps through it. Server A looks up k1 at 12:00:00.02 and finds nothing. It calls the processor, which takes about 2 seconds. Server B looks up k1 at 12:00:01.22. Server A has not saved it yet, because it saves when the processor answers, at about 12:00:02. So B finds nothing too, and sends its own authorization. Two holds again. The check and the save are two separate steps, and the second tap fell between them.

The fix is to make claiming the key the first thing a server does, in one statement the database can refuse. The key table has a unique index on the buyer’s account and the key, so two buyers can never collide. Server A inserts k1 with the state in progress, before it calls anyone. Server B tries the same insert 1.2 seconds later, and the unique index refuses it. So B reads the existing row instead. The row is in progress, so B answers 409, which means another request with this key is still being worked on. B calls nobody. The phone waits a moment and asks again. By then A has saved the processor’s reply on k1’s row, so the second answer is exactly the first: authorized, one hold.

The fix raises a new question. What if the second request carries k1 with a different body, say a different card? Returning the first reply would answer a question nobody asked. So the key row stores a hash of the request, and a mismatch is refused with a 422. Stripe does the same: “The idempotency layer compares incoming parameters to those of the original request and errors if they’re not the same” (Stripe).

Then Anya’s page reloads halfway through checkout. The new page makes a new key, k2, and she taps Pay. k2 is not in the table, so the key cannot help. The order can. The attempt table has a second unique rule: each order may have only one attempt that has not failed. An attempt stops counting only when it has definitely failed: declined, released or expired. Every other state counts, from sending to refunded. The insert of a second such attempt for Anya’s order fails, and the API returns the first attempt’s state instead. The key catches a repeated request. The order rule catches a repeated purchase.

The last question is what happens to k1’s row if server A dies while holding it. The row says in progress, and it would say so forever. So a claim has a lease, a time after which another server may take the key over. Airbnb’s payments team built this pattern into a library called Orpheus. Its rule for the lease is plain: “A good rule of thumb is to have a higher lease expiration than the RPC timeout” (Airbnb). The RPC timeout is how long a server waits on its call to the processor. A shorter lease would let a second server take over while A is still waiting for its answer, and both would act. A server that takes over must not simply call the processor again, though. Whether A’s call reached the processor is exactly the question the next deep dive answers.

Keys are kept for at least a day, because a phone that lost its signal may retry hours later. Stripe may remove its own keys once they are “at least 24 hours old”.

The experiment plays the two taps three ways. The tabs are no key, a key that is checked and saved later, and a key inserted first.

The interactive version of this example is available when JavaScript loads.

The gap: Only the phone knows that two requests are the same attempt, and two servers can handle them at the same moment.

Option 1: Every request is new

Each Pay creates an attempt and calls the processor.

Works when: Never, for money.

Breaks when: Two taps become two holds, because the processor sees two different keys.

Option 2: Check the key, save it with the reply

Look up the caller’s key; if it is missing, do the work and save the key afterwards.

Works when: Requests that are never repeated within a few seconds.

Breaks when: Both requests find the key missing in the 2 seconds before either saves it.

Option 3: Insert the key first, and one attempt per order (start here)

A unique insert claims the key before any work; a repeat gets 409 or the saved reply; each order has one attempt that has not failed.

Works when: Always.

Watch for: A claim held by a dead server needs a lease, and whoever takes it over must look the attempt up, not call again.

In the interview: Open with option 3, and show why option 2 fails by timing the two taps out loud: the second lands in the 2 seconds before the first saves. Mention the order rule when the interviewer asks about a reloaded page, and the lease when they ask what happens if a server dies.

Say this: The checkout page makes an idempotency key when it loads and sends it with every retry. The server claims the key with a unique insert before doing anything, so a second request waits or gets the saved reply. The same key with a different body is refused. Each order may have only one attempt that has not failed, which catches a new key for the same purchase. The claim has a lease longer than the processor timeout.

The processor’s reply never comes back. Did Anya pay?

Anya taps Pay once, at 12:00:00. Server A inserts k1, saves P1 as sending, and asks the processor to authorize $120 with key P1. At 12:00:01.8 the processor places the hold. At 12:00:01.9, before A reads the reply, a deploy kills server A. The load balancer answers Anya’s phone with an error, a 502. She reloads checkout, which makes a new key, k2, and at 12:00:06 she taps Pay again. Server B takes the request. The new key cannot help, so everything depends on what the records say about P1.

Start with the order of the two writes, because one order loses track of the money outright. Suppose server A calls first and saves after. The only record that P1 was sent was in A’s memory, and A is gone. When Anya pays again, nothing on our side records that P1 was sent, so the order rule sees no attempt and B starts P2. A second hold lands. P1’s hold ties up $120 of Anya’s credit for up to 7 days, until it expires, and nothing on our side knows it exists. Saving first means every call the processor ever received has a row on our side.

Now suppose P1 was saved first, and B reads it. P1 says sending, not authorized, so the simple conclusion is that it failed. B marks P1 failed. In this design failed ends an attempt, so the order rule no longer counts it, and B starts P2. Two holds again. P1 had not failed. Nobody knew what had happened to it.

A timeout, a dropped connection and a dead server all leave the same situation. The request may or may not have reached the processor. The answer is somewhere we cannot see. Stripe’s documentation says the same of its own server errors: “You should treat the result of a 500 request as indeterminate” (Stripe).

So an attempt has a state for this: unknown. A server that times out or gets a 5xx marks its attempt unknown. A server that dies marks nothing, so an attempt still sending long after any call could have lasted counts as unknown too. Three kinds of answer end the state. The processor approved or declined the payment, and says so. Our request was malformed, a 400 that no retry will fix. That is our own bug, and it pages an engineer. Or somebody asked the processor what happened and got an answer. Airbnb’s engineers put the risk of mislabelling plainly: “double payments could occur if an exception was labeled ‘retryable’ when it actually should have been ‘non-retryable’”.

Replay the story with that state. At 12:00:06 server B finds that Anya’s order already has an attempt that has not failed: P1, still sending. The order rule refuses a new attempt. B returns P1 to the phone, and the page says it is checking with Anya’s bank. A sweeper runs every 10 seconds. It looks for attempts still sending or unknown after 30 seconds, well past the call’s 10-second timeout. At 12:00:40 it finds P1 and asks the processor what happened to it. The processor answers: held $120. P1 becomes authorized, the page shows the order placed, and Anya has one hold. The sweeper is also what takes over k1 once its lease runs out, and k1’s saved reply follows P1’s answer.

Asking needs a way to find the payment. Many processors split a payment into two calls. The first creates the payment object and returns its ID, which we save on the attempt. The second asks for the money. With that ID saved, the sweeper’s question is one direct read. If the reply to the create call is the one that is lost, nothing has moved yet, so that call can safely be sent again with its key. Resending the same request with the same key is not a reliable way to ask. It returns the saved result of the first request. Stripe saves a 500 as faithfully as a success: “Subsequent requests with the same key return the same result, including 500 errors.” The key also expires. Stripe may drop it after 24 hours and warns: “We generate a new request if a key is reused after the original is pruned.” So the sweeper asks rather than resends. An attempt still unknown after a day goes to a person, with the processor’s records as evidence.

The sweeper’s own retries back off, doubling the wait each time with some randomness added. A thousand stuck attempts then do not all ask again in the same second. Stripe’s engineers describe the same scheme: “Use techniques like exponential backoff and random jitter” (Stripe).

One rule shapes all of this: no database transaction stays open while the processor is called. The call happens between two short transactions, one that saves the attempt and one that records the answer. Holding one transaction across the call looks simpler, because the attempt and its answer would commit together. But at the peak, 10,000 calls start every second and each waits about 2 seconds, so 20,000 are in flight. A slow processor that makes every call wait out its timeout raises that to 100,000. Each would hold a connection. Airbnb learned this in production: network calls inside those transactions “can result in bad things like rapid connection pool exhaustion and performance degradation”.

The last temptation comes during an outage. The processor is failing, so why not send Anya’s payment to a second processor? For a new payment that can be right. For P1 it is wrong. P1 may have placed a hold at the first processor, and the second processor knows nothing of P1’s key. An unknown attempt is settled with the processor it was sent to, and nowhere else. The ticket booking breakdown walks the same lost reply against a seat hold that runs out while the answer is missing.

The interactive version of this example is available when JavaScript loads.

The experiment plays the kill three ways. The tabs are calling before saving, saving first but reading unpaid as failed, and saving first with an unknown state that the sweeper looks up.

The interactive version of this example is available when JavaScript loads.

The gap: A lost reply, a timeout and a dead server all leave the same question open: did the processor act?

Option 1: Call first, save the result

Ask the processor, then write the attempt with its answer.

Works when: Never, for money.

Breaks when: A server killed after the call leaves a hold we have no row for.

Option 2: Save first, and treat unpaid as failed

Write the attempt, call, and treat a missing answer as a failure.

Works when: Only where replies always arrive, which no network promises.

Breaks when: The retry starts a second attempt while the first may have succeeded: two holds.

Option 3: Save first, unknown until looked up (start here)

Write the attempt, call with no transaction open, and look up anything unknown by the processor’s payment ID.

Works when: Always.

Watch for: A lookup needs the processor’s ID saved first, and anything unknown for a day goes to a person.

In the interview: Open with option 3, and say the word unknown out loud: it is the answer the interviewer is listening for. Then give the rule about transactions with the in-flight arithmetic. If they ask about a processor outage, say that new payments may go elsewhere and unknown ones may not.

Say this: I save the attempt before calling, and I never hold a transaction across the call. A timeout or a 5xx means unknown, not failed. The attempt stays unknown, the order cannot start another, and a sweeper looks it up by the processor’s payment ID. Anything still unknown after a day goes to a person, because the processor may forget keys after about 24 hours.

The nightly capture dies at 02:40. What do you run again?

Anya’s $120 is still only a hold. The money moves when the hold is captured. The marketplace captures once a night, for every order that is ready to ship.

Why wait? Because an order that does not ship costs less to undo before the capture. If Hugo finds the lamp cracked, the hold is released and nobody paid anything. After a capture it would be a refund, and a refund does not give back the processor’s fee: “Stripe’s processing fees from the original transaction aren’t returned” (Stripe). A hold is cheap to cancel. A charge is not.

The wait has a limit. “Usually, an authorization for an online card payment is valid for 7 days,” Stripe says. “If the authorization expires before you capture the funds, the funds are released” (Stripe). A hold nobody captures within 7 days is a sale that pays nothing.

Work out the size of the night. On a busy day there are 200 million held payments to capture. Say the processor’s contract allows 5,000 capture calls a second. 200,000,000 ÷ 5,000 is 40,000 seconds, which is 11 hours, 6 minutes and 40 seconds. Started at midnight, the night ends at 11:06:40 the next morning, if nothing goes wrong.

The first design is one job that reads the authorized payments and captures them in a loop, keeping its place in memory. At 02:40 its machine dies. That is 9,600 seconds in, so about 48,000,000 captures have been sent. An engineer is paged, and has the job running again at 03:00. It has lost its place, so it starts again from the first payment. It sends 48 million captures that already happened, and each one uses a call from the same 5,000 a second. A card payment in this design is captured once, and the processor refuses to capture it again, so nobody is charged twice. But the night ends at 14:06:40, three hours late.

The second design stores progress where it cannot be lost: on the payments themselves. Each payment’s row, the attempt row from the first deep dive, moves from authorized to capturing before its capture call, and to captured after it. Every capture has its own key, such as capture:P1. Replay 02:40. At 03:00 the restarted job asks for payments still authorized, and there are 152 million. At 5,000 a second, each taking about 2 seconds, 10,000 captures were in flight at the moment of the crash. Their rows say capturing, and nobody knows whether they went through. They are sent again with the same keys, so the processor returns the first result for each, rather than an error the job would have to interpret. A processor that allowed several partial captures of one payment would not refuse a repeat at all, and the key is what keeps that design safe too. 152,000,000 plus those 10,000, at 5,000 a second, is 30,402 seconds, so the night ends at 11:26:42. The rows saved the night, and the keys made the uncertain captures safe. But an engineer still had to wake up.

The third design removes the person. The job is 20 workers. Each claims a chunk of 10,000 payments, oldest authorization first, by stamping them with its name and a lease that ends in 60 seconds. It renews the lease while it works. The claim uses SELECT … FOR UPDATE SKIP LOCKED, so two workers claiming at the same moment never take the same rows, and the lease keeps them apart afterwards. All 20 share one rate limiter set to 5,000 a second, because the limit is the processor’s, not each worker’s. So each worker sends about 250 a second, and has about 500 in flight at any moment.

Replay 02:40. One worker’s machine dies. The other 19 speed up to fill the shared limit, so the rate stays at 5,000 a second. 60 seconds later the dead worker’s lease has run out. Another worker claims its unfinished rows, including the ones still marked capturing. The 500 captures it had in flight go again with their keys. Nobody is paged, and the night ends at about 11:06:40.

Two more rules keep the night honest. The first is a deadline. Holds are captured oldest first, and an alert fires when any hold is five days old, two days before it would expire. A night that fails is then a problem for tomorrow, and never a loss. The second is the processor’s limit. If the processor answers 429, too many requests, every worker slows down through the shared limiter. Retrying on its own, each worker would only make the pile bigger.

Some teams ask why the capture waits for the night at all. Capturing each order when it ships spreads the 200 million over the day, 2,315 a second on average, well inside the limit. The interviewer’s version of this problem usually fixes the daily batch, so design the batch and mention the alternative in one sentence.

The experiment runs the night three ways. The tabs are one loop that keeps its place in memory, a state on every payment, and workers that claim chunks.

The interactive version of this example is available when JavaScript loads.

The gap: A night of captures takes 11 hours, and some night a machine will die in the middle of it.

Option 1: One loop, place in memory

A single job captures in order and remembers how far it got.

Works when: A few thousand captures that finish in minutes.

Breaks when: A crash at 02:40 restarts from zero: 48 million repeated calls, done at 14:06:40.

Option 2: A state on every payment

Each row goes authorized, capturing, captured, and every capture has its own key.

Works when: A job someone is watching.

Breaks when: The restart still needs a person; done at 11:26:42.

Option 3: Workers claim chunks with leases, under one limit (start here)

20 workers claim rows with SKIP LOCKED and a 60-second lease, and share a limiter of 5,000 a second.

Works when: Always, for a nightly batch this size.

Watch for: Leases and the limiter are two more things to run, and a deadline alert watches the 7-day window.

In the interview: Open with the arithmetic: 200 million at 5,000 a second is 11 hours. Then give option 3 its parts: a state on each payment, keyed captures, and leased chunks under one limiter. Finish with the 7-day deadline.

Say this: I authorize at checkout and capture at night, because a hold is free to release and a refund keeps the processor’s fee. 200 million captures at 5,000 a second is about 11 hours. Each payment’s row records its capture state and each capture has its own key, so a restart resumes and the uncertain ones are safe to resend. Workers claim chunks with leases and share one rate limiter, and an alert fires when a hold is five days old.

The refund arrives before the capture. What state is the payment in?

At 02:14 on Tuesday a capture worker captured Anya’s order. It saved captured on her payment and posted the sale to the ledger. A bad deploy at 02:10 that night had left the webhook intake answering 500 to everything, until someone rolled it back at 09:35. So the processor’s capture event, evt_1, failed to arrive. At 09:36 support refunded the bulbs, and the processor sent evt_2, refund.succeeded. It arrived at 09:36:03. evt_1 arrived at 09:40:00, on the processor’s next retry. At 09:42:00 evt_1 arrived again, because our 200 for it was lost on the way back.

None of this is unusual. Stripe’s documentation says both halves plainly: “Webhook endpoints might occasionally receive the same event more than once.” And: “Stripe doesn’t guarantee the delivery of events in the order that they’re generated” (Stripe). A failed delivery is retried “for up to three days with an exponential back off in live mode”. So an event can arrive long after events about later changes.

The money in this dive is Hugo’s share. The marketplace keeps 10% of a sale, so Hugo is owed 90%: $108 of the $120, and $27 of the $30 refund. The worker’s posting at 02:14 made him owed $108.

The first handler does the obvious thing. Each event carries a status, so it sets the payment to that status and posts the money. Walk the three deliveries through it. evt_2 sets the payment to refunded and posts the refund, so Hugo gives back $27 and is owed $81. evt_1 sets it to captured, which hides the refund, and posts the capture that the worker already posted. Hugo is owed $189. Then evt_1 arrives again and posts it a third time. Hugo is shown as owed $297 for a sale that owes him $81.

The second handler remembers the IDs of events it has applied, and skips any it has seen. Replay it. The repeat of evt_1 is skipped. But its first delivery still wrote captured over refunded, and still posted a capture the worker had already posted, so Hugo is owed $189. The event ID is new to the handler, and the money is not. Stripe warns of the same thing from another side: “In some cases, two separate Event objects are generated and sent.” Skipping repeated IDs fixes one kind of duplicate. It does nothing about order, or about one change reported twice.

The fix has two parts. The first is to read an event as evidence of a move, rather than as an order to set a status. A payment has a few states and a list of allowed moves between them. Authorized can become capturing, captured or released. Capturing can become captured. Captured, or partly refunded, can become partly refunded or refunded, as long as the refunds so far stay within the captured amount. The handler applies an event only if its move is allowed from the current state, in one conditional update: set captured where the state is authorized or capturing. An update that changes no rows sends the handler to read the payment. If its state is already at or past the one the event would set, the event was applied. If not, the event is early.

The second part is where money is posted. Each movement of money is posted once, under a key that names it, called its effect key. It is the processor’s reference for that movement plus what kind it is: ch_A:capture for the capture, re_D:refund for this refund. A unique index on that key refuses a second posting, whichever path the news arrived by. The ledger deep dive shows why balancing alone cannot catch this.

Replay the deliveries. evt_2 is a refund, and the payment is captured, so the move is allowed. It posts re_D:refund, and Hugo is owed $81. At 09:40 evt_1 arrives. ch_A:capture was posted at 02:14, so nothing changes. At 09:42 evt_1 arrives again, and its ID is already in the event table, so it is skipped before any work. The payment ends partly refunded, and Hugo is owed $81.

One case is left: an event that is early. Suppose the capture worker had been killed before saving its reply, so Anya’s payment still said capturing when the refund arrived. A refund cannot follow capturing. The handler does not guess, and it does not throw the event away. It fetches the payment from the processor, which says captured, then $30 refunded, and applies both moves, each under its own effect key.

The intake does very little, on purpose. It checks the signature, stores the event and answers 200. Stripe asks for exactly that: “Your endpoint must quickly return a successful status code (2xx) before any complex logic that could cause a timeout.” The signature is computed over the raw body. Parsing and writing the JSON back out can change its spacing or key order, so the intake checks the signature before any framework parses it. The signed header also carries a timestamp. An event signed more than five minutes ago, Stripe’s default tolerance, is refused, so a recorded event cannot be replayed later. A genuine retry still passes, because each delivery is signed afresh: “we generate a new signature and timestamp for the new delivery attempt.”

Storing before answering matters too. If the intake answered first and then crashed, the processor would treat the event as delivered and stop sending it. Someone would have to find it and resend it by hand. Lookups cover the rest. An event can go missing for good, for example if our endpoint was misconfigured for longer than the three days of retries. So the sweeper also fetches payments that have waited too long for news, such as a refund requested an hour ago that is still pending. Events bring most news within seconds, and the lookups catch whatever they miss.

The experiment delivers the three events three ways. The tabs are setting the status each event carries, skipping repeated event IDs, and allowing only legal moves with one posting per effect.

The interactive version of this example is available when JavaScript loads.

The gap: Events arrive more than once and in any order, one change can be reported twice, and each report can move money.

Option 1: Set the status the event says

Each event overwrites the status and posts its money.

Works when: Never, for payments.

Breaks when: A late capture hides a refund, and every report of the capture posts it again: Hugo owed $297.

Option 2: Skip repeated event IDs

Remember applied event IDs and skip repeats.

Works when: As the first check, always.

Breaks when: The late capture still hides the refund and posts a capture the worker already posted: Hugo owed $189.

Option 3: Allowed moves, effect keys, and a fetch when early (start here)

Apply an event only as an allowed move, post money once per effect key, and fetch the payment when an event cannot follow.

Works when: Always.

Watch for: A fetch costs a call to the processor, so it runs only for events that arrive out of turn.

In the interview: Open with option 3, and name its three parts. Give the intake’s order too: verify, store, answer 200, then work. If the interviewer asks what happens when an event never arrives, add the sweeper’s lookups.

Say this: The intake verifies the signature on the raw body, stores the event and answers 200, and workers apply it afterwards. An event is evidence of a move, so it is applied only if the move is allowed from the payment’s current state. When it cannot follow, I fetch the payment from the processor and apply what it says. Money is posted once per effect key, and repeated event IDs are skipped.

Finance asks where every cent of Anya’s $120 went. What do you show them?

Anya’s $120 is several amounts at once. The processor keeps a fee, which this page assumes is 3% of each charge. Real price lists add a fixed part and vary by card, and the arithmetic works the same way. So the processor keeps $3.60 and holds $116.40 for us. The marketplace keeps 10%, $12.00, and owes Hugo $108.00. Two business days later the processor pays what it holds into our bank. Every one of those numbers must still be right in a year, when an auditor or Hugo asks.

Follow five events on a sale like Anya’s through three designs. A worker recording the sale is killed partway through. The sale is delivered again. The processor sends it twice. Anya’s $30 refund posts. The processor pays out.

The first design keeps a balance for each account and updates it. Add $108 to what we owe Hugo. Add $116.40 to what the processor holds. One UPDATE each, four in all. Walk the events through it. The worker runs the first two updates, and a deploy kills it. The event was never marked done, so it is delivered again, and the next worker runs all four. Then the duplicate runs all four again. The refund takes $27 off what we owe Hugo, $3 off our fees and $30 off the processor’s balance. Hugo is now shown as owed $297: three times his $108 share, less $27. The accounts no longer add up. They are $8.40 out, which is the $12.00 fee less the $3.60 card fee that the killed worker never recorded. No row says any of this, because a balance holds only its latest value and nothing records how it got there.

Double-entry bookkeeping fixes the half-finished updates and the missing history. Every movement of money is one posting of several entries, and each entry says which account changed and by how much. Write each entry as a signed number. Money that lands in something we own or spend is positive. Money we now owe, or have earned, is negative. The sale is +116.40 for the processor’s balance, +3.60 of card fees, −108.00 owed to Hugo and −12.00 of our fees, and those sum to 0. Accountants call the positive entries debits and the negative ones credits, and a posting balances when they are equal: 116.40 + 3.60 = 108.00 + 12.00. Square’s engineers put it in one line: “each cent lost is matched with a cent gained” (Square).

A posting is written in one transaction, so a kill leaves all four entries or none. And entries are never edited. A mistake is fixed by a new posting that reverses it, so the history stays.

Replay the events with postings. The killed worker wrote nothing, because its transaction never committed. The redelivery posts the sale. Then the duplicate posts the sale again, and this posting balances too. Debits equal credits to the cent, and after the refund Hugo is shown as owed $189. Then the processor pays out what it really holds, $86.40. Our books still say it holds $116.40 more for us, which it does not have. A balanced ledger proves the arithmetic. It does not prove that each event happened once.

So every posting also carries the effect key from the last deep dive: the processor’s reference for the movement and its kind, such as ch_A:capture. A unique index on the key refuses a second posting of the same capture, however many times the news arrives. Replay once more. The duplicate is refused. The refund posts: Hugo’s share back, $27; our fee back, $3; the processor’s balance down $30, with its $3.60 fee kept. The payout moves $86.40 from the processor’s balance to our bank. Our books now say the processor holds $0.00 for us, which is what the processor says too, and Hugo is owed $81.00.

Balances are still needed, because Hugo’s dashboard should not add up his entries on every visit. They are kept in a separate table, updated in the same transaction as each posting. They can always be rebuilt from the entries. Stripe’s own ledger works on the same idea at a far larger scale: “At its core, Ledger is an immutable log of events” (Stripe). At 200 million payments and four entries each, ours writes 800 million entries a day. So entries are partitioned by month, and old months move to cheaper storage.

The ledger also records money that goes back. A dispute is a buyer asking their bank to reverse a charge. “Card networks typically allow cardholders to initiate disputes within 120 days of the original payment” (Stripe). By then Hugo has been paid. When a dispute opens, the processor “Debits the disputed amount, plus a dispute fee”. That posts like anything else: the processor’s balance goes down by the amount and the fee, what we owe Hugo goes down by his share, our fees go down by ours, and the dispute fee lands in an account of its own. If Hugo’s balance goes below zero, the ledger shows exactly how much he owes, and his next payout is reduced by it.

The experiment plays the same five events three ways. The tabs are a balance per account, balanced postings, and balanced postings with one per effect.

The interactive version of this example is available when JavaScript loads.

The gap: Money moves in several accounts at once, and the same event can arrive more than once.

Option 1: A balance per account

Update each account’s balance as money moves.

Works when: A prototype nobody will audit.

Breaks when: A kill mid-update leaves the books $8.40 out, and repeats show Hugo owed $297, with no record of why.

Option 2: Balanced postings

Each movement is one transaction of entries that sum to 0, never edited.

Works when: Every ledger, as the base.

Breaks when: A repeated event posts again and still balances: Hugo owed $189.

Option 3: Balanced postings, one per effect (start here)

Each posting has a unique effect key such as ch_A:capture; balances are a projection rebuilt from entries.

Works when: Always.

Watch for: Each refund needs its own reference in the key, so that two real partial refunds never collide.

In the interview: Open with option 3, and write the sale as four entries with the numbers. Say that balancing proves the arithmetic and not uniqueness, before the interviewer asks. Mention reversing postings for corrections.

Say this: Every movement of money is one posting of entries that sum to zero, written in one transaction and never edited. A correction is a new posting that reverses the old one. Each posting has an effect key, the processor’s reference and the kind of movement, with a unique index, because a duplicate posting balances just as well as a real one. Balances are a projection kept in the same transaction and rebuilt from the entries.

The bank got $193.10 and the ledger expected $212.50. Which one is wrong?

Stripe’s settlement table lists the United States at “2 business days”, so Tuesday’s money arrives on Thursday (Stripe). On Thursday morning the processor’s payout for Tuesday lands in our bank: $193.10. Our ledger recorded what the processor owed us for Tuesday, each charge less the fee we posted with it. Anya’s $120 is $116.40. Ben’s $50 is $48.50. Cleo’s $80 is $77.60. Anya’s refund takes $30 off. That is $212.50. The two are $19.40 apart.

The first idea compares the totals every day and alerts when they differ. They differ most days. The processor counts its days by its own cutoff, so a charge captured near the end of our day can land in the next payout. Refunds and disputes come out of whichever payout is next. So the alert fires most mornings, and after a week nobody reads it. Worse, a real problem hides inside the noise. A gap of $19.40 can be one ordinary thing or one expensive one, and a single number cannot say which.

The fix is to compare lines, not totals. The processor publishes each payout as a list of what is in it. Stripe’s report lets you “review every payment, refund, dispute, fee, and other balance transaction included in the payout” (Stripe). Each line carries the processor’s reference, which our attempts and postings store as well. So the reconciler matches line to line by reference. Every line ends up in one of four places. It matches. It is expected in a later payout. It is in the payout and not in our ledger. Or both have it and the amounts differ.

Walk Thursday’s payout through it. ch_A, Anya’s $120 less a $3.60 fee, is $116.40 in both. ch_B, Ben’s $50 less $1.50, is $48.50 in both. re_D, Anya’s $30 refund, matches. Cleo’s charge, ch_E, is in our ledger and not in this payout. It was captured after the processor’s daily cutoff, so it is expected in Friday’s payout. If it is still missing after that, it becomes a problem. And ch_C, $60 less a $1.80 fee, is in the payout and in no posting of ours. It is a charge somebody made by hand in the processor’s dashboard, to fix an order, without going through our system.

Now the gap has parts: Cleo’s $77.60, which arrives on Friday, less $58.20 from a charge we never recorded. 77.60 − 58.20 is 19.40. The first is normal. The second is a real exception, and it can be traced to one charge and one customer.

The match runs three ways, and each catches a different problem. Our ledger is matched against the processor’s lines, as above. A break there is our bug, or money moved outside our system. The processor’s lines must add up to its payout exactly: 116.40 + 48.50 + 58.20 − 30.00 = 193.10. A break there means we read the report wrong. And the payout must match the bank’s statement. A break there is money lost between the processor and the bank.

Exceptions go to a queue that finance works through, each with its evidence. None is fixed by editing a posting. ch_C gets a posting of its own, made by a person, with a reason and the order it belongs to. Two numbers are watched: how many exceptions are open, and how old the oldest one is. A timing exception older than its window is money that should have arrived.

Reconciliation also catches what every rule above it missed: a charge made outside the system, a capture posted twice, or a refund that failed after we recorded it. The financial reconciliation guide walks the sorting in more depth.

The interactive version of this example is available when JavaScript loads.

The experiment compares Thursday’s payout with Tuesday’s ledger two ways. The tabs are comparing the totals and matching every line.

The interactive version of this example is available when JavaScript loads.

The gap: The deposit and the ledger differ most days for ordinary reasons, and a real problem can hide inside the difference.

Option 1: Compare the totals

Alert when the deposit differs from what the ledger expected.

Works when: Never on its own, because it differs most days.

Breaks when: Cutoffs and refunds make it differ daily, so a $60 charge nobody recorded hides inside $19.40.

Option 2: Match every line, three ways (start here)

Match report lines to postings by reference, the lines to the payout, and the payout to the bank.

Works when: Always.

Watch for: Timing needs a window for each line, and the exceptions need an owner who works the queue every day.

In the interview: Open with option 2, and take the gap apart out loud: one charge on its way, and one charge nobody recorded. Say that no exception is fixed by editing a posting.

Say this: The processor pays out days later, by its own cutoff, so the totals differ most days and hide real problems. I match each line of the payout report to a ledger posting by the processor’s reference. Each line is matched, expected later with a window, or an exception that goes to a queue with an owner. The lines must also add up to the payout, and the payout to the bank statement.

The interactive version of this example is available when JavaScript loads.

The code has five tabs: claiming the request key, the attempt around the processor call, the rule that applies an event, a ledger posting, and the capture batch’s claim.

If they ask: 10,000 payments a second on PostgreSQL?

The requirements worked out 100,000 row writes a second at the peak. The data is split across several PostgreSQL primaries by order ID. An order’s keys, attempts, events, outbox rows and ledger postings all live on its shard. So each step is one local transaction, and the one-attempt-per-order index sees every attempt for its order. The key arrives with the order ID, so it is claimed on the right shard. Each payment carries its order ID in the metadata we attach at the processor, so the intake can route an event to its shard.

The hottest rows are the marketplace’s own. Every posting touches the processor’s balance and our fees, 10,000 times a second at the peak. So each of those balances is split into many rows. A posting adds to one of them, and a read adds them all up. Hugo’s balance is touched only by his own sales, so it stays one row.

If they ask: the processor goes down at the peak

At 20:00 the processor starts timing out. The first job is not to make it worse. A circuit breaker opens after a burst of failures, so new checkouts stop waiting 10 seconds each for answers that will not come. The second is to be honest with Anya: her payment shows as processing, never as failed.

Some marketplaces send new payments to a second processor while the first is down. That needs a second contract. It also needs the checkout to show the second processor’s card form, because a card typed into the first processor’s frame becomes a token only that processor understands. Attempts already sent to the first processor stay with it until they are looked up, as the lost-reply deep dive requires. When the breaker closes, the sweeper works through the unknown attempts, oldest first, with backoff.

If they ask: where does the card number go?

Nowhere near our servers. The processor’s payment form runs in a frame on our checkout page, served from the processor’s domain, and hands the page a token. Stripe’s guide explains why that matters: a business that handles card data directly “might be required to meet more than 300 security controls in PCI DSS” (Stripe), the card industry’s security standard. The shortest self-assessment, SAQ A, covers merchants whose card data handling is “completely outsourced to PCI DSS validated and compliant third parties” (PCI Security Standards Council). A marketplace this large is assessed by an outside auditor instead, but the frame shrinks what that audit has to cover in the same way. The page that loads the frame still has to be protected, because a script injected into it could swap the frame for a fake form.

If they ask: how does Hugo get paid?

Once a week, a payout job reads each shop’s balance from the ledger and sends what is owed to the shop’s bank account through the processor. A payout moves money, so it is built like a charge: an attempt saved first with its own key, a state that can be unknown, and a ledger posting once it is confirmed. Some marketplaces hold back a small reserve from each payout, so that a dispute months later has money to come from. A shop whose balance went below zero after a refund or a dispute is paid nothing until it recovers, and the ledger shows why. The distributed transactions guide covers how an order, a payment and a shipment stay in step when each lives in its own service.

Walk one payment through the final design

At 12:00:00 on Monday Anya taps Pay with key k1. The Payment API inserts k1, reads $120 from the order, and saves attempt P1 as sending. With no transaction open, it asks the processor to authorize 12,000 cents with key P1. The hold is placed at 12:00:01.8, P1 becomes authorized, and the page shows the order placed. A second tap would have been answered from k1’s row.

Hugo marks the order ready to ship. That night a capture worker claims a chunk that includes P1, marks it capturing, and captures it with key capture:P1 through the shared limiter. At 02:14 it saves captured and posts the sale under the effect key ch_A:capture: $116.40 held by the processor, $3.60 of card fees, $108.00 owed to Hugo and $12.00 of our fees. The outbox tells the order service the order is paid. The processor’s own capture event arrives later, finds ch_A:capture already posted, and changes nothing. On Thursday the payout report lists ch_A at $116.40 net, and the reconciler matches it to the posting.

The interactive version of this example is available when JavaScript loads.

RequirementWhere it is metThe trade-off
FR1 charge onceKeys inserted first, one attempt per order that has not failed, attempts saved before the call, unknown attempts looked upA buyer can see “checking” for up to a minute
FR2 show the stateA webhook intake that stores first, allowed moves, fetches for early events, and sweeper lookupsThe page can be a few seconds behind the processor
FR3 capture and refundA nightly batch of 20 workers under one limiter, and refunds with their own keysMoney waits for the night, and holds expire after 7 days
FR4 who is owed whatDouble-entry postings with effect keys, reconciled line by line every dayFinance works an exception queue every day
Never lose a chargeSaving first, the unknown state, and reconciliation as the last checkAn attempt unknown for a day needs a person

How does the answer change for Stripe, PayPal or a payment gateway?

Interview variantWhat carries overWhat changes
Design Stripe, or a payment processorKeys, the unknown state, events and the ledgerYou are the processor: shops send you keys, you send them signed events, and you reach the card networks through banks
Design a payment gatewayEverything up to the processor callOften means routing each payment to one of several processors, with the outage rules above
Design PayPal, or a digital walletThe ledger and its effect keysBalances are spent directly, so a transfer must check and debit a balance in one transaction
Design a payment system with daily batch captureEverything on this pageThe same problem, with the capture deep dive at the centre of the round
Design a merchant payout systemThe ledger, keys and reconciliationThe money flows out: balances, reserves, and payouts that fail at the bank
Design a refund systemKeys, the ledger and the event rulesPartial refunds against a captured amount, and refunds that fail days later

What should an answer reach at each level?

LevelWhat the answer shows
Intern or mid-levelCalls a processor, stores payments with a status, handles a webhook, and explains authorize and capture.
SeniorTakes an idempotency key from the client, and sends the processor a key from a saved attempt. Treats a lost reply as unknown and looks it up. Applies events as allowed moves, and keeps a double-entry ledger.
StaffInserts keys first and allows one attempt per order that has not failed. Never holds a transaction across the call, and says why. Builds the capture batch to resume without a person, posts once per effect, and reconciles line by line.
PrincipalDecides what the business promises while a reply is unknown, how the ledger is split and audited, when a second processor is worth it, and who owns each exception.

Test yourself with the quiz, then pick another problem from the System Design interview breakdowns.

By GOAT Engineer. Back to all breakdowns. Privacy Policy · Contact.