Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Case studies · Lesson 31 of 44

Case study: design a ledger and a wallet

A senior-level walkthrough of a ledger and a digital wallet: double-entry bookkeeping, immutable entries and audits, exact money arithmetic, overdraft races, hot accounts and cross-shard sagas with crash recovery, with tested C#.

Case studyApplied36 min readUpdated

  • 1 architecture diagram
  • 1 sequence flow
  • 3 data models
  • 1 API design
  • 7 code samples
  • 10 interviewer follow-ups
  • 4 self-checks

Read first: A framework for system design interviews, Replication and sharding, Case study: design a payment system

By the end you will be able to
  • Record money movement as an append-only double-entry journal, where every transaction's debits equal its credits and a transaction id posts once, and derive every balance from it.
  • Fix mistakes with reversing entries and never with edits, and prove integrity continuously, because the journal must reproduce every balance and assets must equal liabilities plus revenue.
  • Do money math in integer minor units with a stated rounding rule, and allocate with the largest remainder method, since naive rounding broke the total in 29,630 of 100,000 splits.
  • Make the overdraft check and the write one atomic step. A check-then-act overdrew a wallet, and a locked check admitted exactly 100 of 1,600 withdrawals against a balance of 1,000.
  • Move money across shards with a saga of idempotent steps through clearing accounts. In the simulation 9,343 crashes lost no money and no step was posted twice.

6 code samples (297 lines), collapsed so the explanation stays in focus.

A ledger is the one part of a financial system that is not allowed to be approximately right. Every payment, wallet top-up, fee and refund ends as a few rows that say where money came from and where it went, and every other table is derived from those rows or can be checked against them. A wallet is the product built on top: a balance for each user, deposits, withdrawals and transfers between users. The hard questions are the ones a spreadsheet never asks. What if two withdrawals race? What if the process dies between debiting one account and crediting another? What if the accounts live on different machines? How do you split 100.00 three ways without losing a cent?

This lesson builds the answers in C# and tests each one: a double-entry ledger with invariants, an overdraft race, exact money arithmetic, and a transfer across two shards that survives thousands of crashes. It follows designing a payment system, which produces the events this ledger records, and it leans on transactions and isolation and distributed transactions for the theory underneath.

HLD

Clarify the problem

Spend the first minutes on questions. Each answer changes the design.

AskWhy it matters
Is this an internal ledger, a customer wallet, or both?A ledger is the system of record for all money movement. A wallet exposes a balance and operations to users. The wallet sits on the ledger
Which operations: top-up, withdrawal, transfer between users, payment, refund, fee?Each is a transaction with its own entries and its own failure cases
Can a balance go negative?Customer wallets usually cannot. Credit and merchant accounts may. The rule must be enforced atomically
One currency or many?Every transaction must balance within each currency, and conversion needs its own accounts
How consistent must it be?Strongly, for balances and transfers. Reporting can lag
What must never happen?Money created or destroyed, a balance that goes negative, a transfer applied twice or half applied
Is it audited?Yes. History must be immutable and explainable years later

A good scope for 45 minutes: wallets with top-ups, withdrawals and transfers (including across shards), a fee, immutable history, strong consistency, and an audit that proves the books balance.

HLD

Estimate: modest rates, hot spots and a long memory

State assumptions out loud. They are illustrative and the interviewer may change them.

Example · estimate
wallets:     100M users (assumed), 20M active a day
transfers:   5 per active user a day = 100M a day = ~1,200 a second
peak (x5):   ~6,000 transfers a second
entries:     ~3 per transfer (sender, receiver, fee) = 300M a day
entry size:  ~150 B = ~45 GB a day, ~16 TB a year
balance:     ~10 reads per active user a day = ~2,300 a second
hot spot:    one merchant account credited 1,000 times a second

Five conclusions:

  1. The rates are modest, so correctness is the problem. Six thousand transfers a second is well within a sharded relational database. The cost of a wrong balance is not a slow page, it is a lawsuit.
  2. Storage is small and long-lived. About 16 TB a year of entries that are never updated or deleted, so the journal can be partitioned by time and archived.
  3. Balances are read far more than they are written, so keep a running balance next to the journal and verify it against the journal continuously. Summing the journal on every read does not scale.
  4. The scaling enemy is the hot account. A thousand credits a second to one merchant row will serialize on that row's lock. The cure is a design change (sub-accounts, batching), not a bigger machine.
  5. Transfers between shards are the hard part. A transfer within one shard is one atomic transaction. A transfer between shards has no such transaction, and the design must say what happens when it stops halfway.

LLD

The contract and the data model

CallWho calls itMeaning
POST /v1/transfersWallet app or internal servicesMove money between two accounts. The idempotency key is required
POST /v1/topups and POST /v1/withdrawalsPayments and bank integrationsMove money between a wallet and the outside world
GET /v1/accounts/{id}/balanceWallet appThe available and the pending balance
GET /v1/accounts/{id}/entriesWallet app, support, auditThe history of one account, paged by cursor
POST/v1/transfers
auth
user token, or a service token for internal callers
idempotency
Idempotency-Key header, required, so a retry never moves money twice
body
{ "from": "acct_7", "to": "acct_42", "amount": 3000, "currency": "USD", "memo": "dinner" }
note
the amount is an integer in the smallest unit of the currency, and the response never says "failed" while the outcome is in doubt
  • 201posted, returns { "id": "tx_91c", "status": "posted" }
  • 202accepted, a cross-shard transfer is in progress, returns { "id": "tx_91c", "status": "pending" }
  • 402insufficient funds
  • 409the key was reused with different parameters
accountsSQL, sharded by account id
  • idtext

    PKSHARD KEY
  • kindtext

    asset, liability or revenue, which decides how a balance reads

  • currencytext

  • balancebigint

    the running balance in minor units, updated in the same transaction as the entries

  • versionint

    bumped on every posting, for optimistic concurrency

  • frozenboolean

    a frozen account accepts no postings

The balance is a cache of the journal. An audit recomputes it from the entries and compares.

entriesSQL, append-only, partitioned by time
  • tx_idtext

    every transaction posts two or more entries

    INDEX
  • seqint

  • account_idtext

    INDEXSHARD KEY
  • amountbigint

    positive is a debit, negative is a credit, and the entries of a transaction sum to zero

  • currencytext

  • created_attimestamptz

  • metatext

    the business reference: payment id, transfer id, provider reference

    NULL

No UPDATE and no DELETE: the database role of the service has no permission to run either.

transactionsSQL
  • idtext

    also the idempotency handle: posting the same id twice is a no-op

    PK
  • idempotency_keytext

    UNIQUE
  • statetext

    posted, or for a cross-shard transfer: started, debited, done, undone

  • created_attimestamptz

HLD

The high-level design

Fig. Wallet on a double-entry ledger: single-shard posts, sagas across shards
Fig. Wallet on a double-entry ledger: single-shard posts, sagas across shards
Fig. A transfer across two shards
Fig. A transfer across two shards

Read it as one rule applied twice. Inside a shard, a transfer is a single ACID transaction that writes two or three entries and updates the running balances, guarded by a balance check. Between shards, no transaction spans both, so the transfer is a saga, a short sequence of single-shard transactions with a log that says how far it got, each step idempotent and each paired with an undo. The auditor at the bottom re-derives every balance from the journal and compares, which is how the system proves it is still correct.

LLD

Deep dive: the double-entry ledger

Double-entry bookkeeping, centuries old and still the standard, records every movement as at least two entries, a debit in one account and a credit in another, of equal total. That rule gives you a free check, because the sum of every entry in the system must be zero, and it gives money a place: it never appears or disappears, it moves from one account to another. When a customer tops up a wallet with 100.00, the entries are a debit of 100.00 to the company's bank account (an asset went up) and a credit of 100.00 to the customer's wallet account (a liability went up, because the company now owes the customer that money). A transfer debits one wallet and credits another. A fee credits a revenue account.

The convention in the code below is that debits are positive amounts and credits are negative, so a transaction balances when its lines sum to zero. A balance reads according to the kind of account: an asset by debits less credits, a liability or revenue by credits less debits. The books then satisfy the accounting equation, assets equal liabilities plus revenue, and the test checks it after 100,000 transactions.

C# · Kind, Line, Posted, …60 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum Kind { Asset, Liability, Revenue }

public sealed record Line(string Account, long Amount);                          // Amount > 0 is a debit, Amount < 0 is a credit
public sealed record Posted(string TxId, IReadOnlyList<Line> Lines);

// An append-only double-entry ledger. Every transaction balances (debits equal credits), a transaction id can be posted only
// once, and nothing is ever updated or deleted: a mistake is corrected by posting the reverse.
public sealed class Ledger
{
    private readonly object _gate = new();
    private readonly Dictionary<string, Kind> _kinds = new();
    private readonly Dictionary<string, long> _debitMinusCredit = new();              // the running balance of every account
    private readonly Dictionary<string, Posted> _posted = new();
    private readonly List<Posted> _journal = new();

    public void Open(string account, Kind kind) { lock (_gate) { _kinds[account] = kind; _debitMinusCredit[account] = 0; } }

    // The balance as people read it: assets by debits less credits, liabilities and revenue by credits less debits.
    public long Balance(string account) { lock (_gate) return Natural(account); }
    private long Natural(string account) => _kinds[account] == Kind.Asset ? _debitMinusCredit[account] : -_debitMinusCredit[account];

    // Posts a transaction once. A repeat of the same id returns the first result and changes nothing. `noOverdraft` names liability
    // accounts (customer wallets) that must not go below zero, and the check and the write happen under one lock.
    public bool Post(string txId, IReadOnlyList<Line> lines, params string[] noOverdraft)
    {
        lock (_gate)
        {
            if (_posted.ContainsKey(txId)) return true;
            if (lines.Count < 2 || lines.Sum(l => l.Amount) != 0 || lines.Any(l => !_kinds.ContainsKey(l.Account))) throw new ArgumentException("unbalanced or unknown account");
            foreach (var account in noOverdraft)
                if (Natural(account) - lines.Where(l => l.Account == account).Sum(l => l.Amount) < 0) return false;
            foreach (var l in lines) _debitMinusCredit[l.Account] += l.Amount;
            var posted = new Posted(txId, lines.ToList());
            _posted[txId] = posted;
            _journal.Add(posted);
            return true;
        }
    }

    // A correction is a new transaction that mirrors the old one.
    public bool Reverse(string txId) { lock (_gate) return Post(txId + ":reversal", _posted[txId].Lines.Select(l => l with { Amount = -l.Amount }).ToList()); }

    // Recomputes every balance from the journal, which is what an audit does, and compares it with the running balances.
    public bool Audit()
    {
        lock (_gate)
        {
            var sums = _kinds.Keys.ToDictionary(a => a, _ => 0L);
            foreach (var tx in _journal) foreach (var l in tx.Lines) sums[l.Account] += l.Amount;
            return sums.All(kv => _debitMinusCredit[kv.Key] == kv.Value) && _debitMinusCredit.Values.Sum() == 0;
        }
    }

    public long Total(Kind kind) { lock (_gate) return _kinds.Where(k => k.Value == kind).Sum(k => Natural(k.Key)); }
    public int Transactions { get { lock (_gate) return _journal.Count; } }
}

The sample posts 100,000 deposits, transfers with a fee and withdrawals across 50 wallets, refuses overdrafts, sends every accepted id a second time with different lines (a retry that must change nothing), and then audits. After that it corrects a mistake by reversal, and runs the overdraft race that the next section discusses.

C#66 lines
using System;
using System.Diagnostics;
using System.Linq;
using System.Threading;

var ledger = new Ledger();
ledger.Open("bank", Kind.Asset);
ledger.Open("fees", Kind.Revenue);
for (int w = 0; w < 50; w++) ledger.Open("wallet:" + w, Kind.Liability);

// Deposits, transfers with a fee and withdrawals, 100,000 of them. Overdrafts are refused, and every accepted id is sent again once (a retry).
var ops = new Random(6);
int refused = 0;
for (int i = 0; i < 100_000; i++)
{
    int a = ops.Next(50), b = ops.Next(50);
    long amount = 1 + ops.Next(5_000);
    string tx = "tx" + i;
    bool ok;
    switch (ops.Next(3))
    {
        case 0: ok = ledger.Post(tx, new[] { new Line("bank", amount), new Line("wallet:" + a, -amount) }); break;                                               // deposit
        case 1: ok = ledger.Post(tx, new[] { new Line("wallet:" + a, amount + 2), new Line("wallet:" + b, -amount), new Line("fees", -2) }, "wallet:" + a); break;  // transfer plus a fee of 2
        default: ok = ledger.Post(tx, new[] { new Line("wallet:" + a, amount), new Line("bank", -amount) }, "wallet:" + a); break;                                 // withdrawal
    }
    if (!ok) { refused++; continue; }
    long before = ledger.Balance("bank");
    Debug.Assert(ledger.Post(tx, new[] { new Line("bank", 1), new Line("fees", -1) }) && ledger.Balance("bank") == before);   // a retry, even with different lines, changes nothing
}
Console.WriteLine($"{ledger.Transactions} transactions, {refused} refused, bank {ledger.Balance("bank")}, wallets {ledger.Total(Kind.Liability)}, fees {ledger.Balance("fees")}");
Debug.Assert(ledger.Audit());                                                                    // the journal reproduces every balance, and debits equal credits
Debug.Assert(ledger.Balance("bank") == ledger.Total(Kind.Liability) + ledger.Total(Kind.Revenue));  // assets = liabilities + revenue
Debug.Assert(Enumerable.Range(0, 50).All(w => ledger.Balance("wallet:" + w) >= 0));
try { ledger.Post("bad", new[] { new Line("bank", 10), new Line("fees", -9) }); Debug.Fail("an unbalanced transaction was accepted"); } catch (ArgumentException) { }

// A mistake is corrected by posting the reverse, never by editing: the balances return to where they were.
long bankBefore = ledger.Balance("bank"), walletBefore = ledger.Balance("wallet:7");
ledger.Post("oops", new[] { new Line("bank", 500), new Line("wallet:7", -500) });
Debug.Assert(ledger.Balance("wallet:7") == walletBefore + 500);
ledger.Reverse("oops");
Debug.Assert(ledger.Balance("bank") == bankBefore && ledger.Balance("wallet:7") == walletBefore && ledger.Audit());

// Check, then act: two withdrawals both read a balance of 10 before either writes, so both go through and the wallet ends at -10.
long naiveBalance = 10;
bool firstSees = naiveBalance >= 10, secondSees = naiveBalance >= 10;
if (firstSees) naiveBalance -= 10;
if (secondSees) naiveBalance -= 10;
Console.WriteLine($"check-then-act overdraft: balance {naiveBalance}");
Debug.Assert(naiveBalance == -10);

// With the check inside the same lock as the write, eight threads withdrawing 10 at a time from a wallet holding 1,000 get exactly 100.
ledger.Open("wallet:race", Kind.Liability);
ledger.Post("seed", new[] { new Line("bank", 1_000), new Line("wallet:race", -1_000) });
int accepted = 0;
var gate = new ManualResetEventSlim(false);
var threads = Enumerable.Range(0, 8).Select(t => new Thread(() =>
{
    gate.Wait();
    for (int n = 0; n < 200; n++)
        if (ledger.Post($"w{t}-{n}", new[] { new Line("wallet:race", 10), new Line("bank", -10) }, "wallet:race")) Interlocked.Increment(ref accepted);
})).ToList();
threads.ForEach(t => t.Start());
gate.Set();
threads.ForEach(t => t.Join());
Console.WriteLine($"locked check and write: {accepted} withdrawals accepted, balance {ledger.Balance("wallet:race")}");
Debug.Assert(accepted == 100 && ledger.Balance("wallet:race") == 0 && ledger.Audit());

Of the 100,000 attempts, 97,425 posted and 2,575 were refused for insufficient funds. The bank account ended at 4,529,437, which is the wallets' 4,465,145 plus 64,292 of fees: the accounting equation held to the unit. The properties the sample asserts are the ones to name in an interview:

  • Every transaction balances, and an unbalanced one is rejected before anything is written.
  • A transaction id posts once. The retry carried different lines and changed nothing, because the id had already been posted. In production a retry with the same id and different content should be an error, not a silent no-op.
  • The journal reproduces every balance. The audit recomputes each account from the entries and compares it with the running balance, so a bug in the fast path is caught by the slow one.
  • Mistakes are reversals. Posting the mirror image restored the balances and the audit still passed. History only grows.

LLD

Deep dive: two withdrawals at once

The race is the oldest bug in money code. Two withdrawals of 10 hit a wallet holding 10. Each reads the balance, sees enough, and writes the new balance, and the wallet ends at minus 10. The scripted interleaving in the sample shows it with no threads at all. Any design that reads a balance, decides, and writes later is exposed, and a database running at snapshot isolation does not save it either, because both transactions read the same snapshot (the write skew anomaly in transactions and isolation).

The fix is to make the check and the write one atomic step. In a database there are four common ways:

sql
-- 1. A conditional update: the check is part of the write, and the row count says whether it applied.
UPDATE accounts SET balance = balance - 10, version = version + 1
WHERE id = 'wallet:7' AND balance >= 10;

-- 2. A row lock: read under the lock, decide, write, commit.
SELECT balance FROM accounts WHERE id = 'wallet:7' FOR UPDATE;

-- 3. Optimistic: write only if nobody changed the row since the read, and retry on a miss.
UPDATE accounts SET balance = :new, version = version + 1 WHERE id = 'wallet:7' AND version = :seen;

The fourth is to serialize per account: make one worker the only writer of an account (an actor, a partition owner), so operations on it run one at a time and the check is trivially safe. The sample uses the simplest version, a lock around check and write. Eight threads each tried 200 withdrawals of 10 from a wallet holding 1,000, 1,600 attempts in all, and exactly 100 were accepted, whichever thread got there first. The balance ended at zero and the audit passed.

A related need is the hold. A card authorization or a pending withdrawal reserves money without spending it. Model it in the ledger itself: a hold moves the amount from the customer's available account to a held account in one balanced transaction, a capture moves it from held to the merchant, and a release moves it back. The available balance is then simply the balance of one account, and the held money is visible and auditable, and no separate table of holds has to be kept in step with the balances.

LLD

Deep dive: money is not a float

A binary float cannot hold a tenth. Ten payments of 0.10 sum to 0.9999999999999999, and the error grows with volume. Money is stored as an integer count of the currency's smallest unit (cents), together with the currency code. The exponent depends on the currency (most have two decimals, the yen none and the Kuwaiti dinar three), so a hard-coded "multiply by 100" is a bug waiting for a customer in another country. Two more rules need code: a stated rounding rule, and allocation that never creates or loses a unit.

C# · Money24 lines
using System;
using System.Collections.Generic;
using System.Linq;

public static class Money
{
    // Minor units per currency (ISO 4217): most currencies have 2 decimals, the yen has none and the Kuwaiti dinar has 3.
    private static readonly Dictionary<string, int> Exponent = new() { ["USD"] = 2, ["EUR"] = 2, ["JPY"] = 0, ["KWD"] = 3 };

    // A decimal amount as an integer of minor units. The rounding rule is a policy, and half-to-even avoids a bias on halves.
    public static long ToMinor(decimal amount, string currency) =>
        (long)Math.Round(amount * (decimal)Math.Pow(10, Exponent[currency]), MidpointRounding.ToEven);

    // Splits a non-negative amount of minor units in proportion to the weights so that the parts add up to the whole. Each part
    // gets the floor of its share, and the units left over go to the parts with the largest remainders (largest remainder method).
    public static long[] Allocate(long total, params int[] weights)
    {
        long sum = weights.Sum(w => (long)w);
        var parts = weights.Select(w => total * w / sum).ToArray();
        long left = total - parts.Sum();
        foreach (int i in Enumerable.Range(0, weights.Length).OrderByDescending(i => total * weights[i] % sum).ThenBy(i => i).Take((int)left)) parts[i]++;
        return parts;
    }
}
C# · A float cannot hold a tenth: ten payments of 0.10 do not add up to 1.00, and the error…37 lines
using System;
using System.Diagnostics;
using System.Linq;

// A float cannot hold a tenth: ten payments of 0.10 do not add up to 1.00, and the error grows with volume.
double floatSum = 0;
for (int n = 0; n < 10; n++) floatSum += 0.1;
long centSum = 0;
for (int n = 0; n < 10; n++) centSum += 10;
Console.WriteLine($"ten times 0.1 as a double: {floatSum:R}, ten times 10 cents as an integer: {centSum}");
Debug.Assert(floatSum != 1.0 && centSum == 100);

// Minor units depend on the currency, and the rounding rule on halves is a decision.
Debug.Assert(Money.ToMinor(19.99m, "USD") == 1_999 && Money.ToMinor(1_999m, "JPY") == 1_999 && Money.ToMinor(1.234m, "KWD") == 1_234);
Debug.Assert(Money.ToMinor(0.125m, "USD") == 12 && Money.ToMinor(0.135m, "USD") == 14);          // half to even: 12.5 goes to 12, 13.5 to 14

// Splitting 100.00 three ways: rounding each share loses a cent, allocation does not.
long[] naiveShares = Enumerable.Range(0, 3).Select(_ => (long)Math.Round(10_000 / 3.0)).ToArray();
var shares = Money.Allocate(10_000, 1, 1, 1);
Console.WriteLine($"rounded shares {string.Join(" + ", naiveShares)} = {naiveShares.Sum()}, allocated {string.Join(" + ", shares)} = {shares.Sum()}");
Debug.Assert(naiveShares.Sum() == 9_999 && shares.Sum() == 10_000 && shares.SequenceEqual(new long[] { 3_334, 3_333, 3_333 }));

// 100,000 random splits: the naive way is off by whole cents in many of them, the allocation never is, and no part strays more than one unit from its exact share.
var split = new Random(9);
int naiveOff = 0;
for (int n = 0; n < 100_000; n++)
{
    long total = split.Next(1, 1_000_000);
    int[] weights = Enumerable.Range(0, 2 + split.Next(5)).Select(_ => 1 + split.Next(100)).ToArray();
    long weightSum = weights.Sum();
    if (weights.Sum(w => (long)Math.Round((double)total * w / weightSum)) != total) naiveOff++;
    var parts = Money.Allocate(total, weights);
    Debug.Assert(parts.Sum() == total);
    for (int k = 0; k < weights.Length; k++) Debug.Assert(Math.Abs(parts[k] - (double)total * weights[k] / weightSum) < 1);
}
Console.WriteLine($"naive rounding broke the total in {naiveOff} of 100,000 splits, allocation in none");
Debug.Assert(naiveOff > 10_000);

Splitting 100.00 three ways by rounding each share gives 33.33 three times, 99.99 in all, so a cent has disappeared. The largest remainder method gives 33.34, 33.33 and 33.33. Across 100,000 random splits with two to six parties, naive rounding broke the total in 29,630, and allocation in none, with every part within one unit of its exact share. The rules to state:

  • Integers and a currency code, always together. An amount without a currency is a bug, and a transaction must balance within each currency separately. A conversion goes through dedicated accounts at a recorded rate.
  • Decide the rounding rule and say where the remainder goes, whether to the first party, the largest, or a rounding account that collects residue visibly, so that no unit is created or lost.
  • Use decimal or integer arithmetic for rates and taxes, never double, and round once, at the end, by the rule.

LLD

Deep dive: transfers across shards

Accounts are sharded by id, so the two accounts of a transfer can live on different shards. No single transaction spans both, and the three honest options are these. Two-phase commit gives atomicity, but it blocks while its coordinator is down and holds locks across machines, which is poor at this scale (see distributed transactions). Co-location is impossible in general, because any account can pay any other. A saga is a sequence of local transactions, each with a compensating undo, driven by a durable log: the transfer is available and eventually consistent, and with the right structure never loses money.

The structure uses a clearing account on each shard. Step one, on the sender's shard, debits the sender and credits the shard's clearing account. Step two, on the receiver's shard, debits that shard's clearing account and credits the receiver. Each step is a balanced local transaction, so every shard's books balance at every instant. Across shards, the money in flight sits in the clearing accounts, and the wallets plus what is in flight stay constant. If step two cannot happen (the receiver's account is frozen), an undo on the sender's shard reverses step one.

Every step posts under its own transaction id (t1:debit, t1:credit, t1:undo), so a step repeated after a crash is a no-op. That is the whole trick: at-least-once execution plus idempotent steps gives exactly-once effects. The code below is the saga driver. A crash can strike before a step, or after the ledger changed but before the saga log says so.

C# · SagaState, Saga, Crash, …59 lines
using System;
using System.Collections.Generic;
using System.Linq;

public enum SagaState { Started, Debited, Done, Refused, Undone }
public sealed class Saga { public string Id, From, To; public long Amount; public SagaState State = SagaState.Started; }
public sealed class Crash : Exception { }

// A transfer between wallets that live on two different ledgers (shards). No transaction spans both, so the transfer is a saga: a
// debit on the sender's shard into a clearing account, then a credit on the receiver's shard out of its clearing account, with an
// undo on the sender's shard if the receiver cannot accept. Every step posts under its own transaction id, so doing it twice is safe.
public sealed class Transfers
{
    private readonly Ledger _a, _b;
    private readonly Dictionary<string, Saga> _log = new();                  // the saga log; in production it is durable
    private readonly Random _random;
    private readonly double _crashRate;
    public readonly HashSet<string> Frozen = new();                          // receivers that cannot be credited
    public int Crashes { get; private set; }

    public Transfers(Ledger a, Ledger b, Random random, double crashRate) { _a = a; _b = b; _random = random; _crashRate = crashRate; }

    public IEnumerable<Saga> Sagas => _log.Values;

    public void Start(string id, string from, string to, long amount) => _log[id] = new Saga { Id = id, From = from, To = to, Amount = amount };

    private void MaybeCrash() { if (_random.NextDouble() < _crashRate) { Crashes++; throw new Crash(); } }

    // Moves one saga forward by one step. A crash can strike before a step, or after the ledger was changed but before the saga
    // log says so, and the next call simply repeats the step.
    public void Step(string id)
    {
        var s = _log[id];
        switch (s.State)
        {
            case SagaState.Started:
                MaybeCrash();
                bool debited = _a.Post(id + ":debit", new[] { new Line(s.From, s.Amount), new Line("clearing", -s.Amount) }, s.From);
                MaybeCrash();
                s.State = debited ? SagaState.Debited : SagaState.Refused;    // refused for lack of funds: nothing to undo
                break;
            case SagaState.Debited:
                MaybeCrash();
                if (Frozen.Contains(s.To))
                {
                    _a.Post(id + ":undo", new[] { new Line("clearing", s.Amount), new Line(s.From, -s.Amount) });        // compensate
                    MaybeCrash();
                    s.State = SagaState.Undone;
                }
                else
                {
                    _b.Post(id + ":credit", new[] { new Line("clearing", s.Amount), new Line(s.To, -s.Amount) });
                    MaybeCrash();
                    s.State = SagaState.Done;
                }
                break;
        }
    }
}

The experiment opens two shards with 100 wallets each (one sender nearly empty, two receivers frozen), starts 20,000 random transfers, and drives them with a crash probability of 10% at every point where the process could die. After each crash the driver just comes back, and the saga log says where to resume.

C# · Two shards with 100 wallets each, nearly all opened with 1,000,000. Each shard has a…51 lines
using System;
using System.Diagnostics;
using System.Linq;

// Two shards with 100 wallets each, nearly all opened with 1,000,000. Each shard has a clearing account for money in transit.
Ledger NewShard(string name)
{
    var shard = new Ledger();
    shard.Open("bank", Kind.Asset);
    shard.Open("clearing", name == "A" ? Kind.Liability : Kind.Asset);       // A owes the clearing system what it has sent, B is owed what it has received
    for (int w = 0; w < 100; w++)
    {
        long opening = name == "A" && w == 0 ? 5_000 : 1_000_000;                         // one sender is nearly empty
        shard.Open($"{name}{w}", Kind.Liability);
        shard.Post("open-" + w, new[] { new Line("bank", opening), new Line($"{name}{w}", -opening) });
    }
    return shard;
}
var shardA = NewShard("A");
var shardB = NewShard("B");
long WalletTotal() => shardA.Total(Kind.Liability) - shardA.Balance("clearing") + shardB.Total(Kind.Liability);
long InFlight() => shardA.Balance("clearing") - shardB.Balance("clearing");
const long TotalMoney = 199 * 1_000_000 + 5_000;
Debug.Assert(WalletTotal() + InFlight() == TotalMoney);

var sagaRandom = new Random(14);
var transfers = new Transfers(shardA, shardB, sagaRandom, crashRate: 0.10);
transfers.Frozen.Add("B7"); transfers.Frozen.Add("B42");
for (int i = 0; i < 20_000; i++)
    transfers.Start("t" + i, "A" + sagaRandom.Next(100), "B" + sagaRandom.Next(100), 1 + sagaRandom.Next(3_000));

// Drive every saga, crashing at random. After each crash the driver just comes back: the saga log says where to resume.
int rounds = 0, checks = 0;
while (transfers.Sagas.Any(s => s.State is SagaState.Started or SagaState.Debited))
{
    rounds++;
    foreach (var s in transfers.Sagas.Where(s => s.State is SagaState.Started or SagaState.Debited).ToList())
    {
        try { transfers.Step(s.Id); } catch (Crash) { }
        if (++checks % 997 == 0) Debug.Assert(WalletTotal() + InFlight() == TotalMoney);    // conserved at every instant, crashes included
    }
}
int doneCount = transfers.Sagas.Count(s => s.State == SagaState.Done), refusedCount = transfers.Sagas.Count(s => s.State == SagaState.Refused), undoneCount = transfers.Sagas.Count(s => s.State == SagaState.Undone);
Console.WriteLine($"{transfers.Crashes} crashes over {rounds} rounds; done {doneCount}, refused {refusedCount}, undone {undoneCount}");
Console.WriteLine($"money {WalletTotal() + InFlight()}, in flight {InFlight()}, audits {shardA.Audit()} {shardB.Audit()}");
Debug.Assert(WalletTotal() + InFlight() == TotalMoney && InFlight() == 0 && shardA.Audit() && shardB.Audit());
Debug.Assert(Enumerable.Range(0, 100).All(w => shardA.Balance($"A{w}") >= 0));
// However many times a step was repeated after a crash, each was posted once: a debit and a credit per completion, a debit and an
// undo per compensation, nothing for a refusal.
Debug.Assert(shardA.Transactions == 100 + doneCount + 2 * undoneCount && shardB.Transactions == 100 + doneCount);
Debug.Assert(doneCount + refusedCount + undoneCount == 20_000 && refusedCount > 0 && undoneCount > 0);

The run had 9,343 crashes and needed 9 recovery rounds. 19,401 transfers completed, 185 were refused because the nearly empty sender could not cover them, and 414 were undone because the receiver was frozen. Throughout, wallets plus in-flight money equalled the 199,005,000 that was put in, checked at sampled instants including the moments right after crashes, and at the end nothing was left in flight and both ledgers audited clean. The transaction counts show that no step was posted twice: shard A holds 100 opening transactions plus one debit per completion and a debit and an undo per compensation, and shard B holds 100 plus one credit per completion.

What makes a saga safe in a real system:

  • Write intent, do the step, record progress. The saga log is durable and lives apart from the ledgers, so a step and its log entry are not atomic, and the design accepts that by making the step idempotent.
  • Order the steps by risk. Put the step that can fail (a debit with a balance check) first, where an undo is possible, and the step that must eventually succeed (credit an existing account) last, where the saga can only retry. Business rejections such as a frozen receiver should be checked before the money moves where possible. If one must happen late, the undo has to be designed so that it cannot fail.
  • Never show "failed" while in doubt. The sender sees "pending" until the saga reaches a final state. Alert on the age of the oldest unfinished saga.
  • Know the alternatives. Try-confirm-cancel reserves funds in a try step, then confirms or cancels, which is the hold pattern above applied across shards. Two-phase commit is for small, tightly coupled groups of shards.

HLD

Hot accounts, balance reads and pending money

  • A hot account serializes on its lock. A merchant credited 1,000 times a second cannot be one row. Split it into several sub-accounts (16, say). Each credit goes to one of them, chosen at random or by payment id, so credits no longer contend, and the merchant's balance is the sum of the sub-accounts, read together or swept periodically into a main account that payouts debit. The cost is that an overdraft check on a merchant must look across the sub-accounts, so the technique suits accounts that mostly receive money.
  • Batching is the other cure. Coalesce the credits of one second into one net entry per merchant, and keep the individual payments in a detail table that points at it. The ledger stays small and the detail stays available.
  • Keep balances fast to read. The running balance lives in the account row and is updated in the same transaction as the entries. A cache keyed by the account's version avoids stale reads, and a follower replica can lag, so a user who just paid must read their own write from the primary or see a pending marker.
  • Available and pending are different numbers. Available is what can be spent now, pending includes holds and transfers in flight, and the app should show both rather than a balance that jumps.
  • Checkpoint for audits. A snapshot of every balance at the end of each day lets an audit recompute a day from the journal instead of the whole history.

HLD

Audit, immutability and time

  • Immutability is enforced, not hoped for. The service's database role has no permission to update or delete entries, old partitions move to write-once storage, and for tamper evidence each entry can carry a hash of the one before it, so that a rewrite breaks the chain.
  • Corrections are reversals that reference the original, so an auditor sees the mistake, its correction and who posted each.
  • A continuous auditor recomputes balances from the journal per account and day, checks that every transaction sums to zero and that assets equal liabilities plus revenue, and alerts on any difference. It also compares the ledger with the outside world: bank statements and the provider reports from the payments lesson.
  • Two clocks. Each entry has a posting time (when the system wrote it) and an effective date (the accounting day it belongs to). A back-dated adjustment changes the second and never the first, closed periods refuse new postings, and day boundaries follow the legal entity's time zone.
  • Customer funds map to real money. For a wallet, the sum of customer balances must equal the money held in the bank accounts that back it. That is the most important reconciliation the business has.

HLD

Failure modes and edge cases

CaseWhat goes wrongHandle it
Two withdrawals raceA negative balanceCheck and write in one atomic step: a conditional update, a row lock, or a single writer per account
A client retries a transferMoney moves twiceAn idempotency key and a unique transaction id, and a retry with different content is an error
A crash between the debit and the creditMoney is in limboA saga log, idempotent steps and a recovery sweep. In flight is visible in clearing accounts
The receiver cannot acceptThe sender is out of pocketA compensating undo that is designed to always succeed
A step is applied twice after a crashA double debitA transaction id per step. Count transactions per saga state in a test
The running balance drifts from the journalWrong balances shownA continuous audit, a correcting entry, and a root-cause investigation
A hot merchant accountLock contention, slow paymentsSub-accounts, batching of credits
An unbalanced transactionMoney created or destroyedReject it before writing, and enforce it again with a check at the storage layer
Rounding leftoversCents appear or vanishLargest remainder allocation, and a visible rounding account
A wrong or mixed currencyA nonsense totalCurrency on every amount, balance per currency, conversion through accounts at a recorded rate
A back-dated entry in a closed periodReports change after they were issuedEffective dates, closed periods that refuse postings, an adjustment in the open period
A manual database editHistory that cannot be trustedNo update or delete permission, change control, and the audit

Senior depth

What senior interviews ask about a ledger and a wallet

Interviewer follow-upL5Why double-entry instead of just updating balances?How to answer

Because every movement has two sides, and recording both gives a built-in check: the entries of every transaction sum to zero, so money cannot appear or vanish without the check failing. It also gives history (each balance is the sum of what happened), a place for every unit of money (the other side of a top-up is the bank), and an audit that recomputes the balances from the journal. In the test the books satisfied assets equal liabilities plus revenue after 100,000 transactions.

Interviewer follow-upL5How do you prevent overdrafts when two withdrawals race?How to answer

Make the check and the write one atomic step. A conditional update (balance >= amount in the WHERE clause), a row lock, or a single writer per account all work, and a plain read followed by a write does not, even at snapshot isolation. In the test a check-then-act left a balance of minus 10, and a locked check let exactly 100 of 1,600 withdrawals of 10 through a balance of 1,000.

Interviewer follow-upL5Why integers for money, and what about rounding?How to answer

Floats cannot represent a tenth, so errors creep in (ten times 0.10 was 0.9999999999999999). Store integer minor units with a currency code, because the number of decimals differs by currency. Choose and state a rounding rule (half to even avoids a bias), and allocate splits by the largest remainder method so no unit is created or lost: naive rounding broke the total in 29,630 of 100,000 random splits.

Interviewer follow-upL6How do you transfer between accounts on different shards?How to answer

With a saga: debit the sender on their shard into a clearing account, then credit the receiver from their shard's clearing account, with an undo if the second step cannot happen. A durable log records progress, and every step has its own transaction id, so repeating it after a crash is harmless. Wallets plus money in flight stay constant, and in the test 9,343 crashes lost nothing and posted no step twice. Two-phase commit is the alternative, and it blocks on coordinator failure.

Interviewer follow-upL6What does idempotency look like in a ledger?How to answer

A unique transaction id per posting (and per saga step), so a retry returns the first result and writes nothing. A repeat with the same id and different content is a conflict and should be rejected loudly, because it means a caller has a bug. Idempotency keys at the API map to transaction ids, so a client retry and a recovery sweep are the same event to the ledger.

Interviewer follow-upL6How do you handle a hot account?How to answer

Split it into sub-accounts so credits do not contend on one row, and sum them when reading or sweep them into a main account that payouts use. Alternatively batch the credits of a short interval into one net entry and keep the detail elsewhere. State the cost: overdraft checks across sub-accounts are harder, so the technique fits accounts that mostly receive.

Interviewer follow-upL6How do you keep balances fast to read and still correct?How to answer

Keep a running balance in the account row, updated in the same transaction as the entries, and treat it as a cache of the journal. An audit job recomputes balances from the entries and compares, and daily checkpoints bound the work. For reads right after a write, use the primary or show a pending marker, since replicas lag.

Interviewer follow-upL6How do you model a card authorization hold?How to answer

As a transfer inside the ledger: move the amount from the customer's available account to a held account. A capture moves it from held to the merchant, and a release moves it back. Available stays a single account balance, held money is visible and auditable, and expiry is a scheduled release.

Interviewer follow-upL7How would you prove the ledger is correct?How to answer

Invariants that run continuously: every transaction sums to zero, the journal reproduces every running balance, assets equal liabilities plus revenue, clearing accounts net to zero once sagas finish, and customer balances equal the money in the backing bank accounts. Add the reconciliation with banks and providers, append-only storage with tamper-evident hashing, and tests that inject crashes and races the way the experiments above do.

Interviewer follow-upL7How would you migrate the ledger to a new database or schema without downtime?How to answer

The immutable journal makes it tractable, since it can be replayed. Backfill the new store from the journal, dual-write new postings to both, shadow-read and compare balances per account, fix differences, then cut over account groups gradually, with the old store read-only as the fallback. The auditor runs against both until they agree for a full period.

HLD

How to present this design in an interview

  1. Clarify: ledger or wallet or both, operations, whether balances can go negative, currencies, consistency, audit.
  2. Estimate: thousands of transfers a second, a few terabytes of entries a year, hot accounts as the real scaling problem.
  3. Model it as double-entry: accounts, an immutable journal, transactions whose entries sum to zero, running balances as a cache, a transaction id that posts once.
  4. Draw it: API, transfer service, account directory, ledger shards, saga log, outbox, auditor.
  5. Go deep on the race: a check-then-act overdraw against an atomic check and write.
  6. Go deep on money: integer minor units, currency exponents, rounding policy, largest remainder allocation.
  7. Go deep on cross-shard transfers: clearing accounts, a saga with idempotent steps, compensation, recovery after crashes.
  8. Scale it: sub-accounts for hot accounts, running balances, checkpoints, pending and available.
  9. Close with proof: the invariants, the continuous audit, reconciliation with banks, and what you would never allow (edits, deletes, floats).

Summary

A ledger records money as an append-only journal of balanced double-entry transactions, each posted once under its id, with running balances as a fast cache that an audit can re-derive. In the test, 100,000 transactions left debits equal to credits and assets equal to liabilities plus revenue, a retry changed nothing, and a reversal restored the balances. Withdrawals must check and write atomically: a check-then-act overdrew a wallet, and a locked check let through exactly 100 of 1,600 attempts. Money is an integer of minor units with a currency code, with a stated rounding rule and largest remainder allocation, because naive rounding broke the total in 29,630 of 100,000 splits. Transfers across shards are sagas through clearing accounts with idempotent steps and compensations: 9,343 crashes lost no money and posted no step twice. Hot accounts are split into sub-accounts or batched, balances are read from running totals, and the auditor and reconciliation with banks prove the system is correct.

Check yourself

Try answering out loud before you reveal each answer.

QuestionTwo withdrawals of 10 hit a wallet holding 10 at the same moment. What goes wrong, and what are the fixes?Reveal answer

Each reads the balance, sees enough and writes, so both succeed and the wallet is at minus 10, even at snapshot isolation. Make the check and the write one atomic step: a conditional update with the balance in the WHERE clause, a row lock, or a single writer per account. In the test, eight threads attempting 1,600 withdrawals of 10 against 1,000 got exactly 100, and the balance ended at zero.

QuestionWhy is each ledger transaction required to balance, and what do you gain from the journal being append-only?Reveal answer

Because balancing makes money conserved: it moves between accounts and never appears or vanishes, and the sum of all entries must be zero, which is a check you can run any time. Append-only history means a balance can always be recomputed and explained, mistakes are corrected by reversing entries that stay visible, and an auditor or a migration can replay the journal. The audit in the test recomputed every balance and matched the running ones.

QuestionHow do you split 100.00 among three parties, and why not round each share?Reveal answer

Give each party the floor of its share and hand the leftover units to the parts with the largest remainders (33.34, 33.33, 33.33). Rounding each share gives 33.33 three times and loses a cent, and across 100,000 random splits naive rounding broke the total 29,630 times. Store integer minor units with the currency, since the number of decimals differs by currency, and state the rounding rule.

QuestionA transfer between two shards crashes after debiting the sender and before crediting the receiver. What happens?Reveal answer

The money is in the sender shard's clearing account, visible as in flight, and the saga log says the transfer is in the debited state. The recovery driver repeats the next step, the credit on the receiver's shard, under its own transaction id, so a repeat is a no-op. If the receiver cannot accept, an undo reverses the debit. In the test 9,343 crashes ended with nothing in flight, the books balanced and no step posted twice.

Sources and further reading

Lesson 31 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 32Case study: design a distributed cacheA senior-level walkthrough of a Memcached or Redis-style cache cluster: sizing it, a node's memory and expiry, placement that survives adding a node, and what a lost node does to the database, with tested C#.

Send a message

It goes straight to my inbox. I usually reply within a few days.