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

Preventing AB-BA Deadlocks
with Lock Ordering.

Two concurrent transfers—Account A to B and Account B to A—acquire locks in opposite orders, satisfying all four Coffman conditions and freezing both threads permanently.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, enforce a strict total order on lock acquisition using a unique, immutable key (e.g., accountId) plus a global tie-breaker lock for equal hash codes, or use timed tryLock with randomized backoff.

TL;DR30-second simplified summary
▾

Core Mechanics: A Java ledger service executes concurrent transfer(Account from, Account to, long amount) across 10M accounts at 25,000 TPS.

Visual & Structural Flow: Depicts Cyclic Monitor Freeze vs. Canonical ID Lock Ordering (Thread 1 (A->B) -> Lock A (id=10) -> Lock B (id=99) -> Thread 2 (B->A)); Canonical Ordering Eliminates Cycles (COMPARE IDs -> LOCK FIRST -> LOCK SECOND).

Trade-Offs & Production: Using a single global ReentrantLock serializes all 10M accounts to 1 thread at a time, destroying 25,000 TPS throughput. Guarantee deadlock freedom while scaling across 10M accounts: Strict Total Order by Immutable accountId: Guard if (from.id == to.id) return; then always lock first = from.id < to.id ? from : to before second.

Failure Modes & Application: Canonical lock ordering is a universal primitive for multi-resource atomicity: Payment & Double-Entry Ledgers: Atomic debit(from) + credit(to) in both JVM memory and SQL ORDER BY id FOR UPDATE.

Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why Preventing AB-BA Lock Deadlocks Matters.

Why this matters: The mechanism: understand how Why Preventing AB-BA Lock Deadlocks Matters works from first principles.

A Java ledger service executes concurrent transfer(Account from, Account to, long amount) across 10M accounts at 25,000 TPS.

Under hot-account contention (merchant settlement pools), threads freeze in BLOCKED state with jstack showing cyclic monitor ownership (Thread-1 holds A waiting for B; Thread-2 holds B waiting for A).

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Real-World Impact of Cyclic AB-BA Locking.

Why this matters: The problem: see what breaks without Real-World Impact of Cyclic AB-BA Locking under real concurrency or scale.

When two threads acquire locks in opposite orders:

  1. Permanent Thread Freeze: synchronized monitors have no timeout or deadlock detector—blocked threads stay hung until JVM restart.
  2. Worker Pool Exhaustion: As other threads touch either A or B, they pile up behind the deadlocked pair, halting all 25,000 TPS.
  3. Hash-Collision Trap: Ordering by System.identityHashCode() alone can still deadlock on rare 32-bit hash collisions.
Cyclic AB-BA Deadlock vs. Total Lock Ordering

Cyclic Monitor Freeze vs. Canonical ID Lock Ordering

Thread 1 (A->B)Lock A (id=10)Lock B (id=99)Thread 2 (B->A)1. Naive: T1 locks A, T2 locks B2. T1 waits B; T2 waits A ->DEADLOCK!3. Fixed: Both order min(id)=10 ->max(id)=994. T2 waits on Lock A (no cycle!),then acquires B

Enforcing a strict total order (min accountId -> max accountId) makes lock-wait graphs acyclic by construction.

Engineering Decision Framework
Problem
How to implement Preventing AB-BA Deadlocks with Lock Ordering 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, enforce a strict total order on lock acquisition using a unique, immutable key (e.g., accountId) plus a global tie-breaker lock for equal hash codes, or use timed tryLock with randomized backoff.
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 Preventing AB-BA Deadlocks with Lock Ordering experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · NAIVE SOLUTIONL5 · APPLIED DESIGN

Naive Solution (and Why It Breaks).

Why this matters: The problem: see what breaks without Naive Solution under real concurrency or scale.

Using a single global ReentrantLock serializes all 10M accounts to 1 thread at a time, destroying 25,000 TPS throughput.

Locking from then to without ordering deadlocks on concurrent A->B and B->A transfers.

Request & State Flow

Naive Solution (and Why It Breaks)

Client TxPlanner / Lock MgrWAL / MemTableHeap / SSTable1. Acquire snapshot / index plan2. Append redo record + fsync WAL3. Flush dirty pages / compactSSTables4. Commit & release row locks
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise Solution: Canonical `accountId` Ordering + Tie-Breaker / `tryLock`.

Why this matters: Operational control: configure bounds, failure handling, and safe production defaults.

Guarantee deadlock freedom while scaling across 10M accounts:

  • Strict Total Order by Immutable accountId: Guard if (from.id == to.id) return; then always lock first = from.id < to.id ? from : to before second. Because A < B globally, no cycle can ever form.
  • Hash-Code Tie-Breaker (if no unique ID): If ordering by System.identityHashCode, acquire a global TIE_LOCK only on the 1-in-2322^{32} hash collision.
  • Timed tryLock + Jitter / DB Alignment: For ReentrantLocks or multi-row SQL (SELECT ... FROM accounts WHERE id IN ($1, $2) ORDER BY id FOR UPDATE), consistent ascending ID order prevents both JVM and PostgreSQL deadlocks.
Acyclic Lock Acquisition

Canonical Ordering Eliminates Cycles

from.id != to.idno cycle possibleCOMPARE IDsfirst=min, second=maxLOCK FIRSTalways smaller IDLOCK SECONDatomic transfer + unlock

Every thread traverses account locks in strictly increasing ID order, guaranteeing a DAG with zero deadlocks.

import java.util.*;
import java.util.concurrent.locks.ReentrantLock;

public class LedgerService {
    public static final class Account {
        private final long id;
        private long balance;
        private final ReentrantLock lock = new ReentrantLock();
        public Account(long id, long balance) { this.id = id; this.balance = balance; }
        public long id() { return id; }
    }

    public void transfer(Account from, Account to, long amount) {
        if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
        if (from.id() == to.id()) return;

        Account first = from.id() < to.id() ? from : to;
        Account second = from.id() < to.id() ? to : from;

        first.lock.lock();
        try {
            second.lock.lock();
            try {
                if (from.balance < amount) throw new IllegalStateException("Insufficient funds");
                from.balance -= amount;
                to.balance += amount;
            } finally {
                second.lock.unlock();
            }
        } finally {
            first.lock.unlock();
        }
    }

    public void batchTransfer(Map<Account, Long> deltas) {
        List<Account> ordered = deltas.keySet().stream()
                .sorted(Comparator.comparingLong(Account::id))
                .distinct()
                .toList();
        List<Account> acquired = new ArrayList<>(ordered.size());
        try {
            for (Account acc : ordered) {
                acc.lock.lock();
                acquired.add(acc);
            }
            for (var entry : deltas.entrySet()) {
                if (entry.getKey().balance + entry.getValue() < 0) {
                    throw new IllegalStateException("Insufficient funds: " + entry.getKey().id());
                }
            }
            deltas.forEach((acc, delta) -> acc.balance += delta);
        } finally {
            for (int i = acquired.size() - 1; i >= 0; i--) {
                acquired.get(i).lock.unlock();
            }
        }
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where Lock Ordering Applies in System Design.

Why this matters: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Canonical lock ordering is a universal primitive for multi-resource atomicity:

  • Payment & Double-Entry Ledgers: Atomic debit(from) + credit(to) in both JVM memory and SQL ORDER BY id FOR UPDATE.
  • Distributed Lock Managers: Sorting Redis/etcd lock keys lexicographically before multi-key acquisition.
  • Graph & Inventory Engines: Locking multiple SKUs in sorted sku_id order during cart checkout.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why does ordering locks by `System.identityHashCode()` require a global tie-breaker lock?

Recommended Learning Flow