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

Thread-Safe LLD: Locking, Condition Variables
& In-Memory Pub-Sub Queues.

Thread-safe Low-Level Design balances correctness and throughput using fine-grained per-entity locks (per-seat, per-topic, per-floor), Condition/BlockingQueue signaling, and optimistic versioning rather than coarse global mutexes.
Start the journey7 sections· Last modified Nov 16, 2026
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

If lock contention or cache misses stall worker threads, Condition Variables & In-Memory, lock at the smallest independent boundary (e.g., per-topic or per-seat) and always acquire multiple locks in a canonical global order to prevent deadlocks.

TL;DR30-second simplified summary
▾

Core Mechanics: Thread-safe Low-Level Design structures shared in-memory state—bounded blocking queues, pub-sub topics, and seat reservation maps—so concurrent threads never corrupt invariants or busy-wait CPU cores.

Visual & Structural Flow: Depicts Bounded Queue Producer/Consumer Thread States (HOLDING LOCK -> AWAITING COND -> SIGNALED); Canonical Lock Ordering (min(id) -> max(id)) (Thread 1 (B, A) -> Lock(Seat A) -> Lock(Seat B) -> Thread 2 (A, B)).

Trade-Offs & Production: Choose the simplest synchronization boundary that meets your contention profile. In an in-memory pub-sub broker, publishers append to the topic ring buffer under the per-topic lock, then dispatch to subscribers outside the lock (or via per-subscriber.

Failure Modes & Application: Practice implementing bounded queues, pub-sub brokers, and deadlock-free booking systems.

Full walkthrough · 7 stages
01
STAGE 01 · WHAT IT ISL4 · FUNDAMENTALS

What is Thread-Safe Concurrency LLD.

Why this matters: The mechanism: understand how Thread-Safe Concurrency LLD works from first principles.

Thread-safe Low-Level Design structures shared in-memory state—bounded blocking queues, pub-sub topics, and seat reservation maps—so concurrent threads never corrupt invariants or busy-wait CPU cores.

Three primitives form the core toolkit: fine-grained per-entity locks (ReentrantLock per topic or seat), Condition variables (notFull / notEmpty) so waiting threads sleep without spinning, and canonical lock ordering to prevent AB-BA deadlocks.

Condition Signaling

Bounded Queue Producer/Consumer Thread States

cond.await() inside whilePeer calls cond.signalAll()Re-verify predicateHOLDING LOCKCheck while(full/empty)AWAITING CONDLock released; sleepingSIGNALEDRe-acquire & re-check

Always wrap Condition.await() in a while loop: spurious wakeups or competing threads can change the predicate before the thread resumes.

02
STAGE 02 · WHY WE NEED ITL4 · FUNDAMENTALS

Why coarse locks and slow callbacks break concurrent LLD.

Why this matters: The problem: see what breaks without Why coarse locks and slow callbacks break concurrent LLD under real concurrency or scale.

A single synchronized method on a broker or booking service serializes unrelated topics and seats, collapsing multi-core throughput.

Conversely, naive fine-grained locking introduces two classic bugs:

  • AB-BA Deadlocks: Thread 1 locks Seat A then Seat B while Thread 2 locks Seat B then Seat A.
Deadlock Avoidance

Canonical Lock Ordering (min(id) -> max(id))

Thread 1 (B, A)Lock(Seat A)Lock(Seat B)Thread 2 (A, B)1. Sort [B,A]->[A,B]: lock A2. Waits for A (no cycle)3. Acquires B, commits4. Releases A & B -> T2 runs

Sorting lock IDs globally guarantees a strict acquisition DAG, making circular wait mathematically impossible.

Engineering Decision Framework
Problem
How to implement Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues 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
If lock contention or cache misses stall worker threads, condition Variables & In-Memory, lock at the smallest independent boundary (e.g., per-topic or per-seat) and always acquire multiple locks in a canonical global order to prevent deadlocks.
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 Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues experiences a sudden 5x traffic spike alongside a slow downstream dependency, which engineering choice best protects system stability?

03
STAGE 03 · WHERE IT IS USEDL5 · APPLIED DESIGN

Where In-Memory Concurrency LLD applies (and where it does not).

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

Think of Where In-Memory Concurrency LLD applies (and where it does not) as the intuition layer for Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues: Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

In-process concurrency primitives govern single-node engines, while multi-node deployments require distributed coordination.

ChoiceWhat it buysWhat it costs
Good Candidate: In-Memory Pub-Sub & Worker PoolsConcurrentHashMap + per-topic ReentrantLock/Condition scales across cores cleanly.State is ephemeral unless backed by a WAL or external broker.
Good Candidate: Single-Node Seat/Slot Hold EnginesSub-millisecond per-seat locking with TTL expiry sweeps.Cannot coordinate across multiple JVM/service instances.
Avoid: Cross-Process Distributed StateUse Redis Lua scripts, DB row locks (`SELECT ... FOR UPDATE`), or etcd leases instead.In-JVM locks only protect memory inside one OS process.
04
STAGE 04 · HOW IT IS MANAGEDL5 · APPLIED DESIGN

Implementing a Bounded Blocking Queue with Condition Variables.

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

Think of Implementing a Bounded Blocking Queue with Condition Variables as the intuition layer for Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues: Operational control: configure bounds, failure handling, and safe production defaults.

Separate notFull and notEmpty Condition queues on a ReentrantLock, always guard await() with a while loop, and always release the lock in a finally block.

Lifecycle & Failure Recovery

Implementing a Bounded Blocking Queue with Condition Variables

poll batchsink successpoison / timeoutAppended to LogLeased to ConsumerOffset CommittedMoved to DLQ
import java.util.concurrent.locks.*;

public final class BoundedQueue<T> {
    private final Object[] items;
    private int head = 0, tail = 0, count = 0;
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition notFull = lock.newCondition();
    private final Condition notEmpty = lock.newCondition();

    public BoundedQueue(int capacity) { this.items = new Object[capacity]; }

    public void put(T item) throws InterruptedException {
        lock.lock();
        try {
            while (count == items.length) notFull.await();
            items[tail] = item;
            tail = (tail + 1) % items.length;
            count++;
            notEmpty.signal();
        } finally {
            lock.unlock();
        }
    }
}
05
STAGE 05 · ALTERNATIVESL6 · SCALE & TRADE-OFFS

Alternatives: Coarse Mutex vs. Fine-Grained Lock vs. Lock-Free CAS.

Why this matters: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Think of Alternatives: Coarse Mutex vs. Fine-Grained Lock vs. Lock-Free CAS as the intuition layer for Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues: The trade-off: compare competing approaches across latency, consistency, and operational cost.

Choose the simplest synchronization boundary that meets your contention profile.

Component Topology

Alternatives: Coarse Mutex vs. Fine-Grained Lock vs. Lock-Free CAS

ProduceringressPartition LogcomputeConsumerstorageDead-Letter Queuecontrolappend(key)poll(offset)dead-letter
ChoiceWhat it buysWhat it costs
Coarse Global LockTrivial to reason about; zero multi-lock deadlock risk.Serializes unrelated topics/seats; poor multi-core scaling.
Fine-Grained Per-Entity LockHigh parallel throughput across independent entities.Requires strict canonical lock ordering on multi-entity operations.
Lock-Free Ring Buffer (Disruptor / CAS)Zero OS mutex context switches; ultra-low tail latency.Complex memory-ordering invariants and harder debugging.
06
STAGE 06 · PRODUCTION ARCHITECTUREL7 · STAFF / PRINCIPAL

Snapshot-and-Dispatch Pub-Sub Pattern.

Why this matters: Production architecture: see how the components compose end to end under real load.

Think of Snapshot-and-Dispatch Pub-Sub Pattern as the intuition layer for Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues: Production architecture: see how the components compose end to end under real load.

In an in-memory pub-sub broker, publishers append to the topic ring buffer under the per-topic lock, then dispatch to subscribers outside the lock (or via per-subscriber worker threads with offset pointers) so slow consumers never stall publishers.

Per-Subscriber Offset Tracking

Each subscriber maintains an atomic offset into the topic's immutable message array, allowing independent consumption speeds.

TryLock with Timeout

For latency-sensitive APIs, pair canonical ordering with tryLock(50, MILLISECONDS) to fail fast instead of piling up threads.

07
STAGE 07 · PROBLEMS SOLVED & FURTHER DEEP DIVEL7 · STAFF / PRINCIPAL

Concurrency LLD Problems & Related Concepts.

Why this matters: Applied problems: connect these internals to concrete system design and debugging scenarios.

Think of Concurrency LLD Problems & Related Concepts as the intuition layer for Thread-Safe LLD: Locking, Condition Variables & In-Memory Pub-Sub Queues: Applied problems: connect these internals to concrete system design and debugging scenarios.

Practice implementing bounded queues, pub-sub brokers, and deadlock-free booking systems.

Design Trade-Off

Concurrency LLD Problems & Related Concepts

Before · Dual-Write + No DLQ
  • DB/Broker split-brain drift
  • Poison pill blocks partition
  • Unbounded redelivery storm
After · Outbox + Idempotent Consumer
  • Atomic DB + Outbox commit
  • Per-key dedup & DLQ isolation
  • Consumer lag stays bounded
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why must a consumer thread check its wait condition in a `while` loop rather than an `if` statement around `Condition.await()`?

Recommended Learning Flow