📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

๐Ÿ“š Interview question

Design the money-transfer core of a bank or digital wallet: customers move money between their own accounts and to other customers. How do you model the ledger with double-entry bookkeeping, keep balances correct under concurrent transfers, guarantee a transfer is applied exactly once, handle transfers to other banks that settle later, and make everything auditable?

A full banking transfer design: requirements and volumes, an append-only double-entry ledger with journal entries and postings, balance maintenance with concurrency control and overdraft checks, idempotency keys, pending and clearing accounts for external transfers, hot accounts, auditability with immutable records and SQL ledger tables, and reconciliation, in .NET on Azure SQL.

Senior SystemDesign Advanced audit banking double-entry-ledger idempotency system-design transactions

๐ŸŽฏ Key points

  • Double-entry: every journal entry has postings that sum to zero; money is never created or destroyed
  • Append-only ledger: corrections are reversing entries; audit via SQL ledger tables (hash chain + digests) and maker-checker for manual adjustments
  • Internal transfer = one ACID transaction: both postings + balance updates + idempotency record
  • Concurrency: conditional UPDATE (balance + limit >= amount) and row locks in account-id order to avoid deadlocks
  • Idempotency key from the client, unique-indexed, returns the original result on retry
  • External transfers: debit into a clearing account, show 'pending' (available vs ledger balance), notify the customer, settle or reverse when the scheme confirms
  • Hot accounts: one row taking thousands of updates/s serialises on its lock → split into N sub-accounts (logical balance = sum) or post asynchronously in batches
  • Scale: a single writer handles ~1,000+ transfers/s; beyond that shard by account id with clearing-account sagas between shards; daily trial balance = 0

โฑ 30-second answer

The core is a double-entry, append-only ledger: a transfer is a journal entry with postings that sum to zero (debit A, credit B), and corrections are reversing entries, never updates. An internal transfer runs in one ACID transaction in Azure SQL: insert the postings, update both balances with a conditional update that refuses overdrafts, and record the idempotency key with a unique index so retries return the original result. Locks are taken in account-id order to avoid deadlocks. Transfers to other banks first move money into a clearing account as pending, then settle or reverse when the payment scheme confirms. Auditability comes from immutability plus a daily trial balance and reconciliation. The trade-off: strong consistency per transfer limits horizontal scale, which is fine because correctness beats throughput for money.

๐Ÿ—ฃ Full answer (senior)

How I would answer this in an interview

"I'd clarify: internal transfers between a customer's accounts and to other customers of the same bank, external transfers to other banks, no overdrafts unless the account has a limit, balances visible immediately, and a full audit trail for regulators. For scale, say five million customers making ten million transfers a day: about 115 a second average and maybe 1,000 at the lunchtime or payday peak. Each transfer writes at least two postings, so about 2,000 rows a second at peak, which a well-indexed Azure SQL database handles.

The model is double-entry bookkeeping. A journal entry says 'transfer 50 dollars from A to B' and owns two postings: minus 5,000 cents on A and plus 5,000 on B. Postings always sum to zero, and they're append-only. If something is wrong, we post a reversal. Balances are a materialised column on the account, updated in the same transaction as the postings, so reading a balance is cheap and always equals the sum of postings.

The transfer itself is one transaction: check the idempotency key, update the source with WHERE Balance + OverdraftLimit >= @amount, update the destination, insert the entry and postings, commit. If the conditional update touches zero rows, it's insufficient funds. Locking both accounts in id order prevents deadlocks between A-to-B and B-to-A. For example, at [company] we [had deadlocks at payday because transfers locked accounts in request order]; [ordering by account id] [removed them entirely].

External transfers are where eventual consistency comes in: we debit the customer and credit a clearing account immediately, send the payment to the scheme, and when it confirms we move money from clearing to the settlement account; if it's rejected we post a reversal. The clearing account should net to zero once everything settles, which is what we reconcile daily.

The mistake I see is storing only a balance and updating it in place. Then you can't explain a balance, and a bank that can't explain a balance has a regulator problem."


Requirements

Type Requirement Assumption
Functional Internal transfers (own and other customers) Immediate, atomic
Functional External transfers to other banks Async settlement via a scheme
Functional Statements, balance history From postings
Non-functional Never lose or duplicate money ACID + idempotency
Non-functional Full audit trail, tamper-evident Append-only, ledger tables
Non-functional Transfer p95 < 300 ms Single region writer, zone redundant

Capacity estimate

Quantity Arithmetic Result
Transfers/day given 10,000,000
Average rate 10M รท 86,400 โ‰ˆ 115/s
Peak ร—9 (payday lunchtime) โ‰ˆ 1,000/s
Postings/day 10M ร— 2 20M
Storage/year 20M ร— 365 ร— 200 B โ‰ˆ 1.5 TB (plus indexes)

High-level design

Mobile / web โ”€โ”€โ–บ API Management โ”€โ”€โ–บ Transfers API (ASP.NET Core)
                                         โ”‚  idempotency key, fraud/limits check
                                         โ–ผ
                                Ledger service โ”€โ”€โ–บ Azure SQL (Business Critical, zone redundant)
                                         โ”‚            Accounts(Balance, RowVersion)
                                         โ”‚            JournalEntries, Postings (append-only, ledger tables)
                                         โ”‚            IdempotencyKeys, Outbox
                                         โ–ผ outbox
                                Service Bus โ”€โ”€โ–บ External payments gateway โ”€โ”€โ–บ payment scheme
                                                     โ”‚ confirmations / rejections
                                                     โ–ผ
                                Ledger: clearing โ†’ settlement, or reversal
                                Daily: trial balance, clearing reconciliation, statements

Account types

Account Purpose
Customer accounts Balances customers see
Clearing (per scheme) Money in flight to/from other banks
Settlement The bank's position with the scheme
Fees / interest / suspense Bank revenue, expenses, unidentified money

Production example

A wallet ledger on Azure SQL Business Critical sustained [1,200] transfers a second in load tests at p95 [90 ms]. The daily trial balance (sum of all postings = 0) and clearing reconciliation caught a scheme-message mapping bug on day one that would otherwise have left [$38,000] in a clearing account unexplained.

๐Ÿ” What the interviewer is checking

Checks that the candidate can design a correct ledger (double-entry, concurrency, idempotency, asynchronous settlement, audit) and knows where it stops scaling and why.

Green flags

  • Double-entry with zero-sum postings and append-only corrections
  • Correct concurrency control (conditional update, lock ordering)
  • Idempotency key in the same transaction
  • Clearing accounts for external transfers, pending balances and daily reconciliation
  • Identifies hot accounts and the single-writer limit, and explains sub-accounts or sharding with clearing sagas

Red flags

  • Balance column updated in place with no history
  • Read-check-write races
  • Microservices with debit and credit in different databases and no compensation
  • No audit or reconciliation story, or no idea where the design hits its throughput limit

๐Ÿ“š Learn in depth

1. Double-entry from first principles

Every movement has two sides. Represent it as a journal entry with N postings whose amounts sum to zero.

JournalEntry 9001: "Transfer Aโ†’B", idempotencyKey = k-123
   Posting: Account A   -5,000
   Posting: Account B   +5,000
                        ------
                             0   โ† invariant, checked in code and by a daily query

Because postings are immutable, any balance at any time is SUM(amount) WHERE account = X AND postedAt <= T. The materialised balance is a cache of that sum, updated in the same transaction.

2. Concurrency control

Two transfers from the same account at once must not both spend the last $50.

  • Conditional update: UPDATE Accounts SET Balance -= @amt WHERE Id = @a AND Balance + OverdraftLimit >= @amt. The row lock makes it atomic; zero rows affected = insufficient funds. Simple and fast.
  • Lock ordering: when updating two accounts, always update the lower id first. Otherwise Aโ†’B and Bโ†’A can deadlock (error 1205). Retry deadlock victims with backoff anyway.
  • Optimistic concurrency (rowversion) works, but under contention on popular accounts it produces many retries.

Read committed (RCSI on Azure SQL by default) is enough when every invariant is enforced by the conditional update inside the transaction. Don't read the balance in one statement and write it in another.

3. Exactly-once effect

The client generates an idempotency key per transfer intent. Insert it into IdempotencyKeys (unique) in the same transaction as the postings; on a duplicate-key error, read and return the stored result. That turns at-least-once requests into exactly-once effects.

4. External transfers and clearing

T0  customer A  -100   clearing(NPP) +100   (pending, visible to customer)
T1  scheme confirms:   clearing -100  settlement +100
    or scheme rejects: clearing -100  customer A +100 (reversal)

The clearing account's balance equals money in flight. If it doesn't return to the expected value, something is stuck; reconciliation against the scheme's reports finds it. Fast schemes (like the NPP in Australia) confirm in seconds; batch schemes (like BECS direct entry) settle later, so 'pending' may last until the next business day.

5. Hot accounts

A fee account or a merchant receiving thousands of credits a second becomes a lock hotspot. Options: split into N sub-accounts and pick one at random (the logical balance is the sum); credit asynchronously in batches; or don't maintain a materialised balance for internal accounts and compute it from postings.

6. Audit and tamper evidence

  • Append-only postings; no UPDATE/DELETE permissions for the application login.
  • Azure SQL / SQL Server ledger tables (append-only ledger tables) keep a cryptographic hash chain, with database digests that can be stored in immutable Blob Storage, so tampering is detectable.
  • Who-did-what for manual adjustments, with maker-checker approval.
  • Retention per regulatory requirements; personal data protected under the Privacy Act.

7. Scaling beyond one database

At much higher volumes, shard by account id. Transfers within a shard stay ACID; cross-shard transfers become a saga via a clearing account per shard, exactly like external transfers. That is why the clearing pattern is worth understanding first.

8. AWS mapping

Aurora PostgreSQL or RDS SQL Server for the ledger, QLDB is no longer an option for new designs (AWS announced its end of support), so use database-level immutability and S3 Object Lock for digests; SQS/EventBridge for events.

Try it yourself

  1. Create the tables below and run 50 concurrent transfers between two accounts in opposite directions; observe deadlocks without lock ordering and none with it.
  2. Assert the trial balance query returns 0 after a random test of 10,000 transfers.
  3. Send the same idempotency key twice concurrently; confirm one journal entry.
  4. Simulate a scheme rejection and check the clearing account returns to zero.
  5. Create an append-only ledger table in Azure SQL and run sys.sp_verify_database_ledger against a digest.

๐Ÿ’ป Code

An internal transfer in one transaction: idempotency, lock ordering, overdraft check, double-entry postings.

CREATE TABLE dbo.Accounts (
    Id bigint PRIMARY KEY, Currency char(3) NOT NULL,
    Balance bigint NOT NULL,            -- minor units (cents)
    OverdraftLimit bigint NOT NULL DEFAULT 0
);
CREATE TABLE dbo.JournalEntries (
    Id bigint IDENTITY PRIMARY KEY, IdempotencyKey varchar(64) NOT NULL UNIQUE,
    Description nvarchar(200) NOT NULL, CreatedAt datetime2 NOT NULL DEFAULT SYSUTCDATETIME()
);
CREATE TABLE dbo.Postings (
    Id bigint IDENTITY PRIMARY KEY, JournalEntryId bigint NOT NULL REFERENCES dbo.JournalEntries(Id),
    AccountId bigint NOT NULL REFERENCES dbo.Accounts(Id), Amount bigint NOT NULL
) WITH (LEDGER = ON (APPEND_ONLY = ON));  -- tamper-evident, no updates or deletes

-- Daily invariant: must return 0
SELECT SUM(Amount) AS TrialBalance FROM dbo.Postings;
using System.Data;
using Microsoft.Data.SqlClient;

namespace Ledger;

public sealed record TransferRequest(string IdempotencyKey, long FromAccount, long ToAccount, long AmountMinor);
public enum TransferResult { Completed, InsufficientFunds, Duplicate }

public sealed class TransferService(string connectionString)
{
    public async Task<TransferResult> TransferAsync(TransferRequest r, CancellationToken ct)
    {
        ArgumentOutOfRangeException.ThrowIfNegativeOrZero(r.AmountMinor);
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        await using var tx = (SqlTransaction)await conn.BeginTransactionAsync(IsolationLevel.ReadCommitted, ct);
        try
        {
            // 1. Idempotency: the unique index makes a concurrent duplicate fail here.
            var entryId = (long)(await Scalar(conn, tx,
                "INSERT dbo.JournalEntries(IdempotencyKey, Description) OUTPUT inserted.Id VALUES (@k, N'Transfer')",
                ct, ("@k", r.IdempotencyKey)))!;

            // 2. Lock both accounts in id order to avoid Aโ†’B / Bโ†’A deadlocks.
            var (first, second) = r.FromAccount < r.ToAccount ? (r.FromAccount, r.ToAccount) : (r.ToAccount, r.FromAccount);
            await Exec(conn, tx, "SELECT Id FROM dbo.Accounts WITH (UPDLOCK, ROWLOCK) WHERE Id IN (@a, @b) ORDER BY Id", ct, ("@a", first), ("@b", second));

            // 3. Conditional debit: zero rows = insufficient funds. No read-then-write race.
            var debited = await Exec(conn, tx,
                "UPDATE dbo.Accounts SET Balance -= @amt WHERE Id = @from AND Balance + OverdraftLimit >= @amt",
                ct, ("@amt", r.AmountMinor), ("@from", r.FromAccount));
            if (debited == 0) { await tx.RollbackAsync(ct); return TransferResult.InsufficientFunds; }

            await Exec(conn, tx, "UPDATE dbo.Accounts SET Balance += @amt WHERE Id = @to", ct, ("@amt", r.AmountMinor), ("@to", r.ToAccount));

            // 4. Double-entry postings that sum to zero.
            await Exec(conn, tx, "INSERT dbo.Postings(JournalEntryId, AccountId, Amount) VALUES (@e, @from, -@amt), (@e, @to, @amt)",
                ct, ("@e", entryId), ("@from", r.FromAccount), ("@to", r.ToAccount), ("@amt", r.AmountMinor));

            await tx.CommitAsync(ct);
            return TransferResult.Completed;
        }
        catch (SqlException ex) when (ex.Number is 2601 or 2627) // duplicate idempotency key
        {
            await tx.RollbackAsync(ct);
            return TransferResult.Duplicate; // caller returns the original result looked up by key
        }
    }

    private static async Task<int> Exec(SqlConnection c, SqlTransaction t, string sql, CancellationToken ct, params (string, object)[] ps)
    {
        await using var cmd = new SqlCommand(sql, c, t);
        foreach (var (n, v) in ps) cmd.Parameters.AddWithValue(n, v);
        return await cmd.ExecuteNonQueryAsync(ct);
    }

    private static async Task<object?> Scalar(SqlConnection c, SqlTransaction t, string sql, CancellationToken ct, params (string, object)[] ps)
    {
        await using var cmd = new SqlCommand(sql, c, t);
        foreach (var (n, v) in ps) cmd.Parameters.AddWithValue(n, v);
        return await cmd.ExecuteScalarAsync(ct);
    }
}

โš  Common mistakes

  • Mistake: Storing only a balance and updating it in place. Why it is wrong: you can't explain or rebuild a balance, and a bug silently destroys history. Instead: append-only postings with a materialised balance updated in the same transaction.
  • Mistake: Reading the balance, checking it in C#, then writing. Why it is wrong: two concurrent transfers both pass the check and overdraw the account. Instead: conditional UPDATE or a lock held for the whole transaction.
  • Mistake: Locking accounts in request order. Why it is wrong: opposite transfers deadlock under load. Instead: lock in account-id order and retry deadlock victims.
  • Mistake: Deleting or editing wrong postings. Why it is wrong: destroys the audit trail and breaks regulatory requirements. Instead: post a reversing entry with a reason and approver.
  • Mistake: Treating an external transfer as complete when sent. Why it is wrong: the scheme can reject it later, and the money must come back. Instead: a clearing account and pending state until confirmation.
  • Mistake: Splitting debit and credit across two services with two databases and no saga. Why it is wrong: a crash between them creates or destroys money. Instead: keep both postings in one transaction, or use a clearing account and a saga with compensation.
  • Mistake: Floating-point amounts. Why it is wrong: rounding errors break the zero-sum invariant. Instead: integer minor units and an explicit currency per account.

๐Ÿ› Senior insight: trade-offs

The senior insight is that consistency boundaries follow the ledger: everything that must balance to zero goes in one transaction, and anything that crosses a boundary (another bank, another shard, another service) goes through a clearing account with an explicit pending state. That single idea explains internal transfers, external payments and future sharding. I'd also say plainly that a single, well-sized Azure SQL database is the right answer for a long time; sharding a ledger is a cost you pay only when the numbers force it.

Option When it fits Cost When not to
Single Azure SQL ledger Up to thousands of transfers/s Vertical scale, one writer Global multi-region writes
Sharded by account + clearing sagas Very high volume Cross-shard complexity, reconciliation Before you need it
Event-sourced ledger (append log + projections) Need full replay, temporal queries Projection lag, tooling Team new to event sourcing
Buy a core banking / ledger product Regulated bank, many products Licence and integration Small wallet with simple flows

I measure transfer latency, deadlocks and lock waits (Query Store, sys.dm_os_wait_stats), trial balance and clearing reconciliation results daily, and idempotent duplicates rejected.

๐Ÿ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions transactions or isolation levels Why: Checks which anomalies each isolation level prevents and which one the transfer really needs
    How to answer

    Isolation levels decide which anomalies a transaction can see. Read uncommitted takes no shared locks, so dirty reads are possible (it's what NOLOCK does). Read committed, the default, only reads committed data, using short-lived S locks, or row versions when RCSI is on, but a re-read can change (non-repeatable read). Repeatable read holds S locks to the end of the transaction, so rows you read can't change, but new rows can appear (phantoms). Serializable adds key-range locks so ranges can't change either. Snapshot gives a transaction-consistent view from row versions.

    The trade-off: each step up holds more locks for longer, which means more blocking and deadlocks. Pick the lowest level that is correct, and solve specific races with targeted locks or constraints.

  2. When: Candidate proposes optimistic concurrency with a row version Why: Checks lost updates and optimistic concurrency at the aggregate level
    How to answer

    This is a lost update / write skew: both requests loaded the order, each checked the 20% rule against its own copy, and both saved. Removing the line lowered the total; the discount was checked against the old total. Each change was valid alone; together they broke the invariant. EF Core only sends the changed columns, so neither UPDATE noticed the other.

    The fix is optimistic concurrency on the aggregate root: a rowversion column configured with IsRowVersion(), and every behaviour method (including removing a child line) modifies the root so its version changes. EF Core then adds WHERE RowVersion = @original and throws DbUpdateConcurrencyException when 0 rows are affected. Carry the version to clients as an ETag and require If-Match, returning 412. On conflict, reload and re-run the command or ask the user. The trade-off: occasional retries in exchange for no silent corruption.

  3. When: Candidate says transfers are exactly once Why: Checks how idempotency keys turn at-least-once requests into exactly-once effects
    How to answer

    An operation is idempotent if doing it once or many times leaves the system in the same state. It's the core tool because distributed systems produce duplicates all the time: clients retry after timeouts, brokers deliver at least once, users double-click. You get it in two ways. Some operations are naturally idempotent: 'set status to Shipped', a PUT of the full resource, an upsert by a natural key. The rest need deduplication: the caller sends a unique idempotency key (or the broker supplies a message id), and the service records it under a unique constraint in the same transaction as the business change, so a repeat is detected and answered with the stored result. The trade-off is storage and a little complexity, against duplicate charges, orders and emails.

๐Ÿ›  Real-world problems: how you handle them

Payday deadlocks and a clearing account that didn't balance
Situation
A digital wallet for [a credit union], [600,000] customers, ledger on [Azure SQL], transfers peaking at [800/s] on payday. External payments via [the NPP through a sponsor bank].
Signals
Error 1205 deadlocks in Application Insights every payday lunchtime; [2%] of transfers failing; finance noticed the NPP clearing account [$12,400] off after month-end.
Investigation
Captured deadlock graphs from the `system_health` Extended Events session: A→B and B→A transfers locked accounts in request order. For the clearing gap, reconciled clearing postings against the sponsor bank's report and found rejections arriving with a status code our mapper ignored, so no reversals were posted.
Resolution
Immediate: deadlock retries with backoff and manual reversals approved by finance. Long term: account locks in id order with a conditional debit, mapping for all scheme status codes with an 'unknown status' alert, and an automated daily clearing reconciliation.
Prevention
Concurrency load test of opposite transfers in CI; a daily trial-balance and clearing check that pages on any non-zero result; an ADR describing the ledger invariants.

How to tell it (STAR)

**S:** At [company] our wallet ledger hit deadlocks every payday and finance found the clearing account [$12,400] out at month-end. **T:** I owned the ledger and needed both fixed before the next payday. **A:** Deadlock graphs showed transfers locking accounts in request order, so I switched to id-order locking with a conditional debit. For the clearing gap I reconciled against the sponsor bank's report and found rejection codes we didn't map, so no reversals were posted. I fixed the mapping, added an alert for unknown codes, and automated a daily trial balance and clearing reconciliation. **R:** Payday deadlocks went from [about 2%] of transfers to [zero], and the clearing account has balanced every day since.

More in Systems to Design

Last updated 23 Nov 2026.

๐ŸŒ Sangam's Webring

โช Previous ๐Ÿ  Main Next โฉ
๐Ÿ’ฌ Chat with me