Skip to content

Design a Digital Wallet

A system design interview walkthrough for a digital wallet, covering balances, a double-entry ledger, atomic transfers between users, sharding and hot accounts.

Advanced24 minUpdated 2 December 2026

Before this: Distributed Transactions (SAGA Pattern), Idempotency

"Design a digital wallet" sounds like a balance column and two buttons. The interviewer is waiting to see what you do with the sentence "move 20 from Alice to Bob". It must debit one account and credit another, never leave the money in neither or both, never let Alice go below zero even if she taps twice, and still work when Alice and Bob live on different database shards.

This question is about balances you hold on behalf of users and moving value between them. It is distinct from Design a Payment System, which is about charging a card through an outside provider and reconciling with it. The wallet is the system of record for the money itself. Top-ups and withdrawals touch the outside world, but the heart of the design is the internal ledger.

Be exact about money in this answer. Use integer minor units, a double-entry ledger, idempotency keys and the phrase effectively once. Background: distributed transactions and idempotency.

Clarify the requirements

Functional requirements:

  1. Each user has a wallet with a balance in one currency (state if multiple currencies are in scope).
  2. Top up from a bank or card, and withdraw to a bank account.
  3. Transfer money to another user instantly.
  4. View balance and transaction history.
  5. Merchants can receive payments into their wallets.

Out of scope, said aloud: identity verification, fraud scoring, currency conversion, card issuing, and regulatory reporting. Holding customers' money is regulated in many places, so name it as a constraint you would check with legal advisors and don't cite specific rules.

Non-functional requirements: these decide the design.

  • Money is conserved. The sum of all balances plus money in transit equals the money that entered the system minus what left. This must be checkable at any time.
  • No negative balances, even under concurrent spends.
  • Transfers are atomic and effectively once. A retry or a crash cannot move the money twice or half.
  • Auditable. Every balance can be explained by a list of entries that can never be altered.
  • Strongly consistent for the owner. After a transfer, the sender's next balance read reflects it.

Estimate the scale

Assume 10 million daily active users, each making 2 transfers a day, and checking their balance 10 times.

Transfers: 10M × 2 = 20M a day ÷ 86,400 ≈ 230 per second, about 1,150 per second at a 5× peak such as a payday or a holiday.

Ledger entries: each transfer writes 2 entries, so 40M a day ≈ 460 writes per second on average.

Balance reads: 10M × 10 = 100M a day ≈ 1,160 per second.

Storage: 40M entries × 150 bytes = 6 GB a day, about 11 TB over five years. Entries are never deleted.

A hot account: a popular merchant might receive 1,000 transfers a second. If each transfer updates the merchant's single balance row, those updates serialize. At 2 to 5 ms each, a single row sustains roughly 200 to 500 updates a second, so 1,000 a second exceeds one row's limit.

"The averages are small: 230 transfers a second. The risks are correctness, that money is never created or lost, and a few hot accounts such as merchants that receive far more updates than one row can take. I need atomic double-entry writes, a way to scale writes to a hot receiver, and a conservation check."

Adjust the assumptions in the capacity estimator, where writes are ledger entries per user per day.

API and data model

POST /v1/transfers    { fromWalletId, toWalletId, amountMinor, currency, note }
                      Idempotency-Key: <client-generated>
                      -> { transferId, status }
GET  /v1/wallets/{id}                -> { balanceMinor, currency, version }
GET  /v1/wallets/{id}/entries?cursor=
POST /v1/topups      { walletId, amountMinor, source }     Idempotency-Key
POST /v1/withdrawals { walletId, amountMinor, destination } Idempotency-Key
wallets  (id PK, owner_id, currency, balance_minor, version, status)   CHECK (balance_minor >= 0)
entries  (transfer_id, line PK, wallet_id, direction, amount_minor, currency, created_at)   append-only
transfers(id PK, idem_key UNIQUE, from_id, to_id, amount_minor, status, created_at)

balance_minor is a cached running total of the wallet's entries, maintained in the same transaction that appends them. The entries are the truth, and the balance makes reads and the no-overdraft check cheap. The CHECK (balance_minor >= 0) is a last line of defense that the database itself enforces.

High-level design

The slice worth running is the transfer path: a gateway, a wallet service, an idempotency store and the ledger database.

Transfers pass a gateway to a wallet service that checks an idempotency store in Redis and posts balanced ledger entries in a Postgres transaction.clientsgatewaywallet apiidempotency keysledger
Transfers pass a gateway to a wallet service that checks an idempotency store in Redis and posts balanced ledger entries in a Postgres transaction.
  • Clients reach the wallet API through a gateway that authenticates the user.
  • The wallet service checks an idempotency store, then posts the transfer's ledger entries in one database transaction.
Describe this diagram

Components

  • clients (Client)
  • gateway (API gateway)
  • wallet api (Service)
  • idempotency keys (Redis)
  • ledger (PostgreSQL)

Connections

  • clients sends to gateway
  • gateway sends to wallet api
  • wallet api sends to idempotency keys
  • wallet api sends to ledger

Run it, then try raising the load and compare the idempotency check with the ledger writes. The ledger database is where correctness is paid for.

The write path: the service reads the idempotency key and returns the earlier result for a repeat. Otherwise it opens a transaction, debits the sender with a conditional update, credits the receiver, inserts the two entries and the transfer row, and commits. The idempotency record is written in the same transaction (the database is the durable store, and Redis is a fast first check in front of it).

The read path: balance reads go to the primary for the owner (strongly consistent), while history pages can come from a replica.

The interesting problem: moving money atomically, without overdraft

Approach A: read the balance, then update it

Read Alice's balance, check it is at least 20, then write the new balance.

Good: the code reads naturally.

Bad: two simultaneous transfers both read 25, both see enough, and both write: Alice spends 40 from a 25 balance. It is the same check-then-act race as everywhere else in this module, and with money it is a loss.

Approach B: one database transaction with a conditional debit

BEGIN;
UPDATE wallets SET balance_minor = balance_minor - 2000, version = version + 1
  WHERE id = :alice AND balance_minor >= 2000;          -- 0 rows: insufficient funds
UPDATE wallets SET balance_minor = balance_minor + 2000, version = version + 1
  WHERE id = :bob;
INSERT INTO entries (...) VALUES (transfer, 1, :alice, 'debit', 2000, ...),
                                 (transfer, 2, :bob,   'credit', 2000, ...);
COMMIT;

Good: the database decides atomically, a failed condition changes nothing, and the two entries and the two balance changes commit or roll back together. When both wallets live on the same database, this is the whole answer.

Bad: it works only while Alice and Bob are in one database. Two transfers touching the same pair in opposite directions can deadlock unless wallets are always updated in a fixed order (lowest id first).

Approach C: transfers across shards with a saga

At 11 TB of entries you will shard wallets by wallet id, and Alice and Bob will often be on different shards. A transaction cannot span them without two-phase commit, which couples shards' availability and holds locks across a network. Use a saga:

  1. On Alice's shard, in one local transaction: conditionally debit Alice, append her debit entry, and record the transfer as debited with the credit owed to Bob, written to an outbox in the same transaction.
  2. On Bob's shard, from the outbox message: credit Bob and append his credit entry, keyed by the transfer id so a redelivered message does nothing the second time. Mark the transfer completed.
  3. If the credit can never succeed (the account is closed, say), run the compensation on Alice's shard: refund her with a reversing entry and mark the transfer reversed.

Good: every step is a short local transaction, shards stay independent, and the outbox plus idempotent consumers give effectively-once movement.

Bad: between steps the money is in flight. Alice has been debited and Bob not yet credited. Show the transfer as pending, and rely on the conservation check, which counts in-flight transfers, to catch loss.

The recommended answer is B within a shard and C across shards. Keep the in-flight money visible: the debit and the credit are both entries, and the transfer row says which half has happened, so at any instant sum(balances) + sum(in-flight transfers) equals the money in the system. Then the invariant is something you can test, not hope for.

Conceptual diagramcredit impossibleTransfer with keyShard A: conditional debit, entry, outboxMessage with transfer idShard B: credit once, entryTransfer completedShard A: reversing entry
Diagram, as text
  • Transfer with key leads to Shard A: conditional debit, entry, outbox
  • Shard A: conditional debit, entry, outbox leads to Message with transfer id
  • Message with transfer id leads to Shard B: credit once, entry
  • Shard B: credit once, entry leads to Transfer completed
  • Message with transfer id leads to Shard A: reversing entry (credit impossible)

The second decision: hot accounts, and where the balance lives

Only debits need a balance check. A credit can never push a balance below zero. So a hot receiving account, such as a large merchant, can be split into several sub-balances: credits are appended to any of N sub-wallets chosen at random, and the merchant's balance is the sum of them, read or rolled up periodically. Debits and withdrawals (rare for a receiver) take the funds from the sub-wallets under a conditional update. This turns one row taking 1,000 updates a second into ten rows taking about 100 each. The trade-off is that a merchant's exact balance is a sum, not a single field.

Stored balance or computed from entries? Computing a balance by summing entries is always correct and can be slow for an account with millions of entries. Storing it is fast and risks drifting from the entries. Keep both: store the running balance, updated in the same transaction as the entries, and run a job that recomputes SUM(entries) for each wallet and compares. Any difference is an incident, since it means a bug wrote one without the other.

Idempotency for transfers. The client sends an Idempotency-Key for each user intent. A unique constraint on it, inside the same transaction as the money movement, means a retry returns the stored result and does nothing else. Store a hash of the request so a reused key with a different amount is rejected, not honored.

Top-ups and withdrawals involve an outside party. Model the outside as ledger accounts too (a "bank clearing" account), so a top-up is a transaction that debits the clearing account and credits the wallet when the outside payment is confirmed. A withdrawal moves funds into a holding account first, then out once the bank confirms, and back if it fails. See Design a Payment System for the outside call.

Bottlenecks and failures

Hot sender. An account used by a script to send many small transfers serializes on its own row. Rate-limit per account, and queue withdrawals.

Deadlocks. Concurrent transfers between the same two wallets in opposite directions can deadlock. Always lock or update the lower wallet id first, and retry once on a deadlock error.

Crash between saga steps. The transfer row says debited and the credit has not happened. A sweeper finds transfers stuck in a middle state beyond a limit and resumes them, since the credit step is idempotent.

Duplicate messages. The credit consumer may receive the same message twice. The entry's primary key (transfer_id, line) makes a second insert fail, so the credit happens once.

Replica lag. Reading a balance from a lagging replica after a transfer shows the old number. Read the owner's balance from the primary, and use replicas only for history and analytics.

Reconciliation with the bank. The wallet's total should equal the funds held at the partner bank(s). A daily job compares them and flags differences for investigation.

Fraud and abuse. Velocity limits, new-account limits and holds on suspicious transfers sit in front of the ledger and never inside it. The ledger's job is to record, correctly, what was decided.

Trade-offs to name aloud

  • Stored balance plus entries: fast checks, in exchange for a reconciliation job that proves they agree.
  • A saga across shards: shards stay independent, in exchange for a pending state the product must show.
  • Sub-balances for hot receivers: higher write throughput, in exchange for a balance that is a sum.
  • Append-only entries: history is trustworthy, in exchange for fixing errors with reversing entries and never deleting.

What interviewers listen for

  • A working answer: a wallets table, an entries table, and a transaction that debits one wallet and credits another.
  • A strong answer: avoids read-then-write with a conditional debit, makes transfers idempotent, uses double-entry with integer minor units and reads the sender's balance from the primary.
  • A standout answer: moves money across shards with a saga and an outbox, keeps the in-flight money in the invariant, splits hot receivers into sub-balances and runs a job that checks stored balances against the entries.

Check your understanding

Common mistakes

Read-then-write on the balance. It loses money on the first concurrent spend. Use a conditional update.

Floats for money. Use integers in minor units with an explicit currency.

A transfer as two independent requests. Debit and credit must be one atomic operation, or one saga with a compensation.

Mutating entries. Fix mistakes with reversing entries, so history stays intact.

No conservation check. Without a job that proves the invariant, a bug can leak money for months before anyone notices.

Ignoring the outside world. Top-ups and withdrawals are conversations with banks that can fail midway. Model the outside as ledger accounts and the steps as a saga.

Practice

The nightly check finds that 12 wallets have a stored balance different from the sum of their entries. How do you investigate, fix the data and stop it recurring?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Decide which of the two is right before you change anything, and look for the code path that wrote one without the other.

Show a strong answer

Decide which side is right. The entries are the truth, because they are append-only and each belongs to a transfer. Find those 12 wallets' last entries and the transfers they belong to, then compare with the stored balance and its version.

Find the cause. Look for a path that changed the balance without an entry (an admin tool or a manual script) or an entry without a balance change (a code path that skipped the update), and for transactions that ran with a different isolation level or outside the usual function.

Fix the data. Do not edit entries. Correct the balances with an audited adjustment, and if money was truly misplaced, post a correcting transaction so the history records it.

Prevent it. Funnel every balance change through one function that writes the entry and the balance together, forbid direct updates through database permissions, and keep the nightly check as an alert.

The pattern worth keeping: when two records must agree, make one write path own both, then verify the invariant on a schedule.

The interviewer asks how a user's transaction history stays correct when a transfer is still pending between shards. What does the user see?

Write your own answer first, on paper or in a note. Then compare.

Show a hint

Decide what the sender, the receiver and the support team each need to know.

Show a strong answer

The sender sees the transfer as pending right away, with their balance already reduced. The debit is committed, and the sender must not be able to spend that money twice.

The receiver sees it as incoming only when the credit commits. Showing money before it is available invites spending funds that could still be reversed.

Support and auditors see the transfer record with its states and timestamps (debited, completed, reversed), and the entries that back each state.

Keep it short. Most transfers complete in milliseconds, and a sweeper resolves stuck ones. Alert when a transfer stays pending beyond a limit, because it means money is in flight too long.

The pattern worth keeping: a pending state is acceptable if it is honest, short and tied to entries, because each party then sees exactly what is true for them.

Key takeaways

  • The ledger is the product: append-only, double-entry, integer minor units.
  • Conditional debits, not read-then-write, keep balances non-negative under concurrency.
  • Idempotency keys inside the transaction make a retried transfer harmless: effectively once.
  • Within a shard use one transaction, across shards use a saga with an outbox and keep in-flight money in the invariant.
  • Only debits need a balance check, so hot receivers can be split into sub-balances.
  • Prove conservation: a scheduled job compares stored balances with entries, and wallet totals with the partner bank.

Further reading

  • Hector Garcia-Molina and Kenneth Salem, "Sagas", ACM SIGMOD (1987).
  • Pat Helland, "Immutability Changes Everything", CIDR (2015): why append-only records are a sound base for accounting.
  • PostgreSQL documentation, "Explicit Locking" and "Transaction Isolation".
  • Martin Kleppmann, "Designing Data-Intensive Applications" (O'Reilly, 2017): chapters on transactions and derived data.

Check yourself

3 questions in this lesson. Answer each once to complete it.

Practice this

Lessons in this track