Designing a High-Throughput Financial Ledger Service
System DesignModel answerLast updated
Design an accurate, idempotent, and highly concurrent banking ledger database schema and transaction pipeline.
Create a data architecture and service layer for a core banking application handling deposits, withdrawals, balance checks, and transaction auditing.
System Requirements
- Strict Data Integrity: Prevent negative balances on withdrawal operations unless explicitly authorized. Ensure atomic state updates.
- Concurrency Controls: Support high volume without introducing race conditions, dirty reads, or lost updates under concurrent access.
- Idempotent API: Ensure client-side retries (due to dropped connections or timeouts) do not execute duplicate operations or cause double-spending.
- Immutable Audit Log: Every financial operation must produce an append-only transaction record for regulatory compliance and auditability.
Key Deliverables
- Define a relational database schema (including
accountsandtransactionstables). - Outline the step-by-step logic for a
withdraw(account_id, amount, idempotency_key)function. Include code/pseudocode showing transaction boundaries and lock management. - Detail how your solution handles floating-point errors, high overall system throughput (10,000+ operations/sec), and idempotency key misuses.
Hints
Hint 1
Avoid floating point types for currency; represent amounts using integer values of the smallest monetary subunit (e.g., cents).
Hint 2
Combine reading, validating, and mutating state inside a single database row lock or atomic UPDATE query to prevent lost updates under concurrency.
Hint 3
Use a unique database constraint on (account_id, idempotency_key) to safely handle concurrent identical requests.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Architecture Overview
A production financial ledger requires strong consistency per account. While global scale may reach 10,000+ requests per second across the entire application, individual account operations can be partitioned (sharded) by account_id. This allows us to leverage localized ACID transactions within single relational database nodes without requiring slow cross-node distributed locks.
1. Database Schema Design
We maintain two primary entities:
accounts: Stores current metadata and a cached (materialized) balance for rapid $O(1)$ reads.transactions: An append-only historical audit trail.
CREATE TABLE accounts (
id BIGINT PRIMARY KEY,
currency_code CHAR(3) NOT NULL, -- e.g. 'USD', 'EUR', 'JPY'
balance BIGINT NOT NULL DEFAULT 0 CHECK (balance >= 0),
version BIGINT NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE TABLE transactions (
id BIGINT PRIMARY KEY, -- Snowflake ID or UUIDv7
account_id BIGINT NOT NULL REFERENCES accounts(id),
idempotency_key VARCHAR(255) NOT NULL,
tx_type VARCHAR(32) NOT NULL CHECK (tx_type IN ('DEPOSIT', 'WITHDRAWAL')),
amount BIGINT NOT NULL CHECK (amount > 0),
status VARCHAR(32) NOT NULL CHECK (status IN ('SUCCESS', 'INSUFFICIENT_FUNDS')),
balance_after BIGINT,
payload_hash CHAR(64) NOT NULL, -- SHA-256 hash of (account_id, amount, tx_type)
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
CONSTRAINT uq_account_idempotency UNIQUE (account_id, idempotency_key)
);
CREATE INDEX idx_transactions_account_created
ON transactions (account_id, created_at DESC);
Key Schema Decisions:
- Minor Units:
balanceandamountare stored asBIGINTrepresenting minor currency units (e.g., $100.50 \text{ USD} \rightarrow 10050 \text{ cents}$). This eliminates floating-point rounding errors. - Data Integrity Constraints: The
CHECK (balance >= 0)constraint serves as a database-level safety net to prevent overdrafts regardless of application-level bugs. - Append-Only Ledger: Database permissions for the application user should restrict
UPDATEandDELETEontransactions, ensuring the transaction log remains an immutable audit record.
2. Core Service Logic & Implementation
The withdraw service handles three primary challenges:
- Idempotency: Retrying with the same key must return the previous result without altering the balance twice.
- Atomic Execution: Balance reduction and transaction logging must occur within a single database transaction.
- Preventing Race Conditions: Concurrent requests for the same account must be serialized safely.
import hashlib
import psycopg2
from psycopg2.errors import UniqueViolation
def withdraw(conn, account_id: int, amount_cents: int, idempotency_key: str) -> dict:
if amount_cents <= 0:
raise ValueError("Amount must be greater than zero.")
# Generate hash to ensure key isn't reused for different payload arguments
raw_payload = f"WITHDRAWAL:{account_id}:{amount_cents}"
payload_hash = hashlib.sha256(raw_payload.encode('utf-8')).hexdigest()
# Step 1: Fast-path check for existing operation (Read-unlocked)
existing_record = _get_transaction_record(conn, account_id, idempotency_key)
if existing_record:
return _process_replay(existing_record, payload_hash)
# Step 2: Atomic Execution within Database Transaction
try:
with conn.transaction():
# Perform atomic update with conditional guard to prevent overdrafts.
# Acquires an explicit row lock on the affected account.
cursor = conn.cursor()
cursor.execute(
"""
UPDATE accounts
SET balance = balance - %s,
version = version + 1,
updated_at = NOW()
WHERE id = %s AND balance >= %s
RETURNING balance;
""",
(amount_cents, account_id, amount_cents)
)
updated_row = cursor.fetchone()
if updated_row:
status = "SUCCESS"
new_balance = updated_row[0]
else:
status = "INSUFFICIENT_FUNDS"
new_balance = None
# Record ledger record inside the same transaction boundary
cursor.execute(
"""
INSERT INTO transactions (
id, account_id, idempotency_key, tx_type,
amount, status, balance_after, payload_hash
) VALUES (
generate_snowflake_id(), %s, %s, 'WITHDRAWAL',
%s, %s, %s, %s
);
""",
(account_id, idempotency_key, amount_cents, status, new_balance, payload_hash)
)
return {"status": status, "balance_after": new_balance}
except UniqueViolation:
# Step 3: Handle race conditions on idempotency key
# If two identical retries hit concurrently, one fails the unique index constraint.
# The failed transaction rolls back automatically; fetch and replay the winning attempt's outcome.
committed_record = _get_transaction_record(conn, account_id, idempotency_key)
return _process_replay(committed_record, payload_hash)
def _get_transaction_record(conn, account_id: int, idempotency_key: str):
cursor = conn.cursor()
cursor.execute(
"""
SELECT status, balance_after, payload_hash
FROM transactions
WHERE account_id = %s AND idempotency_key = %s;
""",
(account_id, idempotency_key)
)
return cursor.fetchone()
def _process_replay(record, expected_hash: str) -> dict:
status, balance_after, stored_hash = record
if stored_hash != expected_hash:
# Idempotency key payload mismatch error (HTTP 422 / 409)
raise ValueError("Idempotency key reused with conflicting transaction parameters.")
return {"status": status, "balance_after": balance_after}
3. Key Engineering Considerations
Concurrency & Lock Management
- Single-Statement Locking: The
UPDATE accounts SET balance = balance - X WHERE balance >= Xpattern implicitly locks the target account row for the duration of the SQL transaction. This avoids a read-modify-write window without needing manualSELECT FOR UPDATElocks. - Avoiding Lost Updates: Plain
SELECT balancefollowed by application-side calculation and an un-guardedUPDATEcauses lost updates under load. The atomic conditionalUPDATEprevents race conditions natively at the engine level.
Financial Precision
- Floating-point representations (e.g., IEEE 754
floatordouble) cannot exactly represent base-10 decimals (e.g., $0.1 + 0.2 \neq 0.3$). - All API inputs are converted to integer minor units immediately at the service boundary.
- Currencies with different subunit bases (e.g.,
USDwith 2 decimals vsJPYwith 0 decimals vsBHDwith 3 decimals) maintain an explicit exponent scale map per currency code.
High Throughput & Scaling Strategy (10,000+ RPS)
- Database Partitioning / Sharding: Shard database instances using a hash of
account_id. Since all operations (balance update, transaction logging) target a single account, ACID properties are maintained locally without distributed transactions (e.g., 2PC). - Asynchronous Reconciliation: An offline asynchronous worker periodically computes
SUM(amount)from the append-onlytransactionstable and compares it againstaccounts.balanceto catch drift or data corruption early.