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.
TL;DR30-second simplified summary▾
In concurrent services, non-atomic check-then-act logic (if balance >= amount: balance -= amount) opens a Time-of-Check to Time-of-Use (TOCTOU) race window. Two threads both observe balance == $100, pass the >= $80 check, and both deduct $80—driving the account to -$60.
Hardware Compare-And-Swap (AtomicInteger.compareAndSet(expected, update)), database conditional updates (UPDATE ... WHERE balance >= amount AND version = v), and Redis Lua scripts eliminate the TOCTOU window by executing validation and mutation as one indivisible atomic step.
Under high contention, CAS retry loops should use bounded exponential backoff + jitter and pair with ABA generational tags (AtomicStampedReference) when pointers or reusable values are compared.
From patterns to decisions.
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.
Core Intuition & Failure Mode.
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.
Core Intuition & Failure Mode
1.Stage Objective: Understand the baseline failure mode.
2.Level (Foundation): 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-
3.Operational Invariant: Understand the baseline failure mode.
Caption: Understand the baseline failure mode.
Architectural Mechanics.
Hardware Compare-And-Swap (AtomicInteger.compareAndSet(expected, update)), database conditional updates (UPDATE ... WHERE balance >= amount AND version = v), and Redis Lua scripts eliminate the TOCTOU window by executing validation and mutation as one indivisible atomic step.
Architectural Mechanics
1.Stage Objective: Trace the core mechanism end-to-end.
2.Level (Foundation): Hardware Compare-And-Swap (`AtomicInteger.compareAndSet(expected, update)`), database conditional updates (`UPDATE ... WHERE balance >= amou
3.Operational Invariant: Trace the core mechanism end-to-end.
Caption: Trace the core mechanism end-to-end.
Atomic CAS Loop with Bounded Retries.
import threading
class AtomicBalance:
def __init__(self, initial: int) -> None:
if initial < 0:
raise ValueError('Initial balance cannot be negative')
self._lock = threading.Lock()
self._balance = initial
self._version = 0
def withdraw_cas(self, amount: int) -> tuple[bool, int]:
if amount <= 0:
raise ValueError('Amount must be positive')
with self._lock:
if self._balance < amount:
return False, self._balance
self._balance -= amount
self._version += 1
return True, self._balanceAtomic CAS Loop with Bounded Retries
1.Stage Objective: Execute check-and-debit atomically with bounded backoff to prevent livelock.
2.Level (Intermediate): import threading
3.Operational Invariant: Execute check-and-debit atomically with bounded backoff to prevent livelock.
Caption: Execute check-and-debit atomically with bounded backoff to prevent livelock.
Throughput & Latency Trade-Offs.
Evaluate asymptotic bounds, cache locality, and tail-latency impact under peak load.
Throughput & Latency Trade-Offs
1.Stage Objective: Quantify operational complexity and memory bounds.
2.Level (Intermediate): Evaluate asymptotic bounds, cache locality, and tail-latency impact under peak load.
3.Operational Invariant: Quantify operational complexity and memory bounds.
Caption: Quantify operational complexity and memory bounds.
Blast-Radius & Failure Isolation.
Isolate shared resources, apply bounded queues, and prevent retry amplification.
Blast-Radius & Failure Isolation
1.Stage Objective: Contain failures without cascading across tenants or nodes.
2.Level (Advanced): Isolate shared resources, apply bounded queues, and prevent retry amplification.
3.Operational Invariant: Contain failures without cascading across tenants or nodes.
Caption: Contain failures without cascading across tenants or nodes.
Durability, Consistency & Recovery.
Use idempotent state transitions, atomic commits, and deterministic replay.
Durability, Consistency & Recovery
1.Stage Objective: Preserve invariants across crashes and restarts.
2.Level (Advanced): Use idempotent state transitions, atomic commits, and deterministic replay.
3.Operational Invariant: Preserve invariants across crashes and restarts.
Caption: Preserve invariants across crashes and restarts.
Telemetry, Circuit Breakers & Failure Modes.
Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants degrade.
Production Guardrails
1.Stage Objective: Monitor tail latency, error budgets, and invariant violations in production.
2.Level (Advanced): Track p99 latency, retry/conflict ratios, and saturation metrics; fail fast with bounded retries and circuit breakers whenever invariants de
3.Operational Invariant: Bounded retries, telemetry alerts, and circuit breakers prevent cascading failures.
Caption: Bounded retries, telemetry alerts, and circuit breakers prevent cascading failures.
Practice: Make the trade-off yourself.
Why does `if balance >= 80: balance -= 80` fail under two concurrent threads?