Skip to content
Preptima
mediumCodingDesignMidSenior

Build a digital wallet with transfers where a balance can never go negative, even when many transfers run at the same moment.

A digital wallet stays non-negative only if the balance check and the debit happen in one critical section. Lock both wallets in a fixed order by id so concurrent transfers cannot deadlock, record every movement as a pair of entries, and make each transfer idempotent on a client key so a retry cannot pay twice.

6 min readUpdated 2026-10-10Target archetype: Fintech

Answer

Short answer

The balance check and the debit must be one atomic step. In a digital wallet, two concurrent transfers that each read a balance of 100 and each move 80 will both pass a separate check, and the wallet ends at -60. Lock both wallets for the whole transfer, always in the same order by wallet id, and append a debit and a credit entry together. Key each transfer on a client-supplied idempotency key, so a network retry returns the first result instead of moving money again.

Was this answer helpful?

Likely follow-ups

  • Top-ups arrive from a card processor. Which account is allowed to go negative, and why is that one not a bug?
  • How would you replace the two in-memory locks with a single conditional UPDATE once balances live in a database?
  • A client reuses an idempotency key for a different amount. What should happen, and where is that checked?
  • Hot wallets such as a merchant's receive thousands of credits a second. How do you stop that lock becoming the bottleneck?

Related questions