Lesson 3 · Minutes 20-30

Payment System: Scaling It

Problem

Four questions fill minutes twenty to thirty, and none of them is about speed. First a call goes quiet for ten seconds, and the interviewer wants to know what your code believes. Then a phone on a bad connection sends one checkout twice. Then finance brings one seller's balance and asks where it came from. Last comes the nightly run at a million sellers, dying halfway through.

The Silent Call

"Ten seconds and no reply from the processor. Is the money gone or not, and who is going to find out?" Nobody can say yet, and nobody owns the question, because the request that made the call is about to end. So write before you call, and move the call out of the request.

A payment row goes in first, in one local transaction, with its state, its key and a message in an outbox, a table of messages written along with the change. The server answers at once with the state processing, and the page polls the GET. From there an orchestrator owns the flow, one service holding each payment's state machine, because when the request has gone, something must still own the answer. Chapter 5's Transactions Across Partitions names payments as the case for it.

A relay, a small process that reads the outbox, delivers the message to the orchestrator, and the orchestrator calls the processor. A yes moves the payment to charged, and a no to declined. A timeout or a server error moves it to unknown, never to failed, and the buyer keeps seeing processing. Tell the interviewer why: "A timeout isn't a failure, it's a question I haven't had answered, so it gets its own state."

A resolver owns every unknown. It is a small worker that settles each one with the same key, and the first deep dive says when it retries and when it asks. The processor's webhook, its signed report of what happened, often gets there first, and is deduplicated by event ID, as in Backend Deep Dive's Receiving Webhooks. This is also the owner that Chapter 23's hold asked for when its card call timed out.

Each step is one local transaction with its message in an outbox, so a crash between steps loses nothing. And each write applies only if the payment is still in the state it expects, so whichever report lands second changes nothing and writes no second entry. If an orchestrator dies or stalls mid-call, the relay redelivers, and another one calls with the same key and gets the same answer, or is told to wait. A command older than the resolver's limit is not sent: the payment moves to unknown, so a stopped relay leaves buyers waiting and charges nobody a day late. An alert watches the age of the oldest unknown, and past 24 hours the resolver stops and the daily file closes it.

The price is a service and a state machine for what was one call, a buyer who sometimes waits, and 8,000 payments a day through a path you now watch. You pay that once unknowns outrun a person with a dashboard.

It also ends a second failure. At 400 payments a second and an assumed 10-second timeout, a slow processor would pin 4,000 requests in your servers, the sum in Chapter 6's Failure Across Many Services. Now a request ends when its row commits. The orchestrator would face those 4,000 calls instead, so it caps its calls in flight, and the rest wait as rows, holding no server.

The Second Charge

"A phone dropped off the network, the app resent the checkout, and there are two charges on the card. What should have tied those together?" One name for one intent, on both hops. There are exactly two hops: from the phone to you, and from you to the processor.

On the first hop, the app makes a client key per checkout attempt, and keeps it until it has an answer. A unique constraint on the order and that key means a resend finds the first payment and gets it back, a decline included. On the second hop, the payment's ID is the key to the processor, the same on every retry and after every restart, so a resent call replays the first result. Chapter 6's Delivery Semantics at Scale draws this boundary, and a single hop is Backend Deep Dive's Idempotency Keys.

One rule makes it end to end: a new key is allowed only after a definite failure. A decline may get a new attempt. An unknown may not. A second constraint keeps each order to one attempt that is open or charged, so a buyer who tries again during an unknown, or after a charge the app never heard about, is handed that attempt back. Offer the rule before you are asked: "I only allow a new key after a definite no. While an attempt is unknown, that order stays closed to new ones."

The client key comes from outside, so the server trusts nothing else either. The order has to be the signed-in buyer's, the amount has to match it, and a repeat has to name the same order and amount. Anything else gets a refusal.

A refund is a different call, so it gets a key of its own, because sending the charge's key would only replay the charge. It has its own row, with its ID as that key. Only the seller, support or one of your own jobs may ask for one, and refunds may not add up to more than the charge. A timeout leaves it unknown, with the same resolver as its owner. Chapter 23's refund after a late payment is this same call, with this same owner.

What you pay: keys and responses kept on every row, a buyer who cannot retry while an attempt is unknown, and a horizon. Your own constraint lasts as long as the row. Past the agreed 24 hours, the processor forgets the key, and the same call would be a new charge. So the resolver stops retrying well before then, and the file closes whatever is left, which the first deep dive takes up.

The Balance Finance Asks About

"Finance wants to know why this seller is owed 4,312 dollars, and all you have is a number in a column. Show me the explanation." There is none, so the number stops being the record, and a ledger takes over. Every money movement becomes one journal entry: a set of lines, each naming an account, a side and an amount, whose debits equal its credits. It is written in the same local transaction as the state change that caused it, and it is never updated.

Work one sale aloud. A debit raises what you hold or are owed; a credit raises what you owe or have earned. Assume a 100-dollar sale at a 10 percent commission. Assume one call both authorizes and captures, since an authorization alone only holds the funds, and that the processor bills its fees apart from the sale. When it is charged, three lines go in. Debit processor receivable 100, which is what the processor now owes you. Credit seller payable 90, which is what you now owe the seller. Credit commission 10, which is what you earned. When the file settles it, two more: debit bank 100, credit processor receivable 100.

A balance is now the sum of an account's lines, so the 4,312 dollars is a list, and each line names its payment. Because each step of the flow is one balanced entry, the books balance after every step, as the saga in Chapter 5 promises.

One 100-dollar sale through the accounts
Chargeddebits 100, credits 100
Debit processor receivable 100. Credit seller payable 90. Credit commission 10.
Settleddebits 100, credits 100
Debit bank 100. Credit processor receivable 100.
Paid outtwo entries, debits 90, credits 90
Debit seller payable 90, credit payouts in transit 90. Then debit payouts in transit 90, credit bank 90.

Now the store. Partition by the payment ID's first part, the order, so a state change and its entry stay one local transaction and no entry crosses a partition. All of an order's attempts then share a partition, and the two constraints above can hold. The order's row lives there too, and its status is set in the same transaction. A refund and its entry sit with their payment. Each partition keeps three copies, and a commit waits for one in another zone, so a failover cannot lose an entry.

Scope's 4 partitions counted lines alone, so count all that a sale writes to this store at peak, leaving the two settling lines for the night. The payment row and its outbox row are two. The answer writes the payment's state, the order's status, three lines and an outbox row, which is six more. The relay's mark on each outbox row makes ten. Ten writes times 400 is 4,000 a second, which needs 8 partitions at half their limit. The bytes ask for about 10 partitions of three copies, the 31 nodes, so the bytes still decide.

This costs 61 terabytes, and a balance that is no longer one read, because one seller's lines are spread over every partition. So a table keyed by account keeps running totals, fed from the outbox, and may lag by seconds. That is the second table of Chapter 3's Picking the Partition Key, eventually consistent.

That lag is safe because nothing here refuses a charge against these balances, and that is the line against Chapter 25's wallet, where a debit checks its balance as it writes. Finance's line-by-line question still goes to every partition, which a rare question can afford.

A Million Payouts

"Tonight a million sellers get paid. Tell me how the run is built, and what is left when it dies halfway." Build it as a million small pieces. A nightly cut-off divides tonight's payouts from tomorrow's. Each relay reports how far it has delivered, and once all of them have passed the cut-off, so have the running totals. Then the nightly job creates one payout row per seller, keyed by seller and date, so a second run finds the row and does nothing.

The amount is the part of the seller's payable that has settled, which the account table tracks from each settlement's message. A sale the file has not confirmed waits for a later run. Money that has left cannot be recalled, so the payout comes last in the whole flow, after settlement: Chapter 5's rule that the step you cannot compensate goes last.

Each payout is a saga with a pending state. First, one local transaction: debit seller payable, credit payouts in transit, with the outbox message, all on the payout's own partition. Second, a worker takes the message from a queue and calls the processor with that key, at 50 a second between them. It is a queue and not a log because order does not matter, and one slow call must not hold up the sellers behind it. Third, on confirmation: debit payouts in transit, credit bank. Follow the 100-dollar sale to its end, and the bank holds 10, commission holds 10, and every other account is back at zero.

A returned payout writes a new entry that moves the money back to payable, which is the compensation, and it goes out in a later run. A payout call can time out too. At 1 in 1,000, that is about 1,000 a night, and they go to the same resolver under the same rule. The other half of the processor's limit, 50 calls a second, is what those retries spend.

So the second half of the question has a short answer: "If this dies at seller five hundred thousand, nothing repeats, because each payout has its own row and its own key."

The run takes five and a half hours of a six-hour window, so a slower processor misses the bank's deadline, and whatever is unsent goes first in the next window. Six hours at 50 a second is about 1.08 million, so past that many sellers the run no longer fits. Then take more of the limit, or batch where the processor offers it.

It costs bytes as well. Payouts add 4 million lines a day, a tenth on top of Scope's 40 million, and payment rows and keys come on top, so treat 61 terabytes and 31 nodes as floors.

The Board at Minute Thirty

A checkout commits its row to the payments and ledger store, split by order, with an outbox on each partition. A relay delivers from there: commands to the orchestrator, totals to the account table, payouts to a queue. The resolver, the webhook receiver and the payout workers write back to the store. The first design's nightly job is still there, reduced to matching the file and creating the rows.

The full design, with the changes marked new
Browserbuyer, card token Load balancerany server App serversstateless Account tablerunning totalsNEW Orchestratorowns the flowNEW Payments, ledgerby order, outboxNEW Relayreads each outboxNEW Resolverowns every unknownNEW Card processorcharge, payout Nightly jobmatch file, make rows Payout queueone per sellerNEW Payout workers50 a secondNEW Webhookssigned reportsNEW checkout, poll balance row, outbox outbox command state, entry pay same key report file readwriteasyncNEWsince the first design
Interview Pitfalls
  • Minting a new key on each retry, which defeats the only thing that ties the attempts together.
  • Showing a buyer "payment failed" for an unknown, because the state machine had only two ends.
  • Keying the ledger by account, which splits every entry across partitions, a problem this chapter does not otherwise have.
What Interviewers Listen For
  • The rule for when a new key is allowed, stated unasked.
  • A sale worked through the accounts, with debits shown equal to credits.
  • The payout run given as a rate against a window, along with what would break it.

Knowledge Check

A timeout now moves a payment to unknown. What have you taken on by adding that state?

  • A second charge on about 1 in 1,000 payments at the processor
  • A ledger entry to reverse for each call that happens to time out
  • A buyer who sometimes waits, and a path you now have to watch
  • A lost sale each time, because the buyer has to start over

When may a buyer's next try on an order use a new key?

  • Only after a definite failure on that order, such as a decline
  • On every retry, so that the processor can tell the attempts apart
  • Once the resolver has been unable to reach the processor for a while
  • As soon as the 24 hours pass, since the processor forgets its keys

Why may the running totals lag by seconds here, when Chapter 25's wallet may not?

  • Payments are few enough here that the lag rarely shows at all
  • A seller's balance changes only once a night, when the run goes
  • Nothing here refuses a charge against one of these balances
  • The settlement file corrects every total before anyone reads it

The payout run dies at seller 500,000. What does it leave behind?

  • One open transaction, which the database rolls back as a whole
  • A saved position in the job, and a rerun goes on from that seller
  • A run to repeat from the start, which tomorrow's file then checks
  • Rows still pending, which the workers finish under the same keys

You got correct