LOW LEVEL DESIGN · MACHINE CODING · MEDIUM · 32 OF 42

Design a Digital Wallet: Low-Level Design in Java

The wallet machine coding question, solved end to end: users and wallets, adding money, peer-to-peer transfers on a double-entry ledger, a cached balance that always matches the entries, idempotency keys, lock ordering so two opposite transfers never deadlock, KYC limits as a strategy, refunds as new transactions, history, and a full Java 17 solution.

Patterns usedStrategyObserver

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
1 / 21

Press play to hear the narration, or step through at your own pace. The full Java code is below.

Full Java solution

One file, Java 17, 319 lines, with a small main() demo. Save it as DigitalWallet.java, then run javac DigitalWallet.java && java DigitalWallet.

import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.AtomicReference;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;

/** A digital wallet: double-entry ledger, idempotent requests, lock ordering, limits and refunds. */
public class DigitalWallet {

    // ---------- the model ----------
    enum Side { DEBIT, CREDIT }

    enum TxnType { TOP_UP, TRANSFER, REFUND }

    enum TxnStatus { COMPLETED, FAILED }

    /** One line in the ledger. Every completed transaction writes exactly two: a debit and a credit. */
    record Entry(long seq, String txnId, String walletId, Side side, long cents, Instant at) {}

    /** What happened, kept forever. A failed transaction is stored too, so a retry gets the same answer. */
    record Txn(String id, TxnType type, String from, String to, long cents, TxnStatus status,
               String reason, String refundOf) {}

    static final class Wallet {
        final String id;
        final String owner;
        final boolean system;                       // the bank settlement wallet may go negative
        final ReentrantLock lock = new ReentrantLock();
        private long balanceCents;                  // a cache of the entries, guarded by lock
        private final List<Entry> entries = new ArrayList<>();
        private LocalDate spentDay;
        private long spentTodayCents;

        Wallet(String id, String owner, boolean system) {
            this.id = id;
            this.owner = owner;
            this.system = system;
        }

        /** Called with the lock held: the entry and the cached balance change together. */
        void post(Entry e) {
            balanceCents += e.side() == Side.CREDIT ? e.cents() : -e.cents();
            entries.add(e);
        }

        long spentOn(LocalDate day) { return day.equals(spentDay) ? spentTodayCents : 0; }

        void addSpent(LocalDate day, long cents) {
            if (!day.equals(spentDay)) {
                spentDay = day;
                spentTodayCents = 0;
            }
            spentTodayCents += cents;
        }

        long balance() {
            lock.lock();
            try { return balanceCents; } finally { lock.unlock(); }
        }

        /** The truth: recompute the balance from the ledger entries. */
        long derivedBalance() {
            lock.lock();
            try {
                long sum = 0;
                for (Entry e : entries) sum += e.side() == Side.CREDIT ? e.cents() : -e.cents();
                return sum;
            } finally { lock.unlock(); }
        }

        List<Entry> history() {
            lock.lock();
            try {
                List<Entry> copy = new ArrayList<>(entries);
                Collections.reverse(copy);          // newest first
                return copy;
            } finally { lock.unlock(); }
        }
    }

    // ---------- limits (Strategy) ----------
    interface LimitPolicy {
        /** Returns a reason to refuse, or null when allowed. Called with both wallets locked. */
        String check(Wallet from, Wallet to, long cents, LocalDate today);
    }

    /** A basic KYC wallet: a cap per transfer, a daily outgoing cap and a maximum balance. */
    record KycLimits(long perTransferCents, long dailyOutCents, long maxBalanceCents) implements LimitPolicy {
        @Override
        public String check(Wallet from, Wallet to, long cents, LocalDate today) {
            if (!from.system && cents > perTransferCents) return "over the per-transfer limit";
            if (!from.system && from.spentOn(today) + cents > dailyOutCents) return "daily limit reached";
            if (!to.system && to.balanceCents + cents > maxBalanceCents) return "receiver wallet is full";
            return null;
        }
    }

    // ---------- the service ----------
    private record Slot(String fingerprint, CompletableFuture<Txn> result) {}

    private final Map<String, Wallet> wallets = new ConcurrentHashMap<>();
    private final Map<String, Txn> txns = new ConcurrentHashMap<>();
    private final Map<String, Slot> idempotency = new ConcurrentHashMap<>();
    private final Map<String, Long> refunded = new ConcurrentHashMap<>();
    private final AtomicLong txnSeq = new AtomicLong();
    private final AtomicLong entrySeq = new AtomicLong();
    private final LimitPolicy limits;
    private final Supplier<Instant> clock;
    private final Wallet bank = new Wallet("W0", "bank-settlement", true);

    DigitalWallet(LimitPolicy limits, Supplier<Instant> clock) {
        this.limits = limits;
        this.clock = clock;
        wallets.put(bank.id, bank);
    }

    Wallet open(String id, String owner) {
        Wallet w = new Wallet(id, owner, false);
        if (wallets.putIfAbsent(id, w) != null) throw new IllegalArgumentException("wallet exists: " + id);
        return w;
    }

    /** Add money from a bank: the settlement wallet is debited, the user wallet is credited. */
    Txn addMoney(String key, String walletId, long cents) {
        return once(key, "TOP_UP|" + walletId + "|" + cents,
                () -> move(TxnType.TOP_UP, bank, wallet(walletId), cents, null));
    }

    Txn transfer(String key, String fromId, String toId, long cents) {
        return once(key, "TRANSFER|" + fromId + "|" + toId + "|" + cents, () -> {
            if (fromId.equals(toId)) throw new IllegalArgumentException("cannot pay yourself");
            return move(TxnType.TRANSFER, wallet(fromId), wallet(toId), cents, null);
        });
    }

    /** A refund is a new transfer the other way, linked to the original. The original is never edited. */
    Txn refund(String key, String originalId, long cents) {
        return once(key, "REFUND|" + originalId + "|" + cents, () -> {
            Txn orig = txns.get(originalId);
            if (orig == null || orig.type() != TxnType.TRANSFER || orig.status() != TxnStatus.COMPLETED) {
                throw new IllegalArgumentException("not a refundable transfer: " + originalId);
            }
            return move(TxnType.REFUND, wallet(orig.to()), wallet(orig.from()), cents, orig);
        });
    }

    /** Same key and same request: the same answer. Same key, different request: an error. */
    private Txn once(String key, String fingerprint, Supplier<Txn> work) {
        Slot mine = new Slot(fingerprint, new CompletableFuture<>());
        Slot old = idempotency.putIfAbsent(key, mine);
        if (old != null) {
            if (!old.fingerprint().equals(fingerprint)) {
                throw new IllegalArgumentException("key " + key + " was used for a different request");
            }
            return old.result().join();
        }
        try {
            mine.result().complete(work.get());
        } catch (RuntimeException e) {
            idempotency.remove(key, mine);          // a bad request did nothing, so the key is free again
            mine.result().completeExceptionally(e);
            throw e;
        }
        return mine.result().join();
    }

    /** Lock both wallets in a fixed order (by id), so A-to-B and B-to-A can never deadlock. */
    private Txn move(TxnType type, Wallet from, Wallet to, long cents, Txn refundOf) {
        if (cents <= 0) throw new IllegalArgumentException("amount must be positive");
        Wallet first = from.id.compareTo(to.id) < 0 ? from : to;
        Wallet second = first == from ? to : from;
        first.lock.lock();
        try {
            second.lock.lock();
            try {
                return moveLocked(type, from, to, cents, refundOf);
            } finally {
                second.lock.unlock();
            }
        } finally {
            first.lock.unlock();
        }
    }

    private Txn moveLocked(TxnType type, Wallet from, Wallet to, long cents, Txn refundOf) {
        String id = "tx" + txnSeq.incrementAndGet();
        Instant now = clock.get();
        LocalDate today = LocalDate.ofInstant(now, ZoneOffset.UTC);
        String reason = null;
        if (!from.system && from.balanceCents < cents) reason = "insufficient balance";
        else if (refundOf != null) {
            long left = refundOf.cents() - refunded.getOrDefault(refundOf.id(), 0L);
            if (cents > left) reason = "refund exceeds remaining " + money(left);
        } else {
            reason = limits.check(from, to, cents, today);
        }
        String link = refundOf == null ? null : refundOf.id();
        if (reason != null) {
            return save(new Txn(id, type, from.id, to.id, cents, TxnStatus.FAILED, reason, link));
        }
        from.post(new Entry(entrySeq.incrementAndGet(), id, from.id, Side.DEBIT, cents, now));
        to.post(new Entry(entrySeq.incrementAndGet(), id, to.id, Side.CREDIT, cents, now));
        if (type == TxnType.TRANSFER) from.addSpent(today, cents);
        if (refundOf != null) refunded.merge(refundOf.id(), cents, Long::sum);
        return save(new Txn(id, type, from.id, to.id, cents, TxnStatus.COMPLETED, null, link));
    }

    private Txn save(Txn t) {
        txns.put(t.id(), t);
        return t;
    }

    private Wallet wallet(String id) {
        Wallet w = wallets.get(id);
        if (w == null) throw new IllegalArgumentException("no wallet " + id);
        return w;
    }

    /** Double entry means every balance, including the bank's negative one, adds up to zero. */
    long sumOfAllBalances() {
        long sum = 0;
        for (Wallet w : wallets.values()) sum += w.balance();
        return sum;
    }

    static String money(long cents) {
        String sign = cents < 0 ? "-" : "";
        long c = Math.abs(cents);
        return String.format("%s%,d.%02d", sign, c / 100, c % 100);
    }

    static String show(Txn t) {
        String tail = t.status() == TxnStatus.FAILED ? " (" + t.reason() + ")" : "";
        return t.id() + " " + t.type() + " " + money(t.cents()) + " " + t.status() + tail;
    }

    // ---------- demo ----------
    public static void main(String[] args) throws InterruptedException {
        AtomicReference<Instant> now = new AtomicReference<>(Instant.parse("2026-03-02T10:00:00Z"));
        DigitalWallet app = new DigitalWallet(new KycLimits(2_000_00, 3_000_00, 10_000_00), now::get);
        Wallet buyer = app.open("W1", "buyer");
        Wallet friend = app.open("W2", "friend");
        Wallet cafe = app.open("W3", "cafe");

        Txn top = app.addMoney("topup-1", "W1", 5_000_00);
        Txn again = app.addMoney("topup-1", "W1", 5_000_00);
        System.out.println("top up: " + show(top) + ", retry returns " + again.id()
                + ", buyer has " + money(buyer.balance()));
        try {
            app.addMoney("topup-1", "W1", 9_000_00);
        } catch (IllegalArgumentException e) {
            System.out.println("reused key: " + e.getMessage());
        }
        app.addMoney("topup-2", "W2", 5_000_00);

        // The same payment sent ten times at once: one transaction, one pair of entries.
        ExecutorService pool = Executors.newFixedThreadPool(8);
        CountDownLatch go = new CountDownLatch(1);
        Set<String> ids = ConcurrentHashMap.newKeySet();
        for (int i = 0; i < 10; i++) {
            pool.submit(() -> {
                go.await();
                ids.add(app.transfer("order-77", "W1", "W3", 250_00).id());
                return null;
            });
        }
        go.countDown();
        pool.shutdown();
        pool.awaitTermination(5, TimeUnit.SECONDS);
        System.out.println("order-77 sent 10 times: " + ids + ", cafe has " + money(cafe.balance()));
        if (ids.size() != 1 || cafe.balance() != 250_00) throw new AssertionError("double debit");
        Txn order = app.txns.get(ids.iterator().next());

        // Two threads pay each other a thousand times: lock ordering means no deadlock.
        long before = buyer.balance() + friend.balance();
        ExecutorService two = Executors.newFixedThreadPool(2);
        two.submit(() -> { for (int i = 0; i < 1000; i++) app.transfer("ping-" + i, "W1", "W2", 1_00); });
        two.submit(() -> { for (int i = 0; i < 1000; i++) app.transfer("pong-" + i, "W2", "W1", 1_00); });
        two.shutdown();
        if (!two.awaitTermination(10, TimeUnit.SECONDS)) throw new AssertionError("deadlock");
        System.out.println("ping-pong 2,000 transfers: buyer + friend still " + money(buyer.balance()
                + friend.balance()));
        if (buyer.balance() + friend.balance() != before) throw new AssertionError("money lost");

        System.out.println("pay 2,500.00: " + show(app.transfer("big-1", "W1", "W3", 2_500_00)));
        System.out.println("pay 1,500.00: " + show(app.transfer("rent-1", "W1", "W3", 1_500_00)));
        System.out.println("pay 500.00:   " + show(app.transfer("rent-2", "W1", "W3", 500_00)));
        now.set(now.get().plus(Duration.ofDays(1)));
        System.out.println("next day:     " + show(app.transfer("rent-3", "W1", "W3", 500_00)));

        System.out.println("refund 100.00: " + show(app.refund("rf-1", order.id(), 100_00)));
        System.out.println("refund 200.00: " + show(app.refund("rf-2", order.id(), 200_00)));

        for (Wallet w : List.of(app.bank, buyer, friend, cafe)) {
            if (w.balance() != w.derivedBalance()) throw new AssertionError("cache drifted on " + w.id);
            System.out.println("  " + w.id + " " + w.owner + ": " + money(w.balance()) + " (ledger agrees)");
        }
        System.out.println("sum of all balances: " + money(app.sumOfAllBalances()));
        if (app.sumOfAllBalances() != 0) throw new AssertionError("ledger does not balance");
        System.out.println("cafe history, newest first:");
        for (Entry e : cafe.history()) {
            System.out.println("  " + e.txnId() + " " + e.side() + " " + money(e.cents()));
        }
    }
}

Notes

Requirements

Fix the scope first. Each user opens a wallet. They can add money from a bank account, send money to any other wallet, see their history, and a shop can refund all or part of a payment. There are limits per transfer and per day. Two rules sit above everything: a retried request never pays twice, and money is never created or lost inside the system. Withdrawing to a bank and cashback are out of scope.

Ask the questions that change the code. Can a user balance go negative? No. One currency? Yes, stored as whole paise in a long, never a double. Do failed transfers appear in history? Yes, with a reason. Can refunds add up to more than the payment? No. Can the same user act from two phones at once? Yes, which tells you concurrency is part of the question, not a bonus.

Requirements
  • users open one wallet each
  • add money from a bank account
  • send money to another wallet
  • see transaction history
  • refund all or part of a payment
  • limits per transfer and per day
  • a retry must never pay twice
  • money is never created or lost
  • out of scope: bank payouts,
  • rewards, currency exchange
Clarify first
  • can a balance go negative?
  • no, never for a user
  • one currency?
  • yes, whole paise in a long
  • failed transfers in history?
  • yes, with a reason
  • can a refund exceed the payment?
  • no, track what is left
  • many devices at once?
  • yes, so think about races

Entities

Now the entities. A user owns a wallet. A transaction is the story of one money movement: its type, amount, sender, receiver and status. A ledger entry is one line in a wallet's book, either a debit or a credit. The key relationship is that every completed transaction writes exactly two entries. Keep users thin here; login, profile and KYC documents belong to other services.

Class diagram

Turn them into types. Entries and transactions are facts that never change, so they are Java records. A refund does not edit the original transaction; it is a new one that points back to it. The only mutable class is the wallet, with its own lock, its list of entries and a cached balance. Keeping all changing state in one class keeps the thread safety story short.

Types
enum Side { DEBIT, CREDIT }
enum TxnType { TOP_UP, TRANSFER, REFUND }
record Entry(seq, txnId, walletId,
             Side side, long cents, at)
record Txn(id, type, from, to, cents,
           status, reason, refundOf)
class Wallet {
  ReentrantLock lock;
  long balanceCents;   // cache
  List<Entry> entries; // truth
}

Double-entry ledger

Here is the heart of the design: a double-entry ledger. Every transaction writes two entries of the same amount, a debit on one wallet and a credit on another. Adding money is no exception. A system settlement wallet, which stands for the real bank account, is debited and goes negative, while the user is credited. So the sum of every balance in the system is always zero. If it is not, you have a bug, and you can find it.

Two entries per transaction
  • add 5,000.00 to the buyer:
  • bank wallet DEBIT 5,000.00
  • buyer wallet CREDIT 5,000.00
  • buyer pays cafe 250.00:
  • buyer wallet DEBIT 250.00
  • cafe wallet CREDIT 250.00
  • sum of every balance
  • in the system: always zero

Balance

Should the balance be stored or computed? The entries are the truth, so the balance can always be derived by adding them up. But summing a long history on every payment is slow, so we also keep a cached balance on the wallet. The cache and the entry change together, inside one method, while the wallet lock is held. A reconciliation job recomputes the sum and alerts if the cache ever drifts.

Wallet.post()
// called with the wallet lock held
void post(Entry e) {
  balanceCents += e.side() == CREDIT
                  ? e.cents() : -e.cents();
  entries.add(e);
}

derivedBalance(): sum of the entries
nightly check: cache == derived

Idempotency

A phone on a weak network taps pay, the reply is lost, and the app retries. Without protection the friend is paid twice. So the app sends an idempotency key with every request, and we store the key with a fingerprint of the request and a future for its result. A retry with the same key gets the same transaction back. The same key with a different amount is a client bug, so we reject it loudly instead of guessing.

Retries can land at the same instant, so check then insert is not enough. Each request puts a slot into a concurrent map with put-if-absent. Exactly one wins and does the work; the others find the winner's future and wait on it. A transfer refused for low balance is still a stored answer, so a retry sees the same failure. Only an invalid request, like an unknown wallet, releases the key.

Idempotency rules
  • app sends key with every request
  • store: key -> fingerprint + Future
  • same key, same request:
  • return the stored transaction
  • same key, different amount:
  • reject, it is a client bug
  • failed for a business reason:
  • stored too, retry sees FAILED
  • invalid request: key released
once(key, fingerprint, work)
Slot mine = new Slot(fp, new Future());
Slot old = idem.putIfAbsent(key, mine);
if (old != null) {
  if (!old.fp.equals(fp)) throw ..;
  return old.result.join();
}
try { mine.result.complete(work.get()); }
catch (RuntimeException e) {
  idem.remove(key, mine); throw e;
}

Flow: transfer

Walk the transfer. The idempotency wrapper runs first. Then we lock both wallets, check the sender has enough money and ask the limit policy. If anything fails, we save a failed transaction with the reason. Otherwise we post a debit to the sender and a credit to the receiver, add the amount to the sender's spending for today, and save a completed transaction. Both locks are released at the end.

transfer(key, from, to, cents)
once(key, fingerprint, () -> {
  lock both wallets in id order
  if (from.balance < cents) FAILED
  reason = limits.check(..)
  if (reason != null) FAILED
  from.post(DEBIT); to.post(CREDIT);
  from.addSpent(today, cents);
  return COMPLETED txn
})

Concurrency

Now the classic trap. A transfer must lock two wallets so the debit and credit happen together. Thread one, the buyer paying a friend, locks the buyer, then asks for the friend. At the same moment thread two, the friend paying the buyer, locks the friend, then asks for the buyer. Each holds what the other needs, and both wait forever. That is a deadlock, and a naive solution hits it under load.

The fix is lock ordering. Every thread locks the wallet with the smaller id first, whatever the direction of the money. Both threads now start by locking the buyer, so one waits at the very first step while holding nothing, and no cycle can form. Unlock in finally blocks so an exception never leaves a wallet locked. A single global lock would also be safe, but then every payment in the country waits in one queue.

The deadlock
  • thread 1: buyer pays friend
  • lock(buyer)
  • lock(friend) ... waits
  • thread 2: friend pays buyer
  • lock(friend)
  • lock(buyer) ... waits
  • each holds what the other
  • needs: both wait forever
Lock ordering
Wallet first = from.id.compareTo(to.id)
                 < 0 ? from : to;
Wallet second = first == from ? to : from;
first.lock.lock();
try {
  second.lock.lock();
  try { return moveLocked(..); }
  finally { second.lock.unlock(); }
} finally { first.lock.unlock(); }

Strategy: limits

Limits are a policy that changes with the user's KYC level and with regulation, so they sit behind a limit policy interface: the Strategy pattern. Our basic policy caps each transfer, caps total spending per day and caps the wallet balance. It returns a reason or nothing. The day comes from an injected clock, so a test can move to tomorrow without sleeping. A fully verified user simply gets another policy class.

LimitPolicy
interface LimitPolicy {
  String check(Wallet from, Wallet to,
               long cents, LocalDate day);
}
KycLimits(perTransfer 2,000.00,
          dailyOut 3,000.00,
          maxBalance 10,000.00)
FullKycLimits, MerchantLimits:
  new classes, service unchanged

Refunds

A refund never edits or deletes the original transaction. It is a new transaction the other way, linked to the original, with its own two entries. Under the locks of both wallets we check how much is left to refund, so two refunds cannot add up to more than the payment. If the shop has already spent the money, the refund fails with a clear reason. A full reversal is just a refund of everything that is left.

refund(key, txnId, cents)
  • original must be a completed
  • transfer
  • lock receiver and sender
  • (same id order)
  • left = amount - refunded so far
  • cents over left: FAILED
  • receiver too poor: FAILED
  • else DEBIT receiver,
  • CREDIT the original sender
  • original stays untouched

History

Transaction history falls out of the ledger for free. Each wallet's entries, newest first, are its statement, and the transaction id on each line leads to the full details, including the reason for a failure. With millions of rows you page by the entry sequence number using an index on wallet and sequence, never by offset, so new payments arriving do not shift the pages.

Cafe history
tx2008  DEBIT     100.00  refund
tx2007  CREDIT    500.00
tx2005  CREDIT  1,500.00
tx3     CREDIT    250.00

real systems: page by entry seq,
  index on (walletId, seq desc)

Concurrency

Check every shared field. Wallet state is guarded by that wallet's lock, and two wallets are always locked in id order. The cache and the entries change together under that lock. Idempotency is a concurrent map of slots with futures. The amount refunded so far is only changed while both wallets of that payment are locked. Ids come from atomic counters, and transactions and entries are immutable records, safe to share.

Thread safety checklist
  • wallet state: its ReentrantLock
  • two wallets: lock by id order
  • cache + entry: changed together
  • idempotency: ConcurrentHashMap
  • of request + Future
  • refunded so far: updated under
  • both wallet locks
  • ids and entry seq: AtomicLong
  • Txn and Entry: immutable records

Extensibility

Interviewers will stretch it. Withdrawing to a bank is the top-up in reverse. Freezing a wallet is a status the limit policy refuses. Cashback is a transfer from a promotions wallet, so the books still balance. Notifications are observers on completed transactions. On many servers, the locks become row locks taken in id order inside one database transaction, and the idempotency key becomes a unique column.

Extension points
  • withdraw to bank: debit user,
  • credit the settlement wallet
  • freeze a wallet: a status the
  • limit policy checks
  • cashback: a promo wallet pays
  • notifications: Observer on txn
  • many servers: DB transaction,
  • SELECT .. FOR UPDATE in id
  • order, unique idempotency key
  • audit: entries never updated

Testing

The full code is below the player. The demo tops up and retries with the same key, then reuses the key with a new amount and is rejected. Ten threads send the same payment and only one transaction appears. Two threads pay each other a thousand times each and finish without deadlock. A fake clock moves to the next day to reset the daily limit, and every wallet's cache matches its ledger, with all balances summing to zero.

Run it
top up 5,000.00, retry: same tx1
same key, 9,000.00: rejected
order-77 sent 10 times: [tx3]
ping-pong 2,000 transfers: no deadlock
pay 2,500.00: over per-transfer limit
pay 500.00: daily limit reached
next day: COMPLETED
refund 200.00: exceeds remaining 150.00
every cache matches its ledger
sum of all balances: 0.00

Follow-ups

Expect follow-ups. Why not one global lock? It is correct but every payment waits in one line. Why not try-lock with a timeout? It also avoids deadlock, but you must back off and retry. Store or derive the balance? Both, and reconcile them. What about a popular shop receiving thousands of payments a second? Split its wallet into several sub-wallets and add them up when you read the balance.

Follow-ups to expect
  • why not one global lock?
  • correct but serial
  • why not tryLock with timeout?
  • works, but needs retries
  • balance: store or derive?
  • both, and reconcile
  • why record failed transfers?
  • support, and idempotent retries
  • hot merchant wallet?
  • shard it into sub-wallets

Say it like this

Here is the short version to say out loud. Every transaction writes a debit and a credit, so all balances sum to zero. The balance is a cache of the entries, updated together under the wallet lock. Every request carries an idempotency key. Two wallets are always locked in id order, so opposite transfers cannot deadlock. Limits are a strategy, and refunds are new transactions, never edits.

In the interview
  • "Every transaction writes two
  • entries, so balances always sum
  • to zero. The balance is a cache
  • of the entries, updated under
  • the wallet lock. Requests carry
  • idempotency keys. Two wallets
  • are locked in id order, so no
  • deadlock. Limits are a strategy;
  • refunds are new transactions."

Interview questions

What is a double-entry ledger and why use it for a wallet?

Every transaction writes two entries of the same amount: a debit on one account and a credit on another. Money only moves, it is never created or destroyed, so the sum of all balances stays zero and any bug shows up as an imbalance you can find.

Should the wallet balance be stored or computed from the ledger?

The ledger entries are the source of truth, but summing them on every payment is slow. Keep a cached balance updated in the same lock or database transaction as the entry, and run a reconciliation job that recomputes the sum and alerts on any difference.

How do you avoid deadlock when a transfer locks two wallets?

Lock in a global order, for example the wallet with the smaller id first, regardless of which way the money moves. Opposite transfers then compete for the same first lock, so a cycle of waiting cannot form. In a database, take the row locks in the same id order.

How do idempotency keys work for a transfer?

The client sends a unique key with each request. The server stores the key, a fingerprint of the request and the result (a future while it runs) using putIfAbsent. A retry with the same key returns the stored result; the same key with a different request is rejected as a client bug.

Should a transfer that failed for low balance be stored?

Yes. Storing it with the reason gives support a full history, and it makes the request idempotent: a retry with the same key sees the same failure instead of quietly succeeding later after the balance changed.

How do you implement refunds and reversals?

Never edit the original. A refund is a new transaction in the opposite direction that links to the original and writes its own debit and credit. Track the amount refunded so far under the wallet locks so refunds can never exceed the payment.

Why keep money in a long number of paise instead of a double?

A double cannot represent most decimal amounts exactly, so sums drift by tiny fractions and the ledger stops balancing. Whole paise in a long are exact; BigDecimal also works when you need fractions, such as for interest or currency exchange.

Where do daily limits belong and how do you test them?

In a LimitPolicy strategy checked while the sender wallet is locked, so two payments cannot both slip under the limit. Inject the clock as a Supplier of Instant so the test can move to the next day and see the limit reset without sleeping.

What changes when the wallet runs on many servers?

In-memory locks no longer protect anything. Each transfer becomes one database transaction that locks both wallet rows in id order, inserts the two entries, updates the cached balances and inserts the idempotency key into a unique column, so a duplicate request fails at the database.