Lesson 3 · Minutes 20-30

Digital Wallet: Scaling It

Problem

From minute twenty, the interviewer takes apart the one thing that made your design correct. First the holiday forces a split, and one commit no longer reaches both sides of a transfer. Next the machine running that commit dies at the worst moment. Then an auditor asks for a balance from a past afternoon, which a row cannot give. Last, one merchant is paid so often that its row becomes a queue.

Two Sides, Two Shards

"The holiday has pushed your accounts onto separate machines, and the product still forbids anyone seeing half. What commits a transfer now?" Split by a hash of the account ID into 160 partitions, which this chapter also calls shards. Then ask the first question from Chapter 5's Transactions Across Partitions: can the two rows share a shard? 159 times in 160 they cannot, and no key puts two arbitrary users together. The 1 in 160 that do share one commit locally, as before.

The rest take two-phase commit across the two shards. A coordinator asks each one to prepare. Each side writes its changes durably, keeps its locks and votes. The sender's shard votes no if the floor fails, and the receiver's shard votes no if its account is closed. If both vote yes, the coordinator tells both to commit. This fits what was agreed, because nobody may see half and every participant is inside one store.

Each side now writes its own row of the transfer, with the sender and the client's ID. A resend goes to the sender's shard and meets the ID there, and a refusal leaves its row in the same place. Reads need the same care as writes. A balance read goes to the shard's primary and takes the row's lock, so on a row in prepare it waits, and neither person can read the old number once the other can read the new one.

What it costs is time and availability. The locks last at least two round trips, 2 to 4 milliseconds between zones, and that is harmless for an account with two transfers a day. A transfer touching a lost shard is refused, the refusing side of Chapter 4's CAP. Each transfer touches 2 of 160, so about 1 in 80 are refused while one primary fails over and its replicas elect another. Assume that takes about a second. At the holiday's rate it is about 250 refusals, and it spends almost none of Scope's four minutes a month.

Two details keep the sums honest. Prepares go out in parallel, so account order no longer prevents a deadlock between opposite transfers: a shard that waits past a short limit for a lock votes no, and the service tries the round once more before refusing. The one exception is a resend of a transfer the shard already holds in prepare. It is not a new transfer and it never votes no: it waits for the decision, and if the wait runs out the client gets no answer and asks again. Each try also has its own round number, so a late abort from the first cannot touch the second. And the prepare and commit records come on top of Scope's four row writes. Counted in full they are four more writes a transfer, the whole of the half you held back, so treat 160 as a floor and let the load test say how far above it you land.

Two other designs exist, and you say so without stopping for them: "There are two other ways to do this, a saga and one writer per account. I'm parking both for the deep dive, because each gives up something Scope promised."

The Coordinator That Dies

"Both shards have said yes, and the machine that was going to tell them the result is gone. Where does that leave them?" Their rows stay locked. A shard that voted yes has promised, so it may not decide alone, and two yes votes do not tell it what was decided. Those rows are in doubt. A transfer that wants them waits out its limit and is refused, and a balance read waits.

Say where the fix goes: "Each shard promised, so neither can decide alone. The decision is what has to survive, so it goes through consensus before anyone hears it." So the coordinator stops being one machine and becomes a replicated group across zones, keeping the log of Chapter 5's Leader Election and Consensus.

When a leader dies, its followers hear nothing and elect a new one, which reads the log. A decision it finds there, it finishes. A shard still holding a prepared row past a short wait asks the group about that transfer. With no decision in the log, the group logs an abort and answers, because nobody can have been told to commit, and the first decision logged for a round stands. A client with no answer resends the same transfer ID and reads the outcome.

Assume 20 coordinator groups and an election of about a second. At the holiday's peak, one group carries about 1,000 transfers a second. When its leader dies, those wait a second. Most then complete, and the few caught before their decision abort and go again on the client's resend. They miss the under-a-second promise for that moment, and nothing is lost.

What it costs is a consensus group to run, and one more round trip inside the lock, because the decision must be durable before the commit goes out. That makes a hold of about three round trips, up to 6 milliseconds, and the last probe is where that bill arrives. It takes more than one zone's failure to cost a group its majority. If that happens, its rows in doubt stay locked until it is back, and new transfers go to the other 19.

Last Tuesday at 14:00

"Two in the afternoon, last Tuesday. What was this account's balance, and how would you show it?" Make each account's entries the record. The per-side rows from the first probe become an append-only log, with a sequence number per account. The balance row becomes a stored fold, updated in the same local transaction, so the floor is still checked as the debit is written.

The move looks like Chapter 24's ledger, and the difference is the balance. There, each entry commits with its payment while the running totals follow seconds later, which is safe because nothing refuses a charge against them. Here a debit is refused against the balance, so the entry and the balance commit together, on the account's own shard.

An as-of question starts from a snapshot, a saved balance at a known sequence number, and folds forward from there. Assume a snapshot every 10,000 entries. That is at most 2 megabytes to read, about 0.2 milliseconds from an SSD, so replay decides nothing once it is bounded.

An account's order is its sequence, and the time is a label on it from the shard's clock. Chapter 5's Clocks and Ordering is why: a wall clock can jump, and one owner numbering its events cannot go wrong that way. So 14:00 means the last entry labelled at or before 14:00, as good as that clock.

What it costs: the 307 terabytes, the reason for about 150 nodes, with balance rows and snapshots on top, so that is a floor as well. A fold that must read every old shape of entry for as long as entries are kept. And a stored balance that has to be shown equal to the fold, which the deep dive on invariants picks up. A correction is a new entry, never an edit.

The Account Everyone Pays

"It's the holiday, and one merchant is being paid 3,000 times a second. Walk me through that row." It becomes a queue, and the lock sets its speed. A hold of 6 milliseconds lets about 160 credits a second through a row, and half of that, for headroom, is about 80. Every other payment to that merchant waits its turn, and past the short limit from the first probe it is refused.

Split that merchant's credits over sub-accounts, each its own key, the salting of Chapter 3's Hot Partitions. The lock decides how many: 3,000 credits at 80 a row take about 40 sub-accounts. Check the partition too. Each sub-account takes 75 credits a second at two writes each, which is 150. The rest of that partition's traffic is about 460, the 500 you plan on without this merchant's credits, so the total of about 600 row writes goes past the plan and stays well under the 1,000 limit. Count the prepare and commit records as well and a partition with a hot key goes over it, which is the first place the load test moves you above 160. A hash of the transfer ID picks the sub-account, so a resend lands on the same one.

One row against 40 sub-accounts, at 3,000 credits a second
One rowone key, one lock
Takes all 3,000 credits a second. A 6 ms hold passes about 160, or about 80 at half. A balance read is one key.
40 sub-accounts40 keys, a lock on each
Each takes 75 credits a second, under the 80. A balance read sums 40 keys, and only the main one can be debited.

This is safe because a credit has no floor, so any sub-account can take any credit. A hotel's count cannot be split this way, as Chapter 3's Picking the Partition Key warns and Chapter 23's flash sale shows, because its floor is on the total.

What it costs: a balance is a sum of 40 keys, and an as-of question folds 40 logs. A debit does need a floor, so a sweep job moves credits to one main sub-account as ordinary transfers, and only that one is debited. Assume a sweep a minute: 40 small transfers, nothing beside the 3,000 credits a second, and money the merchant can spend up to a minute late. A sum taken during a sweep can be briefly off, which a dashboard can bear, since nothing spends against it. An as-of sum leaves sweep entries out, since they only move the merchant's own money. Apply all this only to accounts known to be hot, from a short list kept in the store and read by the transfer service.

The trigger for something stronger is an account that sends at this rate. It cannot split so simply, because its floor would have to be shared out among the keys. That case belongs to one writer, in the first deep dive.

The Design After Four Probes

A transfer runs from the load balancer to the transfer service, the same stateless app servers, and from there to a coordinator group beside the write path. The group prepares both sides on the accounts store, records its decision through consensus, and tells both sides to commit. The store has 160 partitions, each with balance rows, entry logs and snapshots, a known hot merchant's credits land on its sub-accounts, and a sweep job feeds its main one. A balance read goes straight to the account's partition.

Nothing from the first design has gone missing. The transfer row lives on as the two entries that carry its ID, the unique ID sits on the sender's shard, a refused transfer keeps its small row there, and the floor is still checked on the balance row as the debit is written.

The full design, with the changes marked new
Clientthe wallet app Load balancerany server App serverstransfer service 160 partitionsentries, snapshotsNEW Coordinatorsconsensus decisionNEW The other sidea second partitionNEW Sub-accounts40 keys, hot merchantNEW balance transfer prepare, commit prepare, commit credit readwriteNEWsince the first design
Interview Pitfalls
  • Running the coordinator as one service with its own database, which moves the in-doubt rows without removing them. The interviewer kills that database next.
  • Dropping the stored balance once the log exists, then folding a log to check every debit's floor.
  • Salting every account "to be safe", which turns every balance read into a gather.
What Interviewers Listen For
  • The hot account worked from the lock time, not left at "it gets slow".
  • A plain reason why a credit can be split and a debit cannot.
  • Availability during a failover raised as a cost of the split, with no probe asking.

Knowledge Check

Two-phase commit holds each account's lock for at least two round trips between zones. Who really pays for that?

  • An account that takes many transfers every second
  • Every account, which now waits seconds per transfer
  • Auditors, whose as-of reads wait behind the locks
  • The store, whose partitions double to hold the locks

The decision now goes through consensus before anyone is told. What does that add to a transfer?

  • Two more shards, so 1 in 40 are refused in a failover
  • A pending state that users can see for about a second
  • One more round trip inside the lock, and a group to run
  • A second lock on each row, kept until the next election

Why does replaying the log stop deciding anything in this design?

  • Replay runs only at night, when no transfer is waiting
  • The stored balance replaces the log, so nothing replays
  • Old entries are compacted, so that each log stays short
  • A snapshot every 10,000 entries bounds a read at 2 MB

You split one merchant's credits over 40 sub-accounts. What have you paid for that?

  • Credits that can land twice, since any key can take one
  • A balance that sums 40 keys, and a sweep before any debit
  • A floor check on each credit, now that the total is split
  • A hold that grows to about 40 round trips on every credit

You got correct