Design a Digital Wallet

How a digital wallet keeps balances correct using a ledger, idempotent transfers and cross-shard sagas, and what interviewers ask about it.

Case study25 minLesson 7 of 7
On this page
  1. Clarify the problem
  2. Estimate the scale
  3. Define the API (optional)
  4. Model the data
  5. High-level design
  6. Deep dives
  7. Bottlenecks and failures
  8. What a strong answer sounds like
  9. Follow-up questions

A digital wallet stores a money balance for each user. Users add money from a card, send money to other users, and look at their balance and history. The hard part is correctness: a balance must never go below zero, a retried request must not move money twice, and every cent must be traceable to ledger entries that add up.

This builds on the idempotency keys and ledger rules from Design a Payment System. Here both sides of a transfer are accounts you hold, and at scale they sit in different database shards, so the question is how to move money between your own databases without creating or losing any. The steps follow A Framework for Any Design.

Clarify the problem

The first five minutes
Interviewer

Design a digital wallet.

You

Users top up from a card, send money to each other, and see their balance and history. Do we need bank withdrawals or more than one currency?

Interviewer

One currency only, and withdrawals can wait. Top-ups go through an existing payment system.

You

How many users and transfers should I plan for?

Interviewer

Assume 100 million wallets, about 50 million transfers and 5 million top-ups a day.

You

Then I will treat three rules as exact: a balance never goes below zero, a retried transfer moves money only once, and every cent traces to ledger entries that balance. I would rather reject a transfer than break one of those rules. A recipient seeing the money a second late is acceptable.

  • Functional: a user can top up from a card, send money to another user, and view their balance and a paged history.
  • Non-functional: the three rules above hold even under concurrent requests, no acknowledged transfer is ever lost, the ledger is append-only, a send is answered within about 500 ms, and the recipient is credited within a few seconds.
  • Out of scope: withdrawals, multiple currencies, fraud detection, spending limits, and card processing, which belongs to the payment system.

Estimate the scale

Top-ups are 5 million ÷ 86,400 ≈ 60 a second. Balance reads come from about 300 million app opens a day, which is ≈ 3,500 single-row reads a second. A single relational primary can handle about 5,000 short write transactions a second, so the peak transfer rate below tells us whether one primary is enough.

Estimate: Peak transfer rate

About how many transfers a second must the wallet handle at a 5x peak?

You know
  • 50 million transfers a day
  • A day is 86,400 seconds
  • Peaks run 5 times the average

Show the working
  1. 50 × 106 ÷ 86,400 ≈ 580 a second
  2. 580 × 5 ≈ 2,900, which rounds to 3,000 a second

Estimate 3 thousand/s (anything from 1 thousand/s to 10 thousand/s is a good answer)

A single primary handles about 5,000 short transactions a second, which covers 3,000 transfers a second, so the first design can use one database.

Your turn: Define the API

Write the endpoints for top-up, send, balance and history. Who creates the id that makes a retried send harmless, and when?

Compare with a model answer

The app creates the id when the user taps Send, before the first network call. The server stores it as the transfer's primary key, so a retry cannot become a second transfer.

Define the API Optional

Optional in the interview. Sketch the API only if the interviewer asks, if an API choice shapes the design, or if time permits. Otherwise say "I'll skip the detailed API unless you want it" and go to the data model.

HTTP API
POST /v1/topups            Idempotency-Key: tp-6f1c
  body: { "amount_cents": 5000, "payment_method": "pm_..." }
  201 { "topup_id": "tp-6f1c", "status": "processing" }
 
POST /v1/transfers
  body: { "transfer_id": "t-81", "to_user": "bob", "amount_cents": 2000, "note": "dinner" }
  201 { "transfer_id": "t-81", "status": "sent" }
  200 { "transfer_id": "t-81", "status": "sent" }       this transfer_id was already processed
  409 { "error": "insufficient_funds", "balance_cents": 1000 }
  422 the same transfer_id was sent with a different body
  404 the recipient does not exist
 
GET /v1/wallet
  200 { "balance_cents": 1000, "as_of_entry": 99812 }
 
GET /v1/wallet/history?before=99812&limit=50
  200 { "entries": [ { "transfer_id": "t-81", "amount_cents": -2000,
                       "balance_after": 1000, "at": "..." }, ... ], "next": "99761" }

The decision worth arguing is when the API says a transfer is "sent": once the money has left Alice's balance, not once it has reached Bob's. From then on the transfer cannot be lost, because it either completes or is reversed to Alice. Waiting for Bob's side would add a second database to every send without making it safer. A retry with the same transfer id returns the stored result instead of debiting again, and a reused id with a different body gets a 422. Amounts are integer cents, because floating point cannot represent most decimals exactly.

Your turn: Model the data

Sketch the records. Is the balance a stored column or computed from entries? Where do the ledger entries of one transfer live if Alice and Bob are on different shards?

Compare with a model answer

The ledger entries are the source of truth, and the balance column is a cached sum that is updated in the same transaction. Entries live with their account, so one transfer has entries on two shards, and each shard's half must balance on its own.

Model the data

Per shard; every table is partitioned by wallet
wallets
  wallet_id      VARCHAR(32) PRIMARY KEY
  balance_cents  BIGINT        -- cached sum of ledger_entries, updated in the same transaction
  status         VARCHAR(8)    -- active | frozen
 
ledger_entries                 -- append only
  entry_id       BIGINT PRIMARY KEY
  account_id     VARCHAR(32)   -- "alice", or "transit:shard-A"
  transfer_id    VARCHAR(36)
  amount_cents   BIGINT        -- change to that account: -2000, +2000
  balance_after  BIGINT        -- lets history and audits skip summing; NULL for transit
  INDEX (account_id, entry_id DESC)
 
transfers                      -- on the sender's shard
  transfer_id    VARCHAR(36) PRIMARY KEY
  from_wallet, to_wallet, amount_cents, request_hash
  status         VARCHAR(10)   -- sent | completed | reversed
 
applied_credits                -- on the receiver's shard
  transfer_id    VARCHAR(36) PRIMARY KEY
  outcome        VARCHAR(8)    -- credited | refused
 
outbox                         -- on the sender's shard
  transfer_id, payload, created_at

Every operation is a short transaction over a few rows: a conditional debit, two ledger entries and a transfer row. This is the access pattern of a relational database with ACID transactions, replicated synchronously so that an acknowledged transfer survives the loss of the primary. When one primary is no longer enough, shard by wallet_id, so that a wallet's balance, entries and history are all on one shard.

Your turn: High-level design

Sketch a send between wallets on different shards. What commits first, what carries the transfer to the second shard, and what happens if the second step can never succeed?

Compare with a model answer

The debit and an outbox message commit together on the sender's shard, a worker then credits the recipient exactly once, and a permanent refusal reverses the debit. Every step is a local transaction that balances on its own.

High-level design

The diagram shows the sharded design for 10x load, while today both legs fit in one database transaction. A top-up is simpler: once the payment system confirms the charge, the wallet service credits Alice from a card-funding account, keyed by the top-up id so that it credits only once.

A send is two local transactions, the debit on the sender's shard and the credit on the receiver's shard, joined by an outbox and a worker.Mobile app to API gateway (send, read); API gateway to Wallet service; Wallet service to Shard A (Alice) (debit leg); Wallet service to Payment system (charge card); Shard A (Alice) to Transfer worker (outbox), asynchronous; Transfer worker to Shard B (Bob) (credit leg).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)Transfer workerShard B (Bob)send, readdebit legcharge cardoutboxcredit leg

request and replyasynchronous message

A send is two local transactions, the debit on the sender's shard and the credit on the receiver's shard, joined by an outbox and a worker.
A send, an overdraft race, a crash and a reversalUse the arrows or ← → keys
  1. A send, an overdraft race, a crash and a reversal, step 1Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)Transfer workerShard B (Bob)
    alice
    3000
    bob
    500
    in transit
    0

    1Alice has $30 and sends $20 to Bob. The app creates the transfer id t-81 first, so any retry carries the same id.

  2. A send, an overdraft race, a crash and a reversal, step 2Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)t-81 sentTransfer workerShard B (Bob)
    alice
    1000
    bob
    500
    in transit
    2000

    2One transaction on shard A inserts t-81, debits Alice only if her balance is at least 2000, writes the entries Alice −2000 and transit:A +2000, and writes an outbox row. This leg balances on its own, and Alice sees the status sent.

  3. A send, an overdraft race, a crash and a reversal, step 3Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile app409 for t-82API gatewayWallet servicePayment systemShard A (Alice)Transfer workerShard B (Bob)
    alice
    1000
    bob
    500
    in transit
    2000

    3At the same moment Alice's tablet sends $20 to Carol as t-82. Its debit waits for the row lock, rechecks the balance (1000 is below 2000), changes 0 rows, and the request returns 409 insufficient funds.

  4. A send, an overdraft race, a crash and a reversal, step 4Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)Transfer workerShard B (Bob)
    alice
    1000
    bob
    500
    in transit
    2000

    4The worker reads t-81 from shard A's outbox and sends the credit leg to shard B.

  5. A send, an overdraft race, a crash and a reversal, step 5Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)Transfer workerShard B (Bob)t-81 applied
    alice
    1000
    bob
    2500
    in transit
    0

    5One transaction on shard B inserts t-81 into applied_credits and writes the entries transit:B −2000 and Bob +2000. The two transit accounts now add up to zero across the shards.

  6. A send, an overdraft race, a crash and a reversal, step 6Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)Transfer workerdownShard B (Bob)duplicate, no-op
    alice
    1000
    bob
    2500
    in transit
    0

    6The worker crashes before it marks t-81 completed, and after the restart it delivers the credit again. The key t-81 already exists in applied_credits, so Bob is not credited a second time. The worker then marks t-81 completed on shard A.

  7. A send, an overdraft race, a crash and a reversal, step 7Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)t-90 sentTransfer workerShard B (Bob)
    alice
    500
    bob
    2500
    in transit
    500

    7Later Alice sends $5 to Dan, whose wallet on shard B has just been frozen. The debit leg commits as before, with Alice −500 and transit:A +500.

  8. A send, an overdraft race, a crash and a reversal, step 8Mobile app to API gateway; API gateway to Wallet service; Wallet service to Shard A (Alice); Wallet service to Payment system; Shard A (Alice) to Transfer worker, asynchronous; Transfer worker to Shard B (Bob).Mobile appAPI gatewayWallet servicePayment systemShard A (Alice)t-90 reversedTransfer workerShard B (Bob)Dan frozen
    alice
    1000
    bob
    2500
    in transit
    0

    8Shard B refuses the credit and records the refusal under t-90, so a late redelivery can never credit Dan. The worker then compensates on shard A with transit:A −500 and Alice +500, and sets the status to reversed.

1 / 8

Deep dives

Moving money between two shards

If wallets are sharded by wallet id across 16 shards, Bob is on Alice's shard only 1 time in 16, so about 94% of transfers cross shards, and there are four ways to handle that.

One database transaction. If both wallets are in the same primary, the debit and the credit are two updates in one transaction, so they commit together or not at all and there is no in-between state. This is the simplest correct design while the load fits. Its limit is that every wallet must live in one primary, which caps writes at about 5,000 transactions a second.

Two-phase commit. A coordinator asks both shards to prepare, meaning to do the work and promise they can commit, and then tells both to commit. This is atomic across shards, but each shard holds its row locks for several network round trips, and if the coordinator fails after the prepare phase both rows stay locked until it returns. You would rarely build it by hand, although some distributed SQL databases run it internally over replicated groups.

Saga with compensation. A saga splits the transfer into local transactions: first the debit on Alice's shard, then the credit on Bob's shard, linked by a durable message. No locks are held across shards, and a shard outage only delays the transfers that need it. The cost is a brief in-between state, and you must build and test the compensating step that reverses the debit.

Event-sourced ledger. Every change is appended to an ordered event log, and balances come from replaying it. The overdraft check then needs all events for one account to be processed in order, and you also need snapshots and consumers that apply each event only once.

Ways to move money between two accounts
OptionGood atBad atPick it when
One database transaction Usual defaultIt is atomic and simple, and no in-between state exists.Every wallet must live in one primary, which caps write throughput.Use it while peak load fits one primary, as 3,000 a second does today.
Two-phase commitBoth shards commit or neither does.Locks are held across network round trips, and a failed coordinator leaves rows locked.Rarely build it by hand; use a distributed SQL database that provides it.
Saga with compensationEach step is a fast local transaction, and a shard outage delays transfers instead of locking rows.An in-between state exists, and the reversal must be built and tested.Use it when the wallets are sharded, which is the case at 10x. This is our design.
Event-sourced ledgerThe ordered log is the truth, and the audit trail is complete.It needs ordered processing per account, snapshots, replays and consumers that handle each event once.Use it for very high throughput, or when a log is already the system of record.

Use one database while it fits, then a saga. Two details make the saga safe. The first is to debit first and credit second. The debit is the only step that normally fails, because the sender may not have enough money, and the rare refused credit, such as to a frozen wallet, has a simple reversal. If you credited first, you could credit Bob and then fail to debit Alice, which creates money from nothing.

The second detail is that each leg balances on its own, through one transit account per shard. Alice's debit is paired with a credit to transit:A, and the second leg moves the money from transit:B to Bob. While a transfer is in flight, transit:A holds +2000. When the credit leg commits, transit:B gets −2000, and the two transit accounts together add up to zero again. Every ledger still sums to zero, and the balance of the transit accounts shows the money in flight.

Two details need care. Transit accounts receive ledger entries only, because a cached balance on one would be the hottest row on the shard. And a refusal must be final: shard B stores it in applied_credits, so a redelivery after Dan is unfrozen cannot credit him after Alice has her money back.

Preventing overdraft under concurrency

Suppose Alice has $30 and two devices each send $20 at the same moment. A service that reads the balance, checks it in code and then writes it lets both requests see 3000 and both succeed, leaving Alice at −$10. The check and the write must be a single atomic step, and there are three ways to get that: lock the row first, make the check part of the update, or check a version number.

Lock the row, then check. The transaction runs SELECT ... FOR UPDATE on Alice's wallet row, checks the balance in code and then updates it. The second request waits for the lock and then sees the new balance.

Conditional update. The check is part of the update, as in the code below: UPDATE ... WHERE balance_cents >= 2000. The database locks the row, so the second debit waits. In PostgreSQL at read committed it then re-evaluates its WHERE clause against the new balance of 1000 and changes no rows. At repeatable read or serializable the second debit fails with a serialization error instead, and the retry sees 1000. Either way there is no overdraft, and the lock is held only for one statement. Name the isolation level you rely on (see Transactions and isolation).

Version check. The service reads the balance and a version number, and writes only if the version is unchanged. This detects a conflict instead of preventing it, so a busy wallet would retry often. The conditional update is therefore the best choice, because it needs one statement and no retry loop.

The debit leg on Alice's shard
BEGIN;
INSERT INTO transfers (transfer_id, from_wallet, to_wallet, amount_cents, status)
     VALUES ('t-81', 'alice', 'bob', 2000, 'sent');      -- duplicate id: stop here
UPDATE wallets SET balance_cents = balance_cents - 2000
 WHERE wallet_id = 'alice' AND balance_cents >= 2000;    -- 0 rows: ROLLBACK, return 409
INSERT INTO ledger_entries ... ('alice', -2000), ('transit:shard-A', +2000);
INSERT INTO outbox (transfer_id, payload) VALUES ('t-81', '...');
COMMIT;

The check must also run on the primary, because a cached or replica balance can be seconds behind.

Ledger, audit and reconciliation

The ledger rules from the payment system apply here: entries sum to zero, entries are never edited, and a mistake is fixed with a reversing entry. Here balance_after also lets anyone verify any point in the history without summing years of rows. These checks run continuously, and any failure pages someone:

  • Per wallet: the cached balance equals the latest balance_after, which equals the sum of all entries. Sample wallets all day, and check every wallet nightly.
  • Per transfer: a transfer that is still sent after a minute is stuck, and a sweeper re-drives it from the outbox.
  • Across shards: all accounts together sum to zero, and the transit accounts sum to the money in flight.
  • Against the outside world: all balances add up to the pooled bank account.

Bottlenecks and failures

At 10x the peak is 30,000 transfers a second. Each cross-shard transfer is two local transactions, so the shards must handle 60,000 transactions a second. At about 5,000 per primary that needs 12 primaries, and 16 shards leaves some headroom. Balance reads rise to 35,000 a second, which replicas can serve.

When this failsWhat happensWhat you do
A wallet service serverRequests in flight fail, but committed debits are safe because their outbox rows are in the database.The app retries with the same transfer id and gets the same answer.
A shard primaryIts wallets pause until the synchronous replica is promoted, and no acknowledged transfer is lost.Its senders get a 503, and credits for its wallets wait in outboxes until failover.
The transfer workerSenders are already debited, recipients are not yet credited, and the transit balance grows.Run several workers over partitioned outboxes, and alert when transfers are stuck.
The payment systemTop-ups stop working.Transfers do not depend on it, so they continue.

What a strong answer sounds like

LevelWhat the answer does
JuniorUses a balance column and updates both rows in one transaction, and handles a double tap once the interviewer raises it.
MidUses idempotent transfer ids, a conditional debit, and a ledger from which balances are derived.
SeniorStarts with one database and says when it stops fitting, points out that most sharded transfers cross shards, chooses a debit-first saga with balanced legs, and defines reconciliation checks.
Crossing shardsStrong answer
Interviewer

Alice and Bob are on different shards. How does the transfer work?

You

With 16 shards, about 94% of transfers are cross-shard, so this is the normal path. I would use a saga. One local transaction debits Alice into a transit account and writes an outbox row, and a worker then credits Bob exactly once, keyed by the transfer id. If Bob's wallet refuses the credit, the worker reverses the debit.

Interviewer

So Alice is debited before Bob is credited?

You

Yes, for a short time, and the transit account shows where the money is. That is the cost of avoiding cross-shard locks. Before we need to shard, I would use a single transaction instead.

Follow-up questions

What breaks when a merchant wallet receives 1,000 credits a second?

The lock on its balance row becomes the bottleneck, because every credit has to update that row in turn. Credits need no balance check, so the service can append entries and fold them into the balance once a second, or split the account into sub-accounts that are summed on read.

How would you add withdrawals to a bank account?

The wallet debits the user into a "payouts pending" account and then calls the bank with an idempotency key. If the bank does not answer before the timeout, the withdrawal stays pending until the bank's records settle it.

How do you prove that the ledger was never edited?

The application account gets insert-only permission on the ledger table, and each entry stores a hash of the previous entry, so any edit breaks the chain after it.

Why not compute the balance from the entries on every read?

An active wallet has thousands of entries, and summing them for 3,500 reads a second is wasteful. The cached balance column is exact because it changes in the same transaction as the entries, and a nightly check verifies it.

How would you support more than one currency?

Each wallet holds one balance per currency, and every ledger entry carries its currency, so entries must sum to zero within each currency. A conversion is a pair of transfers through the company's exchange account, with the rate stored on the transfer.

Self-review: digital wallet0 of 12

After your attempt, tick what you really did. Be strict: "I thought about it" is not "I said it out loud".

Before drawing

Numbers and interfaces

Design and depth

Failure