Lesson 4 · Minutes 30-45

Digital Wallet: Deep Dives and Curveballs

Problem

Two-phase commit is on the board, and around minute thirty the interviewer asks why not something else. The fifteen minutes that remain take that question first, then the log, then how you watch the invariants. Four curveballs follow, and then what each level does with all this.

Three Ways to Move Money Between Two Shards

You parked two designs by name in Scaling It, a saga and one writer per account. Here they are beside the one you drew. Two-phase commit, as drawn, is atomic and invisible, with locks of about 6 milliseconds and a refusal when a shard is down.

A saga, as Chapter 5's Transactions Across Partitions draws it, is a chain of local transactions. One on the sender's shard debits the sender and holds the amount as pending, with its message in an outbox. One on the receiver's shard credits, deduplicated by sender and transfer ID, and its acknowledgement closes the hold. A credit that can succeed later is retried. One that never will, on a closed account, releases the hold back to the sender. Nothing is locked across shards, and a downed receiver does not stop the sender. But the pending state is visible, and Scope ruled that out.

One writer per account, in practice one per partition, is fed by a log. Commands apply in order, so there are no locks, and a hot account is limited only by its writer's rate. A transfer is still two appends on two logs, though, so underneath it is a saga with the same visible gap. It also brings a writer to fence on failover, the job of Chapter 5's Leases, Locks and Fencing.

The choice here is two-phase commit, and you tie it to the words that decide it: "I'm choosing two-phase commit because you said nobody sees half. If the product can live with pending, or accounts move to different regions, I'd take the saga." In different regions, two round trips alone are 140 milliseconds of locks. Many hot senders, or a team that already keeps its truth on a log, would give one writer.

Which transfer, by requirement
Nobody sees half, and one store holds every account→Two-phase commit
Pending is acceptable, or shards are regions apart→A saga
Many hot senders, and a log already the truth→One writer
Two-Phase Commit vs Saga vs One Writer

Two-phase commit is atomic and invisible until whole, and holds locks across both shards. Use it inside one store with a replicated coordinator, when nobody may see half.

A saga commits a step at a time, with a pending hold between. Use it when the product can show pending, or the shards are too far apart to hold locks across.

One writer applies each account's commands in order from a log, with no locks. Use it when hot accounts are the main problem, and pay with a saga's visible gap and a writer to fence.

The Log Decides

Back to the log from the third probe, because it is not only there for auditors. Chapter 24's ledger explains money after the fact: its entries commit with each payment, and its running totals may lag, because nothing refuses a charge against them. This log is the write path, with the balance a fold kept beside it, and every debit decides on that balance.

So separate a command from an entry. A command asks for something and may be refused. An entry is a fact. Only facts go in the log, and a refused transfer leaves its small row beside the log, never in it, so replay never decides anything a second time.

That gives two kinds of repair. A bug in the fold is fixed and replayed, and balances and snapshots are rebuilt from nothing, because both are only saved answers. A bug that moved money is corrected by new entries, because what it wrote is a fact now.

What it costs: entries are never rewritten and stay at least the agreed 7 years, and past that an old one can go only behind a snapshot that carries the balance forward. That snapshot is then part of the record, the one saved answer a replay cannot rebuild. Their shapes pile up. And a query the log was not designed for needs its own derived table.

Invariants, Watched All the Time

Scope promised proof on demand, so the proof runs all day. Each entry carries two lines on its own shard: the account, and that shard's inter-shard account, which says what this shard owes the others. Take 25 dollars. The sender's shard debits the sender 25 and credits its inter-shard account 25. The receiver's shard credits the receiver 25 and debits its inter-shard account 25.

So a shard's lines sum to zero at every commit, and each shard can be checked alone. Both lines live on the one entry row, so this adds no write, and the inter-shard total is summed by the checker, never kept in a row that every transfer would lock. Across shards, those accounts net to zero once every transfer has landed.

This is also what makes Chapter 5's line, the books balance at every step, exact under a saga, if the product ever flips you to one. Step one, on the sender's shard: debit the sender, credit the hold. Step two, on the receiver's shard: debit its inter-shard account, credit the receiver. Step three, on the sender's shard again: debit the hold, credit its inter-shard account. Each step sums to zero where it runs. A checker that simply added balances and open holds would count the money twice between the credit and the closing of the hold.

One 25-dollar saga on two shards, each step summing to zero
Debit and holdsender's shard
Debit the sender 25. Credit the hold 25.
Creditreceiver's shard
Credit the receiver 25. Debit the inter-shard account 25.
Hold closedsender's shard
Debit the hold 25. Credit the inter-shard account 25.

Three more checks run off the write path, in a job that reads the shards' replicas. Every transfer, named by sender and ID, has both sides, and, at an assumed limit of a minute, one left unmatched pages someone. The stored balance equals the fold, sampled across accounts. No user account is below zero.

No total is read at one instant across shards. Chapter 5's Clocks and Ordering is why two shards' clocks cannot name the same instant, and stopping the world to make one would refuse every transfer. Pairing by sender and ID stands in for it, and you can say so plainly: "I don't need one moment across all the shards. Each shard balances at every commit, and the transfers pair up by sender and ID."

Curveballs

"A fraudulent transfer has to be reversed." That is a compensation, not an undo: a new transfer the other way, with an ID of its own and a link to the original, both left in the log. Only your fraud team's role may ask for one. The receiver may have spent the money, so the floor stops it, or the account goes negative under a rule only this path can use, and the below-zero check has to know that rule. Ask who bears the shortfall.

"Let a group pay one bill: one sender, ten recipients, all or none." Only a store that holds every account can promise this; a path through an outside party could not. Two-phase commit stretches to eleven rows, prepared in parallel, so the hold stays about three round trips, up to 6 milliseconds. It now touches up to 11 of 160 shards, so about 1 in 15 are refused while one primary fails over, against 1 in 80. So cap the group.

Past the cap, say a payroll of 50,000, a commit across every shard stops whenever any primary does, so ask what all or none really means. Debit the sender once into a batch account, then credit each person as an ordinary transfer keyed by batch and line. At the 80 a second one row passes at half its limit, that takes about ten minutes. Each transfer is still whole, and two colleagues may see their pay minutes apart, so say that. A line that cannot land stays in the batch account and goes back to the sender as a transfer of its own.

"Prove to a regulator that no money was created." Replay the whole log with a checker that shares no code with the writers, and show the totals match at every checkpoint. A replay proves only what the log says, so tie the total of all balances to the money in the bank. That one comparison is reconciliation with an outside party, the move Chapter 24 names.

"A region fails, and you may lose nothing." That is an RPO of zero, so every durable step waits for another region, as Chapter 6's Regions and the Arithmetic of Nines lays out. Across the US that is about 70 milliseconds a step. Three steps are about 210 milliseconds of locks, so a row passes about 5 credits a second, and the merchant's 40 sub-accounts become over a thousand at half that limit. An ordinary transfer still answers under a second, so the price lands on hot accounts. Say it, then ask whether surviving a zone at 1 to 2 milliseconds is enough for most traffic. Fence the old region before the new one takes a write, or both spend the same money.

How Each Level Answers

A mid-level answer has the single transaction right, floor and row order included. It reaches for sharding when told the database tops out, and needs prompting to see that the transaction no longer covers both sides. It knows two-phase commit by name, and works through the coordinator's death with help.

A senior answer asks whether anyone may see half, and gets the protocol from the reply. It explains in-doubt rows and moves the decision into consensus without a hint. It builds the log and bounds replay with snapshots, works the hot account from the lock time, and says why credits can be split.

A staff answer lays out the three transfers with what would flip the choice, and asks the product question that decides it. It designs the invariants as a running job and sees why adding balances and holds counts money twice. It prices zero RPO in sub-accounts and asks whether a regulator requires it. And it gives reversal an owner and a policy, rather than a database operation.

Interview Pitfalls
  • Presenting a saga as atomic, then being asked what the receiver sees between the steps.
  • Offering a nightly total as the proof, when a day of drift is a day of unexplained money.
  • Answering the reversal by deleting the transfer, in a design whose point is that entries are only ever added.
What Interviewers Listen For
  • The event that would change the candidate's mind between the three transfers, named unasked.
  • The checker's double count raised without being led there.
  • Each curveball priced before it is accepted.

Knowledge Check

A fraudulent transfer has to be reversed, and the receiver has already spent the money. What is the best move?

  • Delete both entries, then rebuild the two balances from the log
  • Lower the receiver's balance row and leave the log as it stands
  • Send a new linked transfer back, and ask who bears the shortfall
  • Refuse the reversal, since no balance may ever go below zero

One sender now pays ten recipients, all or none. What does the payment touch, and what does that cost?

  • Two shards, so refusals stay at 1 in 80 while a primary fails over
  • All 160 shards, so every group stops when any primary fails over
  • Up to 11 of 160 shards, so a row's hold grows to 11 round trips
  • Up to 11 of 160 shards, so about 1 in 15 are refused in a failover

A regulator wants proof that no money was created. What does tying the total to the bank add to a replay?

  • It checks the log against a record you did not write yourself
  • It speeds up the replay, since only the bank's total is read
  • It replaces the checker, since the bank has audited the log
  • It shows that each transfer reached the right person in time

A region may now fail with nothing lost. What does an RPO of zero do to a row's lock?

  • It holds about 6 ms, because only the decision leaves the region
  • It holds about 210 ms, so a row passes about 5 credits a second
  • It holds about 70 ms, because three steps share one round trip
  • It holds no longer, because the copy goes after the lock is freed

You got correct