2Brute2Best
πŸ”₯0
P17

Design an In-Memory Pub-Sub Message Queue With Offsets

Hard High-frequency interview topic Pro OnlyObserverMediatorConcurrency std::jthread std::stop_token (C++20)
⚑ 30-Second Interview Cheat SheetP17 · 45-Min Design Plan
3 Patterns Combined
1. Scope Boundaries

In a 45-minute LLD interview, this problem evaluates append-only log architectures, message immutability, and decoupled consumer offset tracking (inspired by Apache Kafka). Scope the solution to: an in-memory Broker acting as Mediator, topics owning immutable sequential commit logs, independent per-subscriber offset pointers, pull-based (poll) batch consumption, and replayability by cursor rewinding. Multi-broker network consensus (Raft/Paxos) can be cited as a distributed system extension.

2. Core Noun Entities
Brokerstateful-class
Topicstateful-class
Messagedata-struct
ISubscriberinterface
3. Hotspot β†’ Pattern
Publisher-to-subscriber interaction and routing coordination β†’ Mediator Pattern (Broker coordinating publishers, topics, and subscribers)
Consumer notification and pull-based event delivery β†’ Observer Pattern (ISubscriber interface)
Concurrent commit log writes and offset cursor increments β†’ Monitor Object / Mutex synchronization (std::mutex per Topic and per Broker)
01

Problem statement & clarifying requirements

Design an in-memory distributed message queue inspired by Apache Kafka and RabbitMQ. The system organizes messages into distinct Topics, appends published events to an immutable commit log, and maintains independent consumer offsets. Slow consumers must never block fast consumers, and consumers must be able to replay past events by rewinding their offset cursor back to any point in the log.

Questions you should ask the interviewer first
β€œDoes a slow consumer lagging behind block other consumers on the same topic?”

No. Topics use an append-only log with separate per-subscriber offset pointers. Each consumer polls and advances its own read index independently.

β€œCan consumers replay historical messages from the beginning?”

Yes. Messages are not deleted upon consumption. A consumer can call resetOffset(topic, subscriberId, 0) to replay all past messages.

β€œIs message consumption push-based or pull-based?”

The architecture implements a pull-based (poll) model mediated by the Broker, giving consumers direct control over batch size and consumption pacing.

β€œHow are concurrent publishers and consumers coordinated safely?”

The Broker acts as a Mediator: topic append operations are synchronized with internal mutexes, preventing producers and consumers from coupling directly to each other.

02

First, sketch the design yourself

Spend 5 minutes listing the classes, who owns whom, and which interface hides the part that changes.

  1. 1.

    Traditional queues (like simple FIFOs) pop elements upon receipt, preventing multiple independent subscriber groups and making replay impossible.

  2. 2.

    Decouple publishers from consumers via a central Broker Mediator: publishers only know topic names and payloads; they never hold references to downstream worker instances.

  3. 3.

    Treat the commit log as an immutable sequence of numbered entries: once appended, a message's content and offset never change.

03

How to think through this problem (5-step walkthrough)

Step 1 Β· Scope the 45-minute target & core boundary

In a 45-minute LLD interview, this problem evaluates append-only log architectures, message immutability, and decoupled consumer offset tracking (inspired by Apache Kafka). Scope the solution to: an in-memory Broker acting as Mediator, topics owning immutable sequential commit logs, independent per-subscriber offset pointers, pull-based (poll) batch consumption, and replayability by cursor rewinding. Multi-broker network consensus (Raft/Paxos) can be cited as a distributed system extension.

Step 2 Β· Extract candidate nouns (and reject false classes)

Not every noun in the prompt deserves its own class. Separate dumb data structs from stateful managers, and turn trivial nouns into fields or enums.

Broker
Stateful Class / Manager

Central Mediator managing topic registries, subscriber mappings, topic creation, publication, and per-subscriber cursor offsets without direct publisher-to-consumer coupling.

Topic
Stateful Class / Manager

Encapsulates an append-only thread-safe vector of Message instances and provides sub-slice batch reads by offset range under mutex protection.

Message
Value Struct

Immutable value struct representing a committed record with sequential offset (int64_t), payload string, and optional routing key.

ISubscriber
Abstract Interface

Observer interface declaring subscriber identity and onMessage(topic, message) callback contract.

WorkerSubscriber
Stateful Class / Manager

Concrete consumer worker that polls message batches from the Broker, processes payloads, and tracks received message history.

PerConsumerQueueCopy
Reject as Class β†’ Field / Method

Trap noun β€” beginner candidates often allocate a separate std::queue<Message> for each subscriber and duplicate every published message N times. This balloons memory by O(N Γ— M) and prevents historical seeking; the correct architecture is a single append-only topic log with a lightweight scalar integer offset cursor per consumer.

Step 3 Β· Draft the naive design & spot what breaks

A traditional naive message queue deletes messages as soon as a consumer dequeues them (pop()). This prevents multiple consumer groups from reading the same topic, makes historical message replay impossible, and causes slow consumers to either block fast consumers or exhaust memory with unbound subscriber buffers. Coupling publishers directly to subscriber instances also creates cascading failure when a consumer crashes.

Step 4 Β· Map change hotspots to design patterns
Publisher-to-subscriber interaction and routing coordination→ Mediator Pattern (Broker coordinating publishers, topics, and subscribers)

Direct publisher-to-subscriber calls couple services together, creating circular dependencies and synchronous bottlenecks.

Consumer notification and pull-based event delivery→ Observer Pattern (ISubscriber interface)

Tightly coupling message consumers to concrete processing logic prevents adding analytics loggers or audit workers without touching publisher code.

Concurrent commit log writes and offset cursor increments→ Monitor Object / Mutex synchronization (std::mutex per Topic and per Broker)

Unsynchronized appends to shared message vectors cause data races, offset collision, and iterator invalidation.

Step 5 Β· Lock down C++23 ownership, invariants & concurrency
  • βœ“

    Append-only log immutability: Once appended to a Topic, a Message and its assigned offset index never change or get deleted during standard consumption, allowing safe concurrent reads and rewinds.

  • βœ“

    Independent consumer offset isolation: Each consumer maintains its own independent offset cursor (C_i β‰₯ 0). A slow consumer lagging behind does not delay or block fast consumers reading higher offsets on the same topic.

  • βœ“

    Replayability invariant: Any subscriber can rewind its cursor to an earlier valid offset (0 <= targetOffset <= latestOffset) via Broker::resetOffset() to reprocess historical messages from that point onward.

04

Entities & design patterns used

Brute2Best Pro Content

Unlock Full UML Diagram & C++23 Solution

The complete UML diagram, production-ready C++23 code, follow-up extensions, and design pitfall analysis are part of Brute2Best Pro. All 7 foundation chapters are 100% free.

All 440 visual dry runs & algorithms
Interactive step-by-step playback with pointer & array state transitions
52 comprehensive LLD chapters
Interactive UML diagrams, real-world stories (Food Delivery, Trading, RPG), and practice solutions
40 C++ basics labs & hardware memory models
Vtables, byte layouts, assembly insights, and multi-threading race conditions
Production-ready C++23 source code
Modern idioms, clean contracts, time/space complexity derivations, and interview takeaways

First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.

Systems Integration

Related C++ Systems & Algorithmic Foundations

Deep dive into underlying layers