Design a Tag-Based Pub/Sub Message Broker
System DesignModel answerLast updated
Design a message queue where each message carries multiple topic tags and consumers receive only messages whose tags overlap their subscription set.
Background
You are building a messaging layer for a platform where producers emit events and consumers process them. Unlike a simple single-topic queue, every message can belong to several topics simultaneously, and each consumer opts in to a personal collection of topics. A consumer should receive a message if and only if at least one of its subscribed topics appears on that message — but it should receive the message at most once regardless of how many tags match.
What You Need to Design
Core operations
enqueue(producer_id, payload, topics)— publish a message labelled with one or more topic identifiers.subscribe(consumer_id, topics)— add topics to a consumer's interest set.unsubscribe(consumer_id, topics)— remove topics from a consumer's interest set; only affects messages not yet delivered.dequeue(consumer_id)— return the next eligible message for this consumer in arrival order, or nothing if none exists.
Query operations
- Given two arbitrary topic sets (for example, the tags on a message and the subscription mask of a consumer), return the topics they have in common.
- Given a set of required producer → consumer delivery pairs, determine the minimum number of topic channels that can satisfy all of them without a consumer receiving messages from a producer it is not paired with.
What Is Expected in Your Answer
Walk through the full design in the order below.
- Clarify assumptions — delivery semantics, scale (order-of-magnitude numbers), and how many topics a typical message or subscriber touches.
- API and data model — how you store messages, track subscriptions, and route events.
- Representing topic sets — pick a concrete data structure and justify it; describe what happens as the number of topics grows.
- Fan-out strategy — compare writing to each consumer's queue at enqueue time versus filtering at dequeue time; explain when you would choose each.
- Handling unsubscribe — explain how pending messages are dealt with without expensive queue scans.
- Topic intersection and union — describe the operations and their cost.
- Minimum channel cover — model the problem formally, state its theoretical complexity, and give at least one practical algorithm or bound you would use in an interview or in production.
- Complexity analysis — time and space for every operation.
Include pseudocode or working code for the core queue operations.
Hints
Hint 1
Think about how a set of topic IDs can be packed into an integer and what CPU operations that unlocks for intersection and union checks.
Hint 2
Fan-out on write keeps dequeue fast but multiplies storage; fan-out on read keeps enqueue cheap but makes dequeue scan heavy — the right choice depends on your read/write ratio and average fan-out width.
Hint 3
The minimum channel cover maps onto a biclique cover of a bipartite graph, which is NP-hard in general; in an interview, an efficient upper bound based on grouping nodes by identical neighbor sets is usually what the interviewer is looking for.
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
1. Clarify Assumptions
Before diving into boxes and arrows, nail down the contract.
Functional semantics
- Delivery is FIFO per consumer.
- A consumer receives a message at most once, even if multiple tags match.
- Unsubscribing only affects messages not yet dequeued; already-delivered messages are unaffected.
- "Shared topics" and "minimum channels" are read-only queries — they do not alter queue state.
Scale assumptions to state out loud
- Up to ~10,000 distinct topics.
- Up to ~10,000 active consumers.
- ~100,000–1,000,000 messages per second at peak.
- Each message carries a small number of tags (k ≈ 2–10); each consumer subscribes to a similarly small set.
- Single-process in-memory structure for now; distribution is an extension.
2. API and Data Model
enqueue(producer_id, payload, topics: set[int]) -> msg_id
dequeue(consumer_id) -> Message | None
subscribe(consumer_id, topics: set[int])
unsubscribe(consumer_id, topics: set[int])
shared_topics(mask_a: int, mask_b: int) -> set[int]
min_channels(pairs: set[(producer_id, consumer_id)]) -> int
Core tables
| Structure | Key | Value |
|---|---|---|
messages | msg_id | (payload, topic_mask, refcount) |
topic_subs | topic_id | set[consumer_id] — inverted index |
consumer_mask | consumer_id | bitmask of subscribed topics |
consumer_queue | consumer_id | deque[msg_id] — per-consumer FIFO |
Each message is stored once. Consumers hold references to it via their queues, and a refcount lets the payload be freed when the last consumer dequeues it.
3. Representing Topic Sets
Map each topic to a dense integer ID in [0, C) and represent any set of topics as a bitmask of C bits.
| Operation | Bitmask form | Cost |
|---|---|---|
| Membership test | mask & (1 << topic_id) | O(1) |
| Union | a | b | O(W) |
| Intersection | a & b | O(W) |
| Delivery check | (msg_mask & sub_mask) != 0 | O(W) |
| Unsubscribe | sub_mask & ~removed_mask | O(W) |
W = ⌈C / 64⌉ machine words. For C ≤ 64 every operation is a single CPU instruction. For C = 4,096, W = 64 words — a short SIMD-friendly AND loop.
When to switch representations: if C is enormous but each set is sparse (say, a consumer subscribes to 5 out of 1,000,000 topics), a sorted array of IDs or a Roaring Bitmap is better. Intersection then costs O(|a| + |b|) rather than O(C/64), and memory drops from O(C) to O(|set|). This is the main representation trade-off to articulate.
4. Fan-Out Strategy
Fan-out on write (push model): at enqueue time, union the subscriber sets for each tag on the message, deduplicate, and append the msg_id to every matching consumer's deque.
- Enqueue: O(k · S + F), where k = tags per message, S = average subscribers per tag, F = fan-out size.
- Dequeue: O(1) amortized.
- Best when fan-out is narrow or reads are far more frequent than writes.
Fan-out on read (pull/log model): append every message to a single ordered log. Each consumer maintains a cursor and scans forward, filtering with msg_mask & sub_mask.
- Enqueue: O(1).
- Dequeue: O(messages scanned) — can be expensive if most messages do not match.
- Best when the read/write ratio is low or fan-out is extremely wide (broadcast-style). Kafka uses this model per partition.
For a general-purpose broker with mixed workloads, fan-out on write is the safer default.
5. Handling Unsubscribe Lazily
Eagerly removing msg_id entries from a consumer's deque on every unsubscribe is O(queue length) in the worst case. Instead, use lazy filtering:
unsubscribeupdates onlyconsumer_maskandtopic_subs— O(k).- On
dequeue, after popping amsg_id, re-checkmsg_mask & consumer_mask[cid]. If the result is zero, the message no longer matches; discard it, decrement the refcount, and move to the next entry.
This keeps unsubscribe O(k) and shifts the filtering cost to dequeue, where it is naturally incurred anyway.
6. Implementation
from collections import deque, defaultdict
class TaggedMessageQueue:
def __init__(self):
self.messages = {} # msg_id -> [payload, mask, refcount]
self.topic_subs = defaultdict(set) # topic_id -> set of consumer_ids
self.consumer_mask = defaultdict(int) # consumer_id -> bitmask
self.queues = defaultdict(deque) # consumer_id -> deque of msg_ids
self._next_id = 0
def subscribe(self, cid, topics):
for t in topics:
self.topic_subs[t].add(cid)
self.consumer_mask[cid] |= 1 << t
def unsubscribe(self, cid, topics):
for t in topics:
self.topic_subs[t].discard(cid)
self.consumer_mask[cid] &= ~(1 << t)
def enqueue(self, payload, topics):
mask, targets = 0, set()
for t in topics:
mask |= 1 << t
targets |= self.topic_subs.get(t, set())
if not targets:
return None
mid = self._next_id
self._next_id += 1
self.messages[mid] = [payload, mask, len(targets)]
for cid in targets:
self.queues[cid].append(mid)
return mid
def dequeue(self, cid):
q = self.queues[cid]
while q:
mid = q.popleft()
entry = self.messages.get(mid)
if entry is None:
continue
payload, mask, _ = entry
self._release(mid)
if mask & self.consumer_mask[cid]: # lazy filter
return payload
return None
def _release(self, mid):
self.messages[mid][2] -= 1
if self.messages[mid][2] == 0:
del self.messages[mid]
@staticmethod
def shared_topics(mask_a, mask_b):
overlap, result, i = mask_a & mask_b, [], 0
while overlap:
if overlap & 1:
result.append(i)
overlap >>= 1
i += 1
return result
7. Minimum Channel Cover
Formal model. Build a bipartite graph G = (Producers ∪ Consumers, E) where edge (p, c) means p must reach c. A topic channel is a complete bipartite subgraph (biclique): every producer publishing on it reaches every subscriber. The goal is to cover all edges of G with the fewest bicliques such that no edge outside E is covered — otherwise a consumer would receive messages from a producer it is not paired with.
This is the biclique cover problem, which is NP-hard in general.
What to deliver in an interview:
-
Efficient upper bound. Group consumers by the set of producers they receive from (their "fan-in fingerprint"). Each distinct fingerprint needs one channel. Symmetrically, group producers by their consumer sets. The answer is at most the smaller group count. Cost: O(|E|) using bitmask hashing.
-
Lower bound (fooling set). Find a set of edges {(p₁,c₁), …, (pₜ,cₜ)} such that for every i ≠ j, at least one of (pᵢ,cⱼ) or (pⱼ,cᵢ) is absent from E. No single biclique can contain two such edges, so at least t channels are required.
-
Greedy heuristic for larger inputs.
- Pick any uncovered edge (p, c).
- Grow the producer side by intersecting consumer-neighbor bitmasks.
- Grow the consumer side by intersecting producer-neighbor bitmasks.
- Mark all covered edges; repeat.
- Each growth step is O(W) with bitmask intersection.
-
Exact solution for small inputs: enumerate maximal bicliques (there can be exponentially many, but in practice the graph is sparse), then solve the set-cover ILP or use bitmask DP.
8. Complexity Summary
| Operation | Time | Space |
|---|---|---|
subscribe / unsubscribe | O(k) | O(k) per call |
enqueue | O(k · S + F) | O(1) per message stored |
dequeue | O(skipped + W) amortized | — |
shared_topics | O(W) | O(result) |
| Upper-bound channel cover | O(|E| · W) | O(N · W) |
W = ⌈C/64⌉, k = tags per message, S = avg subscribers per tag, F = fan-out width.
Common mistakes to avoid
- Delivering a message multiple times when two tags both match the same consumer — deduplicate the target set at enqueue time.
- Eager queue scanning on unsubscribe — use the lazy re-check pattern instead.
- Claiming the minimum channel count is polynomial — it is NP-hard; give a bound or heuristic and say so explicitly.
- Choosing a flat bitmask when C is in the millions — recognize when Roaring Bitmaps or sorted arrays are necessary.