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.
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.
"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."
| 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 |
| 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) |
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 | 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 |
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.
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
Red flags
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.
Two transfers from the same account at once must not both spend the last $50.
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.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.
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.
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.
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.
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.
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.
sys.sp_verify_database_ledger against a digest.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);
}
}
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.
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.
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.
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.
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.
Last updated 23 Nov 2026.