Quick revision
The short answer
Every money movement is a journal entry with at least two lines, a debit and a credit that sum to zero, written in one database transaction. Entries are immutable, so corrections are new reversing entries. Balances are either derived from the lines or kept in an account row updated in the same transaction under a row lock or an optimistic version, with accounts always locked in id order to avoid deadlocks. Amounts use long minor units or BigDecimal, never double, and periodic checks prove that all lines sum to zero and balances match.
What to remember
In this answer, we designed a double-entry ledger for a wallet. Every movement is an immutable journal entry whose lines sum to zero, written in one transaction with an idempotency key, and corrections are reversing entries. We kept balances correct under concurrency with row locks taken in a consistent id order, or with optimistic versions, used long minor units or BigDecimal instead of double, and added scheduled checks that all lines sum to zero and that balances match their lines.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
Every money movement is a journal entry with at least two lines, a debit and a credit that sum to zero, written in one database transaction. Entries are immutable, so corrections are new reversing entries. Balances are either derived from the lines or kept in an account row updated in the same transaction under a row lock or an optimistic version, with accounts always locked in id order to avoid deadlocks. Amounts use long minor units or BigDecimal, never double, and periodic checks prove that all lines sum to zero and balances match.
Why this question is asked
A wallet looks like a single number per user, but a wallet that keeps only that number cannot explain where money came from, cannot be audited and silently drifts when two updates race. Double-entry bookkeeping, used by accountants for centuries, solves this by recording every movement from both sides. Interviewers ask this design question because it combines domain modelling with the concurrency details that decide whether balances are actually correct. In this answer, we will recap double entry, design the tables, write a payment as one transaction, handle concurrency and deadlocks, choose the money type, and add the checks that prove the ledger is consistent.
1A Quick Recap of Double Entry
In double entry, money is never created or destroyed inside the system; it only moves between accounts. Each movement is a journal entry made of lines. A line says which account changes and by how much, positive for a debit and negative for a credit (or the opposite convention, as long as it is consistent). The lines of one entry always sum to zero: if 25.00 leaves one account, 25.00 arrives in others.
Every party is an account. Each user's wallet is an account. Each merchant has an account. Money coming from outside, such as a card top-up, comes from an external clearing account that represents the card provider. Fees go to a revenue account. This is what makes the ledger auditable: for any balance, we can list every line that produced it.
| Entry | Account | Amount (cents) | Why |
|---|---|---|---|
| E1 top-up | card_clearing | -5000 | money arrives from the card provider |
| E1 top-up | wallet:alice | +5000 | alice's balance rises to 50.00 |
| E2 payment | wallet:alice | -2500 | alice pays a merchant |
| E2 payment | merchant:cafe | +2500 | cafe receives it |
| E3 refund | merchant:cafe | -1000 | partial refund back |
| E3 refund | wallet:alice | +1000 | alice's balance is now 35.00 |
2The Data Model
Three tables are enough to start: accounts, journal entries and journal lines. Entries and lines are insert-only. The account row holds a cached balance and a version for concurrency control.
The unique idempotency key means a retried request cannot post the same payment twice: the second insert fails and we return the first result. Because entries are never updated, a mistake is fixed by posting a new entry that reverses the wrong one, with the opposite amounts and a reference to the original. The history stays complete, which auditors and support both need.
3Posting a Payment in One Transaction
A payment from Alice to a cafe touches two accounts. We must check that Alice has enough money and then write the entry, both lines and both balance updates, in a single transaction, so either all of it happens or none of it does.
The lockById method runs SELECT ... FOR UPDATE, in Spring Data JPA a repository method annotated with @Lock(LockModeType.PESSIMISTIC_WRITE). It locks the account row until the transaction ends, so a second payment from Alice waits instead of reading a balance that is about to change. Without the lock, two payments of 30.00 against a balance of 35.00 could both read 35.00, both pass the check and leave the balance at -25.00.
4Locking in a Consistent Order
Notice that the code locks the lower account id first, not the sender first. The reason is deadlocks. If Alice pays Bob while Bob pays Alice, and each transaction locks its sender first, transaction 1 holds Alice and waits for Bob while transaction 2 holds Bob and waits for Alice. PostgreSQL detects this and aborts one of them, which is safe but wastes work and causes errors under load. When every transaction locks accounts in the same order, by id, the second transaction simply waits for the first, and no cycle can form.
6 messages in order. Play them, or step through them one at a time.
Both transactions take id 7 first, so they queue instead of deadlocking.
5Choosing the Balance Strategy
There are two ways to know a balance. We can derive it every time with SUM(amount) over the account's lines; this is always consistent with the lines but gets slower as an account accumulates millions of lines. Or we keep the balance column updated in the same transaction as the lines, as above, which makes reads instant and still correct, because both change atomically.
Instead of pessimistic locks, we can use optimistic locking: a @Version column, so the update succeeds only if nobody changed the row since we read it, and otherwise we retry. Optimistic locking works well when conflicts are rare. For a merchant account receiving hundreds of payments per second, pessimistic locks on one hot row become a bottleneck either way; a common answer is to split the merchant into several sub-accounts and sum them, or to post merchant credits asynchronously while user debits stay synchronous.
6Exact Money Types and Proving Correctness
Money must use exact types. A double cannot represent 0.10 exactly, so 0.1 + 0.2 gives 0.30000000000000004 and small errors accumulate. We store long minor units (3500 means 35.00 in a currency with two decimals) or BigDecimal with a fixed scale, together with the currency, and we never add amounts in different currencies.
Finally, we prove the ledger instead of trusting it. A scheduled job checks that the sum of all lines is zero, that every entry's lines sum to zero, and that each account's balance column equals the sum of its lines. Any difference raises an alert immediately, because it means a bug or a manual change bypassed the rules, and it is far easier to fix on the day it happens than at month end.
7Follow-up questions
How would you handle a top-up from a card that is later charged back?
The top-up posted card_clearing to wallet. A chargeback is a new entry that reverses it: wallet debited, card_clearing credited. If the user already spent the money, the wallet goes negative, which is a real business situation; we allow the reversal entry to take the balance below zero, flag the account and start collections, rather than refusing to record what actually happened.
Why not just store a balance and update it with UPDATE ... SET balance = balance - 2500?
An atomic update does avoid lost updates, and with a CHECK (balance >= 0) constraint it even prevents overdrafts. But it leaves no history: we cannot explain a balance, reverse a specific payment or reconcile with external systems. The journal lines are the record of truth; the balance column is a convenient cache of their sum, kept consistent because both change in the same transaction.
8Conclusion
In this answer, we designed a double-entry ledger for a wallet. Every movement is an immutable journal entry whose lines sum to zero, written in one transaction with an idempotency key, and corrections are reversing entries. We kept balances correct under concurrency with row locks taken in a consistent id order, or with optimistic versions, used long minor units or BigDecimal instead of double, and added scheduled checks that all lines sum to zero and that balances match their lines.
Open with
I would model it as a proper double-entry ledger. Every party is an account: each user wallet, each merchant, and system accounts such as card clearing for money coming in and revenue for fees.
Then, if they want more
Every money movement, top-up, payment or refund, is a journal entry with at least two lines, a debit and a credit, that sum to zero, and the whole entry is written in one database transaction with a unique idempotency key so a retry cannot post it twice.
Entries are immutable; if something is wrong, we post a reversing entry rather than updating anything, so the history stays complete. For balances, I keep a balance column on the account row and update it in the same transaction as the lines, so reads are fast and the balance always matches its lines. Concurrency is the important part.
I lock the account rows with SELECT FOR UPDATE before checking funds, so two payments cannot both spend the same money, and I always lock accounts in ascending id order so Alice paying Bob and Bob paying Alice cannot deadlock. Optimistic locking with a version column is an alternative when conflicts are rare.
Money is stored as long minor units or BigDecimal with a fixed scale, never double. And I would not just trust the code: a scheduled job checks that all lines sum to zero, every entry balances and every cached balance equals the sum of its lines, and alerts on any difference.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Design a double-entry ledger for a wallet product in a Spring Boot service, where users...": https://scrivio-interview-library.netlify.app/architecture/backend-system-design/5d30fdcd99/