Skip to main content
← PROBLEMS / CONCURRENCY
An end-to-end domain learning journey

Design an Atomic Payment Ledger &
Reservation Engine Preventing TOCTOU Races.

Combine an atomic INSERT ... ON CONFLICT idempotency gate with single-statement conditional UPDATE + version CAS and an immutable double-entry ledger table.
Start the journey7 stages· Last modified Nov 22, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, execute balance check, version increment, and idempotency claim inside one short local ACID transaction—never across external RPCs.

TL;DR30-second simplified summary
▾

At 25K debits/sec, naive SELECT balance followed by application-side if balance >= amount and UPDATE leaks millions during mobile retry storms and flash sales.

The hardened architecture enforces three atomic layers: (1) an Idempotency-Key table claimed via INSERT ... ON CONFLICT DO NOTHING + SHA-256 payload hash check; (2) a single conditional UPDATE ledger_accounts SET balance = balance - :amt, version = version + 1 WHERE id = :id AND balance >= :amt AND version = :v; and (3) an append-only ledger_entries insert in the same local PostgreSQL transaction.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
TOCTOU Race Conditions & Atomic Compare-And-Swap (CAS)
Time-of-Check to Time-of-Use (TOCTOU) race conditions occur when state validated in step 1 changes before step 2 mutates it; Atomic Compare-And-Swap (CAS) closes the gap in a single indivisible operation.
Optimistic Concurrency Control
A lock-free concurrency pattern that lets readers and writers proceed without blocking, validating at commit time via a version number or ETag that no one else modified the record.
Deadlock Detection & Prevention
Identifying and resolving circular wait conditions—where two or more threads or database transactions hold locks each other needs—via wait-for graph cycle detection, timeouts, or canonical lock ordering.
Full walkthrough · 7 stages
01
STAGE 01 · CORE INTUITIONfoundation

Scale Envelope & Latency Budget.

Why this matters: Size 25K concurrent debits/sec across 10M accounts with zero overdraft TOCTOU races and strict idempotency.

Think of Scale Envelope & Latency Budget as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Size 25K concurrent debits/sec across 10M accounts with zero overdraft TOCTOU races and strict idempotency.

Design a payment reservation and double-entry ledger service handling 25K concurrent debits/sec across 10M accounts with zero negative-balance TOCTOU races, strict idempotency on client retries, and full auditability.

STAGE 01 · CORE INTUITION

Scale Envelope & Latency Budget

25K Debits / SecThroughput TargetRead-Check-Write GapTOCTOU HazardSingle-Tx SQL CASAtomic Guarantee<25ms p99 CommitProduction SLAclosed by

1.Throughput & Scale: 25,000 debits/sec across 10M ledger accounts with double-entry auditability.

2.Zero Overdraft Invariant: Two simultaneous $80 debits on a $100 account must never both succeed.

3.Retry Safety: Mobile client retries on 504 timeouts must return the original receipt without double-debiting.

Single-transaction conditional SQL updates and Idempotency-Key claims prevent TOCTOU overdrafts at 25K debits/sec.

02
STAGE 02 · CORE MECHANICSfoundation

Core Architecture & Data Flow.

Why this matters: Enforce Idempotency-Key deduplication, conditional balance update, and double-entry journal insert in one ACID commit.

Think of Core Architecture & Data Flow as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Enforce Idempotency-Key deduplication, conditional balance update, and double-entry journal insert in one ACID commit.

The hardened architecture enforces three atomic layers: (1) an Idempotency-Key table claimed via INSERT ... ON CONFLICT DO NOTHING + SHA-256 payload hash check; (2) a single conditional UPDATE ledger_accounts SET balance = balance - :amt, version = version + 1 WHERE id = :id AND balance >= :amt AND version = :v; and (3) an append-only ledger_entries insert in the same local PostgreSQL transaction.

STAGE 02 · CORE MECHANICS

Core Architecture & Data Flow

Idempotency TableRetry BarrierConditional UPDATEAtomic BalanceLedger EntriesTableDouble-Entry LogCommitted ReceiptSafe Responserecords entry

1.Payload Hash Check: Compare SHA-256 of incoming body against stored payload_hash to catch buggy key reuse.

2.Single-Statement CAS: UPDATE ledger_accounts SET balance = balance - amt WHERE id = $1 AND balance >= $2.

3.Atomic Audit Trail: Balance mutation and double-entry journal rows commit or roll back together.

Idempotency claim, conditional balance debit, and double-entry journal write execute inside one ACID transaction.

Engineering Decision Framework
Problem
How to implement Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races without hitting unbounded tail latency, state divergence, or operational fragility.
Naive Solution
Use a single unpartitioned path with unbounded retries and synchronous global coordination.
Why It Fails
Global coordination serializes throughput under load, while unbounded retries amplify transient stalls into full outages.
Alternatives
Compare synchronous strict-consistency paths against bounded asynchronous replication, local caching, or partitioned ownership.
Engineering Decision
When traffic spikes expose hidden coupling, execute balance check, version increment, and idempotency claim inside one short local ACID transaction—never across external RPCs.
Trade-Offs
Gains predictable p99 latency and fault isolation in exchange for explicit bounding, observability, and slightly higher implementation complexity.
Decision Exercise · Make the Call

When Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · SAFE IMPLEMENTATIONintermediate

Atomic Conditional Debit & Idempotency Gate.

Why this matters: Execute execute_atomic_debit with positive-amount validation, conflict detection, and row-count checking.

Think of Atomic Conditional Debit & Idempotency Gate as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Execute execute_atomic_debit with positive-amount validation, conflict detection, and row-count checking.

def execute_atomic_debit(cur, account_id: str, amount: int, idem_key: str, payload_hash: str) -> dict:
    if amount <= 0:
        raise ValueError('Debit amount must be positive')
    cur.execute(
        'INSERT INTO idempotency_keys(key, payload_hash, status) VALUES (%s, %s, %s) ON CONFLICT (key) DO NOTHING',
        (idem_key, payload_hash, 'IN_PROGRESS'),
    )
    if cur.rowcount == 0:
        return {'status': 'DUPLICATE_OR_IN_FLIGHT'}
    cur.execute(
        'UPDATE accounts SET balance = balance - %s, version = version + 1 WHERE id = %s AND balance >= %s RETURNING balance, version',
        (amount, account_id, amount),
    )
    row = cur.fetchone()
    if row is None:
        raise ValueError('Insufficient funds or missing account')
    return {'status': 'COMMITTED', 'balance': row[0], 'version': row[1]}
STAGE 03 · SAFE IMPLEMENTATION

Atomic Conditional Debit & Idempotency Gate

Amount > 0 GuardInput CheckINSERT Idem-KeyDedup GateUPDATE ...RETURNINGAtomic CheckCommit & SaveReceiptClean Resultif new key

1.Fail Fast on Bad Input: Reject non-positive debit amounts before acquiring database connections.

2.Explicit Row-Count Check: If UPDATE affects 0 rows, roll back the idempotency claim and raise InsufficientFunds.

3.Cached Replay: If INSERT conflicts with matching payload_hash, return the persisted receipt immediately.

Validating positive amounts, checking INSERT conflict, and inspecting UPDATE row counts prevent double-debits.

04
STAGE 04 · SCALING & TRADE-OFFSintermediate

Sharding & Hot-Spot Mitigation.

Why this matters: Shard 10M accounts by account_id across Citus/PostgreSQL partitions and split hot merchant accounts into sub-buckets.

Think of Sharding & Hot-Spot Mitigation as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Shard 10M accounts by account_id across Citus/PostgreSQL partitions and split hot merchant accounts into sub-buckets.

Partition state deterministically and apply bounded-load or sub-bucket sharding for hot keys.

STAGE 04 · SCALING & TRADE-OFFS

Sharding & Hot-Spot Mitigation

Hash Shard(account_id)Horizontal ScaleHot Merchant AccountRow-Lock Hotspot16 Sub-AccountBucketsLock StripingAsync Rollup View25K+ TPS Scalestriped into

1.Co-Located Sharding: Shard both ledger_accounts and ledger_entries by account_id so single-account debits stay local.

2.Hot-Merchant Striping: Split high-volume clearing accounts into 16 sub-buckets to avoid single-row lock queues.

3.Cross-Account Transfers: Order lock acquisition deterministically by sorted account_id to prevent deadlocks.

Account-ID sharding and 16x sub-bucket striping for hot merchants sustain 25K+ TPS without row-lock contention.

05
STAGE 05 · FAULT ISOLATIONadvanced

Failure Modes & Graceful Degradation.

Why this matters: Isolate slow downstream settlement rails and poison retries using bounded locks, dead-letter queues, and circuit breakers.

Think of Failure Modes & Graceful Degradation as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Isolate slow downstream settlement rails and poison retries using bounded locks, dead-letter queues, and circuit breakers.

Apply circuit breakers, fallback caches, and dead-letter quarantine queues.

STAGE 05 · FAULT ISOLATION

Failure Modes & Graceful Degradation

lock_timeout = 50msLatency ShieldDB Pool BreakerCascade StopSettlement RetryDLQOrderly RecoveryRead-ReplicaOffloadWrite Isolationdefers async

1.Short Lock Timeouts: Set PostgreSQL lock_timeout = 50ms so contended rows shed cleanly instead of piling up connections.

2.Transactional Outbox: Write downstream webhook/settlement events to an outbox table in the same DB transaction.

3.Read Isolation: Route user balance-history queries to read replicas so analytical scans never stall debits.

50 ms lock timeouts, transactional outboxes, and read-replica isolation keep live debit commits fast under load.

06
STAGE 06 · RECOVERY & CONSISTENCYadvanced

Consistency, Idempotency & Recovery.

Why this matters: Guarantee zero lost or duplicated ledger state across primary failovers and client crashes via WAL sync and 24h key TTLs.

Think of Consistency, Idempotency & Recovery as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Guarantee zero lost or duplicated ledger state across primary failovers and client crashes via WAL sync and 24h key TTLs.

Enforce atomic state transitions, fencing/idempotency keys, and fast snapshot recovery.

STAGE 06 · RECOVERY & CONSISTENCY

Consistency, Idempotency & Recovery

Sync WALReplicationZero RPO24h Idempotency TTLRetry WindowOutbox Relay ReplayCrash RecoveryDaily Trial BalanceAudit Proofresumes

1.Synchronous Standby: Wait for synchronous_commit = remote_write on one AZ standby to guarantee zero lost commits.

2.Partitioned Key Expiry: Drop daily idempotency partitions after 24-72h without expensive vacuuming.

3.Continuous Reconciliation: Verify SUM(debits) == SUM(credits) across all accounts every hour.

Synchronous AZ replication, partitioned idempotency retention, and hourly trial-balance audits guarantee zero RPO.

07
STAGE 07 · OBSERVABILITY & GUARDRAILSadvanced

Telemetry, Circuit Breakers & Failure Modes.

Why this matters: Track lock-wait p99, idempotency cache-hit rates, overdraft rejections, and trial-balance drift.

Think of Telemetry, Circuit Breakers & Failure Modes as the intuition layer for Design an Atomic Payment Ledger & Reservation Engine Preventing TOCTOU Races: Track lock-wait p99, idempotency cache-hit rates, overdraft rejections, and trial-balance drift.

Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.

STAGE 07 · OBSERVABILITY & GUARDRAILS

Telemetry, Circuit Breakers & Failure Modes

lock_wait_ms p99Latency Signalidem_replay_rateNetwork Signaloverdraft_reject_t…Business SignalInvariant PagerZero-Drift Guardtracks

1.Zero-Imbalance Pager: Any non-zero difference between debits and credits pages on-call immediately as Sev-1.

2.Retry Surge Alert: A sudden jump in idempotency replays points to upstream gateway timeouts before users complain.

3.Pool Saturation: Alert when PostgreSQL active connections exceed 75% of max_connections.

Monitoring lock-wait p99, idempotency replay rates, and trial-balance invariants catches contention and bugs early.

Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why is `UPDATE accounts SET balance = balance - amt WHERE id = ? AND balance >= amt` immune to TOCTOU?

Recommended Learning Flow