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.
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.
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:
- Synchronous Fan-Out: Calling
subscriber.onMessage(msg)directly insidepublish()lets one slow subscriber stall the publisher and all fast subscribers. - Busy-Wait Polling:
while (offset >= log.size()) {}burns 100% CPU when caught up. - Global Broker Lock: Synchronizing all topics on one lock causes
Topic Atraffic to blockTopic B.
Per-Topic Append Log + Condition Wakeup for Independent Consumers
Publishers append and signalAll() in O(1) while each SubscriberWorker advances its own offset independently.
- 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
Topicwith an append-only log guarded by a per-topicReentrantLock+Condition, and give eachSubscriberWorkerits ownAtomicIntegeroffset 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.
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?
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.
Naive `BlockingQueue` per subscriber or `Thread.sleep(10)` loops
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>:createTopicusesputIfAbsentwith zero global lock duringpublish().- Per-Topic
ReentrantLock+Condition:publish()appends toList<Message>and callsnewMessageCond.signalAll().SubscriberWorkersleeps vianewMessageCond.await()inside awhile (offset.get() >= topic.size())loop (handling spurious wakeups). - Independent
AtomicIntegerOffset: EachSubscriberWorkertracks its own offset;resetOffset(newOffset)sets the offset and signals the condition variable to replay immediately.
Topic-Isolated Append Log & Per-Subscriber Cursors
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(); }
}
}
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: Make the trade-off yourself.
Why should `SubscriberWorker` check `while (offset.get() >= log.size())` around `Condition.await()` instead of an `if` statement?