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

Design a Thread-Safe In-Memory
Pub-Sub Message Queue (LLD).

Design an in-memory Kafka-like Pub-Sub broker supporting multiple topics, concurrent publishers, independent subscriber offsets, and non-spinning Condition signaling.
Start the journey5 stages
FIRST PRINCIPLES. PRODUCTION SCALE.
The idea to keep with you

When traffic spikes expose hidden coupling, model each `Topic` with an append-only log guarded by a per-topic `ReentrantLock` + `Condition`, and give each `SubscriberWorker` its own `AtomicInteger` offset so slow consumers never block fast ones.

TL;DR30-second simplified summary
▾

Core Mechanics: Unlike a point-to-point BlockingQueue (where 1 consumer pops and removes each message), Pub-Sub requires every subscriber on a topic to receive all messages independently and support resetOffset() for replay—all while isolating slow subscribers and unrelated topics.

Visual & Structural Flow: Depicts Per-Topic Append Log + Condition Wakeup for Independent Consumers (Publisher -> Topic Log (Lock+Cond) -> Fast Sub (off=42) -> Slow Sub (off=10)); Topic-Isolated Append Log & Per-Subscriber Cursors (Broker Registry -> Topic Append Log -> Fast Worker -> Slow / Replay Worker).

Trade-Offs & Production: Duplicating messages into N separate BlockingQueues wastes N× memory and cannot support resetOffset(0) replay. This exact in-memory model scales out into distributed streaming logs: Apache Kafka & Redpanda: Store immutable per-partition append logs on disk and track per-consumer-group offsets independently for replay.

Failure Modes & Application: This exact in-memory model scales out into distributed streaming logs: Apache Kafka & Redpanda: Store immutable per-partition append logs on disk and track per-consumer-group offsets independently for replay.

Before you begin · Building blocksAlready know these? Jump to Stage 01 ↓
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.
Core LLD Behavioral Patterns: State, Strategy & Observer in Practice
Behavioral patterns—State, Strategy, and Observer—eliminate brittle if-else chains in Low-Level Design interviews and production systems by encapsulating lifecycle transitions, interchangeable algorithms, and event notifications behind clean interfaces.
Full walkthrough · 5 stages
01
STAGE 01 · WHY IT MATTERSL4 · FUNDAMENTALS

Why fan-out Pub-Sub needs independent offsets and per-topic locks.

Why this matters: The mechanism: understand how Why fan-out Pub-Sub needs independent offsets and per-topic locks works from first principles.

Think of Why fan-out Pub-Sub needs independent offsets and per-topic locks as the intuition layer for Design a Thread-Safe In-Memory Pub-Sub Message Queue (LLD): The mechanism: understand how Why fan-out Pub-Sub needs independent offsets and per-topic locks works from first principles.

Unlike a point-to-point BlockingQueue (where 1 consumer pops and removes each message), Pub-Sub requires every subscriber on a topic to receive all messages independently and support resetOffset() for replay—all while isolating slow subscribers and unrelated topics.

02
STAGE 02 · IMPACTL5 · APPLIED DESIGN

Head-of-line blocking, busy-wait CPU burn, and global-lock contention.

Why this matters: The problem: see what breaks without Head-of-line blocking, busy-wait CPU burn, and global-lock contention under real concurrency or scale.

Naive in-memory brokers break in three ways:

  1. Synchronous Fan-Out: Calling subscriber.onMessage(msg) directly inside publish() lets one slow subscriber stall the publisher and all fast subscribers.
  2. Busy-Wait Polling: while (offset >= log.size()) {} burns 100% CPU when caught up.
  3. Global Broker Lock: Synchronizing all topics on one lock causes Topic A traffic to block Topic B.
Non-Blocking Fan-Out

Per-Topic Append Log + Condition Wakeup for Independent Consumers

PublisherTopic Log(Lock+Cond)Fast Sub (off=42)Slow Sub (off=10)1. append(msg) + cond.signalAll()2. Wakes & reads idx 42immediately3. Reads idx 10 at own pace (noblocking!)

Publishers append and signalAll() in O(1) while each SubscriberWorker advances its own offset independently.

Engineering Decision Framework
Problem
How to implement Design a Thread-Safe In-Memory Pub-Sub Message Queue (LLD) 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, model each Topic with an append-only log guarded by a per-topic ReentrantLock + Condition, and give each SubscriberWorker its own AtomicInteger offset so slow consumers never block fast ones.
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 a Thread-Safe In-Memory Pub-Sub Message Queue (LLD) 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 `BlockingQueue` per subscriber or `Thread.sleep(10)` loops.

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

Think of Naive BlockingQueue per subscriber or Thread.sleep(10) loops as the intuition layer for Design a Thread-Safe In-Memory Pub-Sub Message Queue (LLD): Scope boundary: identify where this pattern fits best and where simpler or async alternatives win.

Duplicating messages into N separate BlockingQueues wastes N× memory and cannot support resetOffset(0) replay. Meanwhile, Thread.sleep(10) polling wastes CPU and adds 10 ms artificial tail latency.

Component Topology

Naive `BlockingQueue` per subscriber or `Thread.sleep(10)` loops

ProduceringressPartition LogcomputeConsumerstorageDead-Letter Queuecontrolappend(key)poll(offset)dead-letter
04
STAGE 04 · ENTERPRISE SOLUTIONL6 · SCALE & TRADE-OFFS

Enterprise solution: Per-Topic Log + `Condition` + `AtomicInteger` Offsets.

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

Build clean isolation across topics and subscribers:

  • ConcurrentHashMap<String, Topic>: createTopic uses putIfAbsent with zero global lock during publish().
  • Per-Topic ReentrantLock + Condition: publish() appends to List<Message> and calls newMessageCond.signalAll(). SubscriberWorker sleeps via newMessageCond.await() inside a while (offset.get() >= topic.size()) loop (handling spurious wakeups).
  • Independent AtomicInteger Offset: Each SubscriberWorker tracks its own offset; resetOffset(newOffset) sets the offset and signals the condition variable to replay immediately.
Broker Memory Layout

Topic-Isolated Append Log & Per-Subscriber Cursors

Broker RegistryConcurrentHashMap<To…Topic Append LogPer-topic Lock +…Fast WorkerAtomicInteger…Slow / ReplayWorkerresetOffset(0) +…zero-copy offset read

Sharing one immutable append log per topic avoids N-way message copying and enables instant offset replay.

public class Topic {
    private final List<Message> log = new ArrayList<>();
    private final ReentrantLock lock = new ReentrantLock();
    private final Condition hasNew = lock.newCondition();

    public void publish(Message msg) {
        lock.lock();
        try {
            log.add(msg);
            hasNew.signalAll();
        } finally { lock.unlock(); }
    }

    public Message readAt(AtomicInteger offset) throws InterruptedException {
        lock.lock();
        try {
            while (offset.get() >= log.size()) {
                hasNew.await(); // Sleeps with zero CPU spin until publish or resetOffset
            }
            return log.get(offset.getAndIncrement());
        } finally { lock.unlock(); }
    }
}
05
STAGE 05 · SYSTEM DESIGN APPLICATIONSL7 · STAFF / PRINCIPAL

Where append-log Pub-Sub architectures are used.

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

This exact in-memory model scales out into distributed streaming logs:

  • Apache Kafka & Redpanda: Store immutable per-partition append logs on disk and track per-consumer-group offsets independently for replay.
  • In-Process Event Buses: High-frequency trading and game servers use ring-buffer/append-log buses to fan out market ticks to isolated strategy threads.
Practice · Explain the consequences

Practice: Make the trade-off yourself.

Question 1 of 3
Score: 0/3

Why should `SubscriberWorker` check `while (offset.get() >= log.size())` around `Condition.await()` instead of an `if` statement?

Recommended Learning Flow