Multi-Tag Pub/Sub Queue and Channel Cover Design
Hard · System Design · Software Engineer · Technical Screen
Prompt
Design a specialized message-queue data structure and broker architecture in which every published message carries one or more named channels, and each consumer subscribes to a chosen subset of channels.
Your design should address four parts:
- Multi-tag pub/sub delivery: Support publishing messages across multiple channels and claiming messages per consumer so a subscriber matching one or more of a message's channels receives that message logically once, with safe lease/retry handling.
- Dynamic channel creation & minimal channel cover: Support registering new channels at runtime, and show how to determine (or tightly bound and construct) the minimum number of channels needed to realize a target producer-to-consumer routing matrix without leaking messages to unintended consumers.
- Set representation & fast set algebra: Explain how channel identifiers and subscription sets are represented so set union, set intersection, and producer-consumer reachability checks execute efficiently.
- Complexity analysis: Derive the time and space complexity for
enqueue,dequeue(and lease acknowledgement/release),subscribe/unsubscribe, and channel-set queries.
Scope & Expectations
- Clear delivery invariants: Define ordering scope, duplicate-free merging across overlapping subscriptions, crash-safe visibility leases with fencing tokens, and subscription cutover rules.
- Compact data structures: Show how single-copy payload storage, dense integer channel interning, per-channel append logs, and bitmasks keep memory small and set algebra fast.
- Graph-covering math and system scaling: Formulate producer-consumer channel minimization via biclique matrix covers with upper and lower bounds, justify Big-O costs for every operation, and outline durable distributed scaling.
Step-by-step walkthrough
Clarify delivery semantics and non-functional requirements
This problem combines custom data-structure design (multi-tag logs, bitset algebra, and graph covering) with production message-broker semantics (leases, retries, and durability). Lock down the exact rules first, because changing any rule changes the core data structure:
- Fan-out (pub/sub) delivery: Every consumer subscribed to a matching channel receives its own independent delivery of the message. (Supporting a consumer group — a pool of workers sharing one cursor so only one worker processes each message — is a clean extension covered in the follow-ups.)
- "Any-of" eligibility & zero logical duplicates (hard correctness boundary): A consumer is eligible for a message tagged with channels
MifMshares at least one channel with the consumer's active subscriptionsS(M ∩ S != empty). Even ifc1subscribes to both"gpu"and"alerts", a message tagged{"gpu", "alerts"}must be delivered toc1logically once, never twice. - At-least-once physical delivery with fenced leases:
dequeue(claiming a message) grants a time-bounded visibility lease (a temporary lock hiding that message from re-claim for, say, 30 seconds) paired with a monotonic fencing token (lease_epoch). Callingackwith the activelease_epochcompletes delivery; if the worker crashes or callsrelease, the message is retried up tomax_attemptsbefore moving to a Dead-Letter Queue (DLQ) — a quarantine list for "poison" messages that repeatedly fail processing. - Ordering scope: Normal deliveries arrive in strict
enqueueorder per consumer via a global monotonic sequence number (seq = 1, 2, 3, ...); retried messages trade strict arrival order for liveness so one slow retry never stalls newer work. - Subscription convergence & dynamic channels:
subscribe(c, ch)takes effect from the current log tail (no historical flood) and increments a monotonicsub_versionso distributed nodes converge deterministically. Channels can be added dynamically, and an offline planner computes the minimum channel set needed to satisfy a producer-to-consumer matrix without unauthorized leaks.
Back-of-the-envelope numbers
Size a single broker node first so memory layout and write-vs-read amplification trade-offs jump off the page:
Workload assumptions Active channels (C): 512 Producers (P): 200 Consumers (N): 2,000 Throughput: 50,000 messages/sec, average payload = 512 bytes Tags per message (k): 2 on average (up to 8, non-empty) Subscriptions per consumer (s): 4 on average Avg subscribers per channel: (N x s) / C = (2,000 x 4) / 512 ≈ 16 subscribers Retention window: 5 minutes (300 seconds -> 15,000,000 retained messages) Memory footprint over 5-minute retention 1. Payloads (stored once): 15M x 512 B ≈ 7.68 GB 2. Per-channel log entries: 15M x k=2 x 8 B (seq) ≈ 240 MB 3. Message tag storage: - as 512-bit mask/msg: 15M x 64 B ≈ 960 MB (wasteful!) - as compact int16 list: 15M x 2 x 2 B ≈ 60 MB (16x smaller!) 4. Consumer subscription masks: 2,000 x 64 B ≈ 128 KB (tiny!) Write vs. read amplification - Single global log + filter on read: A consumer following 4 of 512 channels matches ~1 - (508/512)^2 ≈ 1.56% of traffic -> wastes ~64 scanned messages for every 1 match! - Push into per-consumer inboxes on enqueue: Up to k x 16 = 32 inbox writes/msg -> 1,600,000 writes/sec (and slow consumers bloat RAM) - Append seq to per-channel logs on enqueue (chosen): k = 2 appends/msg -> 100,000 appends/sec (16x fewer writes, unaffected by 10k-subscriber channels)These numbers dictate four foundational choices: store each payload once, append its 8-byte
seqtokper-channel logs, keep compact integer ID tuples on messages, and keep 512-bit bitmasks on consumers and producers.API contracts and durable entity lifecycles
Queue & lease operations add_channel(name: str) -> int # Idempotent; returns dense cid enqueue(payload: bytes, channels: set[str], # Non-empty channels; deduplicates producer_id: str | None, producer_seq: int | None) -> int # retries via (producer_id, producer_seq) subscribe(consumer: str, channel: str) -> int # Starts at tail; returns sub_version unsubscribe(consumer: str, channel: str) -> int # Stops future-only matches; returns sub_version dequeue(consumer: str, now: float) -> (int, bytes, int) | None # Claims (seq, payload, lease_epoch) or None ack(consumer: str, seq: int, lease_epoch: int) -> bool # Fenced ack; False if lease expired/stale release(consumer: str, seq: int, lease_epoch: int) -> bool # Fenced nack; retries or routes to DLQ Channel set & offline planning operations shared_channels(party_a: str, party_b: str) -> list[str] # Bitwise AND intersection union_channels(party_a: str, party_b: str) -> list[str] # Bitwise OR union can_reach(producer_channels: set[str], consumer: str) -> bool # Eligibility test (mask_p & mask_c) != 0 audience(channels: set[str]) -> set[str] # All consumers matching any channel in set plan_channels(needs: dict[str, set[str]]) -> list[(set, set)] # Leak-free biclique channel assignmentCore durable entities, versions, and state transitions:
Entity Identity & versions Lifecycle & invariants ---------------- ----------------------------------- -------------------------------------------------------- Channel cid (dense int 0..C-1), name ACTIVE -> DRAINING -> RETIRED (retired cids never reused) ProducerStream producer_id -> last_producer_seq Deduplicates retries so 1 logical send = 1 global seq Message seq (global int), cids tuple IMMUTABLE once appended; expires after retention TTL Subscription (consumer_id, sub_version) sub_mask + per-cid start_seq; monotonic sub_version DeliveryLease (consumer_id, seq) + lease_epoch LEASED -> ACKED | EXPIRED/RELEASED -> RETRY -> DLQ tracks physical_attempts (1..max) 1 logical eligibility maps to 1..max physical attempts ChannelPlan plan_id, plan_version DRAFT -> STAGED (channels created, subs converged) -> ACTIVEData model: dense channel IDs, per-channel logs, and two-stage cursors
The central representation trick is interning — mapping human-readable channel strings like
"gpu"and"alerts"once to consecutive integers0, 1, ..., C - 1. Once every channel is a dense integercid, per-channel logs are direct array slots (logs[cid]), and any subscription set is a bitmask — an integer (or fixed array of 64-bit words) where bitcidis1if channelcidis subscribed and0otherwise.To combine duplicate-free multi-channel merging with crash-safe visibility leases, split each consumer's state cleanly into two stages:
Stage 1 — Multi-channel log merge (pulls each matching seq out of logs AT MOST ONCE): sub_mask[c]: int bitmask of subscribed cids (e.g. 0b011 = {gpu, alerts}) positions[c]: dict[cid, int] -> next unread array index inside logs[cid] scanned_seq[c]: int -> highest message seq already merged from c's channel logs Stage 2 — Lease, retry, and dead-letter tracking (at-least-once physical delivery): in_flight[c]: dict[seq, (lease_epoch, expires_at)] -> currently leased messages retry_heap[c]: min-heap of seqs released or lease-expired and awaiting redelivery attempts[(c,seq)]: physical attempt counter; exceeding max_attempts routes seq to dead_letters[c]Why is separating
scanned_seqfromin_flightso clean? Because everylogs[cid]is strictly increasing, Stage 1 mergesslogs in strictseqorder and skips multi-tag duplicates (log[pos] <= scanned_seq[c]) inO(1)space per consumer. Once aseqgraduates from Stage 1 into Stage 2, lease expirations and retries operate purely onretry_heap[c]without ever rewinding or re-scanning the channel logs!End-to-end architecture
Producers Consumers | enqueue(payload, {"gpu","alerts"}, p_id, p_seq) dequeue / ack | v v +-----------------------+ +------------------------+ +----------+----------------+ | Idempotency & Global |---->| Single-Copy Payloads |<---| Stage 1: Log Merge Cursor | | Sequencer (next_seq) | | seq -> (payload, cids) | | scanned_seq, positions | +-----------+-----------+ +------------------------+ +----------+----------------+ | | unique seq | append seq to k=2 channel logs v v +----------+----------------+ +---------------------------------------------------+ | Stage 2: Fenced Leases | | Per-Channel Logs (indexed by dense cid) |<------| in_flight (lease_epoch), | | 0 ("gpu"): [ 3, 9, 41, 57 ] | | retry_heap, dead_letters | | 1 ("alerts"): [ 9, 12, 41 ] | +---------------------------+ | 2 ("net"): [ 5, 12 ] | +-------------------------+-------------------------+ +---------------------------+ | | Channel Registry & Planner| v | Bitwise AND/OR queries, | +-------------------+ | inverted subscriber sets, | | Write-Ahead Log | | offline biclique planner | | + State Snapshots | +---------------------------+ +-------------------+Deep dive: enqueue, duplicate-free dequeue, and fenced leases
Walk through a concrete trace with consumer
c1subscribed to"gpu"(cid=0) and"alerts"(cid=1),lease_ttl = 10s, andmax_attempts = 2: -m1(seq=1) arrives on{"gpu", "alerts"}->logs[0] = [1],logs[1] = [1]-m2(seq=2) arrives on{"net"}(cid=2) ->logs[2] = [2]-m3(seq=3) arrives on{"alerts"}->logs[1] = [1, 3]1. t=0s dequeue("c1"): Stage 1 checks cid 0 (seq 1) and cid 1 (seq 1) -> picks min seq=1 from cid 0, sets positions[0]=1, scanned_seq=1. Stage 2 issues (seq=1, epoch=101, exp=10s), attempts=1. 2. t=15s Worker 1 stalled! Lease on seq=1 expired (10s <= 15s) -> moved to retry_heap=[1]. Worker 2 calls dequeue("c1", now=15s): Pops seq=1 from retry_heap, issues NEW (seq=1, epoch=102, exp=25s), attempts=2. 3. t=16s Stalled Worker 1 wakes up and sends late ack("c1", seq=1, epoch=101): Active lease has epoch=102 != 101 -> REJECTED (False)! Worker 2's lease stays safe! 4. t=17s Worker 2 fails to parse m1 and calls release("c1", seq=1, epoch=102): attempts (2) == max_attempts (2) -> seq=1 routed to dead_letters["c1"]! 5. t=18s dequeue("c1", now=18s): retry_heap is empty. Stage 1 checks cid 0 (exhausted) and cid 1: logs[1][0] is seq=1 <= scanned_seq (1) -> SKIP duplicate! Advances positions[1] to 1, sees logs[1][1] is seq=3 -> sets scanned_seq=3, issues (seq=3, epoch=103). (m1 was never double-delivered via "alerts", and m2 on "net" was never touched!)Why scan the consumer's
ssubscribed logs directly instead of keeping a per-consumer min-heap? A min-heap cuts comparisons fromO(s)toO(log s), but whenever a channel log runs dry it leaves the heap; the nextenqueueon that channel would have to locate every idle subscriber and push that channel back into their heaps — puttingO(fan-out)work right back ontoenqueue! Scanningsheads keepsenqueuestrictlyO(k).Deep dive: bitwise union/intersection queries and reference implementation
Because channel
cidmaps to bit1 << cid, union (|), intersection (&), and eligibility tests compile down to CPU word operations (64 channels per 64-bit integer word, so 512 channels is just 8 word instructions).Suppose: 0="gpu" (bit 0), 1="alerts" (bit 1), 2="net" (bit 2), 3="storage" (bit 3) c1 subscribes to {"gpu", "alerts", "storage"} -> mask_a = 0b1011 c2 subscribes to {"alerts", "net"} -> mask_b = 0b0110 Intersection (shared channels): mask_a & mask_b = 0b1011 & 0b0110 = 0b0010 -> ["alerts"] Union (combined reach): mask_a | mask_b = 0b1011 | 0b0110 = 0b1111 -> ["gpu","alerts","net","storage"] Extracting set bit indices without scanning 512 zero bits: Trick: `lowest = mask & -mask` isolates the lowest '1' bit via two's-complement negation. For 0b1010: Pass 1 isolates 0b0010 (bit_length()-1 = 1 -> "alerts"), clears it -> 0b1000; Pass 2 isolates 0b1000 (bit_length()-1 = 3 -> "storage"), clears it -> 0. Runs in exact proportion to matched bits, skipping all zero bits!Here is the complete in-memory
MultiChannelQueuecombining dense interning, single-copy storage, two-stage fenced leases, bitwise union/intersection, and an inverted index (subscribers[cid], mapping each channel ID directly to the set of consumers following it):import heapq class MultiChannelQueue: def __init__(self, lease_ttl: float = 30.0, max_attempts: int = 3): self.lease_ttl = lease_ttl self.max_attempts = max_attempts # Channel registry: bidirectional mapping between names and dense IDs 0..C-1. self.channel_id = {} # name -> cid self.channel_name = [] # cid -> name self.logs = [] # logs[cid]: strictly increasing list of message seqs self.subscribers = [] # subscribers[cid]: set of subscribed consumer IDs # Single-copy payload store + optional (producer_id, producer_seq) deduplication. self.messages = {} # seq -> (payload, tuple_of_cids) self.producer_dedup = {} # (producer_id, producer_seq) -> seq self.next_seq = 1 # Stage 1: Per-consumer subscription bitmask and duplicate-free log merge state. self.positions = {} # consumer -> {cid: next unread index in logs[cid]} self.sub_mask = {} # consumer -> integer bitmask of subscribed cids self.sub_version = {} # consumer -> monotonic subscription version self.scanned_seq = {} # consumer -> highest seq already merged from logs # Stage 2: Per-consumer fenced visibility leases, retry min-heap, and dead letters. self.in_flight = {} # consumer -> {seq: (lease_epoch, expires_at)} self.retry_heap = {} # consumer -> min-heap of seqs awaiting retry self.attempts = {} # (consumer, seq) -> physical attempt count self.next_epoch = 1 # monotonic fencing token across all leases self.dead_letters = {} # consumer -> list of seqs that exceeded max_attempts def add_channel(self, name: str) -> int: cid = self.channel_id.get(name) if cid is None: cid = len(self.channel_name) self.channel_id[name] = cid self.channel_name.append(name) self.logs.append([]) self.subscribers.append(set()) return cid def enqueue(self, payload, channels, producer_id=None, producer_seq=None) -> int: unique_names = set(channels) if not unique_names: raise ValueError("channels must contain at least one channel") # Producer idempotency: return original seq if this producer retry already committed. if producer_id is not None and producer_seq is not None: dedup_key = (producer_id, producer_seq) if dedup_key in self.producer_dedup: return self.producer_dedup[dedup_key] seq = self.next_seq self.next_seq += 1 cids = [] for name in unique_names: cid = self.add_channel(name) cids.append(cid) self.logs[cid].append(seq) self.messages[seq] = (payload, tuple(cids)) if producer_id is not None and producer_seq is not None: self.producer_dedup[(producer_id, producer_seq)] = seq return seq def subscribe(self, consumer: str, name: str) -> int: cid = self.add_channel(name) consumer_positions = self.positions.setdefault(consumer, {}) self.scanned_seq.setdefault(consumer, 0) if cid not in consumer_positions: # Start at current tail so messages published before subscribe are not replayed. consumer_positions[cid] = len(self.logs[cid]) self.sub_mask[consumer] = self.sub_mask.get(consumer, 0) | (1 << cid) self.subscribers[cid].add(consumer) self.sub_version[consumer] = self.sub_version.get(consumer, 0) + 1 return self.sub_version.get(consumer, 0) def unsubscribe(self, consumer: str, name: str) -> int: cid = self.channel_id.get(name) consumer_positions = self.positions.get(consumer, {}) if cid is not None and cid in consumer_positions: del consumer_positions[cid] self.sub_mask[consumer] &= ~(1 << cid) self.subscribers[cid].discard(consumer) self.sub_version[consumer] = self.sub_version.get(consumer, 0) + 1 return self.sub_version.get(consumer, 0) def _requeue_or_dead_letter(self, consumer: str, seq: int) -> None: if self.attempts[(consumer, seq)] >= self.max_attempts: self.dead_letters.setdefault(consumer, []).append(seq) else: heapq.heappush(self.retry_heap.setdefault(consumer, []), seq) def _reap_expired_leases(self, consumer: str, now: float) -> None: leases = self.in_flight.get(consumer) if not leases: return expired_seqs = [] for seq, (_, expires_at) in leases.items(): if expires_at <= now: expired_seqs.append(seq) for seq in expired_seqs: del leases[seq] self._requeue_or_dead_letter(consumer, seq) def dequeue(self, consumer: str, now: float = 0.0): self._reap_expired_leases(consumer, now) # 1. Serve any released or lease-expired retry first so failed items are not forgotten. retries = self.retry_heap.get(consumer) if retries: chosen_seq = heapq.heappop(retries) else: # 2. Scan each subscribed channel log head, advancing past already-merged seqs. consumer_positions = self.positions.get(consumer, {}) seen_up_to = self.scanned_seq.get(consumer, 0) best_seq = None best_cid = None for cid, pos in consumer_positions.items(): log = self.logs[cid] while pos < len(log) and log[pos] <= seen_up_to: pos += 1 consumer_positions[cid] = pos if pos < len(log) and (best_seq is None or log[pos] < best_seq): best_seq = log[pos] best_cid = cid if best_seq is None: return None consumer_positions[best_cid] += 1 self.scanned_seq[consumer] = best_seq chosen_seq = best_seq # Issue a fenced visibility lease for this physical attempt. epoch = self.next_epoch self.next_epoch += 1 pair = (consumer, chosen_seq) self.attempts[pair] = self.attempts.get(pair, 0) + 1 self.in_flight.setdefault(consumer, {})[chosen_seq] = (epoch, now + self.lease_ttl) payload, _ = self.messages[chosen_seq] return chosen_seq, payload, epoch def ack(self, consumer: str, seq: int, lease_epoch: int) -> bool: # Reject late acknowledgements if the lease expired and moved to a newer epoch. leases = self.in_flight.get(consumer, {}) active = leases.get(seq) if active is None or active[0] != lease_epoch: return False del leases[seq] return True def release(self, consumer: str, seq: int, lease_epoch: int) -> bool: leases = self.in_flight.get(consumer, {}) active = leases.get(seq) if active is None or active[0] != lease_epoch: return False del leases[seq] self._requeue_or_dead_letter(consumer, seq) return True def mask_of(self, names) -> int: mask = 0 for name in names: cid = self.channel_id.get(name) if cid is not None: mask |= 1 << cid return mask def names_of(self, mask: int) -> list[str]: result = [] while mask: lowest_bit = mask & -mask cid = lowest_bit.bit_length() - 1 result.append(self.channel_name[cid]) mask ^= lowest_bit return result def shared_channels(self, consumer_a: str, consumer_b: str) -> list[str]: common_mask = self.sub_mask.get(consumer_a, 0) & self.sub_mask.get(consumer_b, 0) return self.names_of(common_mask) def union_channels(self, consumer_a: str, consumer_b: str) -> list[str]: combined_mask = self.sub_mask.get(consumer_a, 0) | self.sub_mask.get(consumer_b, 0) return self.names_of(combined_mask) def can_reach(self, producer_channels, consumer: str) -> bool: return (self.mask_of(producer_channels) & self.sub_mask.get(consumer, 0)) != 0 def audience(self, channels) -> set[str]: matched_consumers = set() for name in channels: cid = self.channel_id.get(name) if cid is not None: matched_consumers |= self.subscribers[cid] return matched_consumersAdding and retiring channels safely:
add_channelgrowschannel_name,logs, andsubscribersin amortizedO(1)time. Never reuse a retired channel's integercidwhile any retained message or saved bitmask still has that bit set — otherwise old bitcidsilently aliases to the new topic! IfCgrows past ~10,000 sparse channels, swap raw integer bitmasks for Roaring bitmaps (compressed chunked bitsets that keep sparse sets tiny while preserving fastAND/OR).Deep dive: how many channels do communication patterns need?
Suppose we are given
needs[producer] = set_of_target_consumerswith a strict isolation rule: no consumer may receive messages from a producer that did not target it. (Without isolation, 1 shared broadcast channel would trivially cover everything!)Write
needsas a0/1matrix with producers as rows and consumers as columns. One channelXconnects every producer publishing toXwith every consumer subscribed toX— forming an all-1s combinatorial rectangle called a biclique. Covering every1without touching any0using the fewest channels is the matrix's Boolean rank (minimum biclique cover), which is NP-hard in general.Even though the exact minimum is NP-hard, we can tightly bracket and construct strong covers: 1. Guaranteed upper bound —
min(distinct non-empty rows, distinct non-empty columns): Give each distinct producer target-set its own channel, or give each distinct consumer source-set its own inbox channel. You never need more than the smaller of the two! 2. Certifiable lower bound — a fooling set: Two required pairs(p1, c1)and(p2, c2)cannot share any channel if either cross-pair(p1, c2)or(p2, c1)is0(forbidden), because putting both pairs on one channel would leak messages across the forbidden cross-pair. Any set ofBmutually incompatible1-cells proves at leastBchannels are mathematically required.Worked 3x3 example: C1 C2 C3 P1 1 1 0 needs["P1"] = {"C1", "C2"} P2 0 1 1 needs["P2"] = {"C2", "C3"} P3 1 1 1 needs["P3"] = {"C1", "C2", "C3"} - Baseline upper bound: min(3 distinct rows, 3 distinct cols) = 3 channels. - Fooling set: {(P1, C1), (P2, C3)} cannot share a channel because (P1, C3) == 0 -> >= 2 channels! - Optimal 2-channel cover: Channel 0: producers {P1, P3} <-> consumers {C1, C2} Channel 1: producers {P2, P3} <-> consumers {C2, C3} Covers every '1', touches zero '0's, and matches the lower bound of 2 -> proven optimal!One subtle algorithmic trap: a greedy biclique cover alone can occasionally pick a large shared rectangle first that fractures leftover
1s into more pieces thanmin(distinct rows, distinct cols). Comparing the greedy biclique cover against the row-grouped and column-grouped baselines guarantees our planner always beats or tiesmin(distinct rows, distinct cols):def plan_channels(needs: dict[str, set[str]]) -> list[tuple[set[str], set[str]]]: """Build a leak-free (producers, consumers) channel plan <= min(distinct rows, distinct cols).""" uncovered = set() all_consumers = set() for producer, consumers in needs.items(): for consumer in consumers: uncovered.add((producer, consumer)) all_consumers.add(consumer) if not uncovered: return [] # Baseline 1: Group producers that share the exact same non-empty consumer row. by_row = {} for producer, consumers in needs.items(): if consumers: by_row.setdefault(frozenset(consumers), set()).add(producer) row_plan = [(producers, set(consumers)) for consumers, producers in by_row.items()] # Baseline 2: Group consumers that share the exact same non-empty producer column. by_col = {} for consumer in all_consumers: sources = set() for producer, consumers in needs.items(): if consumer in consumers: sources.add(producer) by_col.setdefault(frozenset(sources), set()).add(consumer) col_plan = [(set(producers), consumers) for producers, consumers in by_col.items()] # Close both producer-row seeds and single-consumer seeds into maximal leak-free rectangles. seeds = list(by_row.keys()) for consumer in all_consumers: seeds.append(frozenset([consumer])) seen = set() candidates = [] for seed in seeds: producers = set() for producer, reach in needs.items(): if seed <= reach: producers.add(producer) if not producers: continue closed_consumers = None for producer in producers: if closed_consumers is None: closed_consumers = set(needs[producer]) else: closed_consumers &= needs[producer] rect = (frozenset(producers), frozenset(closed_consumers)) if rect not in seen: seen.add(rect) candidates.append(rect) # Greedily pick the candidate rectangle covering the most remaining uncovered pairs. greedy_plan = [] remaining = set(uncovered) while remaining: best_rect = None best_gain = 0 for producers, consumers in candidates: gain = 0 for producer in producers: for consumer in consumers: if (producer, consumer) in remaining: gain += 1 if gain > best_gain: best_rect = (producers, consumers) best_gain = gain chosen_producers, chosen_consumers = best_rect greedy_plan.append((set(chosen_producers), set(chosen_consumers))) for producer in chosen_producers: for consumer in chosen_consumers: remaining.discard((producer, consumer)) # Return whichever valid leak-free cover uses the fewest channels. return min([greedy_plan, row_plan, col_plan], key=len) def fooling_set_lower_bound(needs: dict[str, set[str]]) -> int: """Return a certifiable lower bound on channel count via a greedy fooling set.""" fooling_pairs = [] for producer in sorted(needs): for consumer in sorted(needs[producer]): can_add = True for other_p, other_c in fooling_pairs: # If both cross-pairs are allowed, these two pairs COULD share a channel. if consumer in needs[other_p] and other_c in needs[producer]: can_add = False break if can_add: fooling_pairs.append((producer, consumer)) return len(fooling_pairs)Whenever
len(plan_channels(needs)) == fooling_set_lower_bound(needs), the plan is proven optimal; for offline schedules where closing a remaining gap matters, feedcandidatesto an integer linear program (ILP) solver. To activate a new plan online without dropping messages, stage the new channels first, wait for all consumers'sub_versionacknowledgements to converge, switch producers to the newplan_version, and drain old channels toRETIRED.Complexity analysis and distributed scaling
Let
k= channels on a message,s= channels a consumer subscribes to,C= total registered channels,N= total consumers,M= retained messages,r= consumer's in-flight/retry items, andW = ceil(C / 64)= 64-bit words per channel bitmask (W = 8forC = 512).Operation Time complexity Why it holds in plain words enqueueO(k)Deduplicates producer retries in O(1), stores payload once inmessages, and appendsseqtokarray logs (independent of subscriber count).dequeueO(s)amortized (orO(log r)on retry)Scans ssubscribed log heads; each delivered message creates at mostmin(k, s) - 1 < sduplicate entries across those logs, so total skipped duplicates overDdeliveries is< s * D(O(s)amortized per claim!).ack/releaseO(1)/O(log r)Verifies lease_epochinO(1)hash lookup;releasepushes onto the consumer'sr-item retry heap inO(log r).subscribe/unsubscribeO(1)with word array (O(W)Pythonint)Updates cursor map and subscriber set in O(1)expected time; flipping one bit isO(1)in a mutable 64-bit word array (O(W)when copying an immutable Pythonint).can_reach(pre-built masks)O(W)Computes one bitwise ANDacrossW = ceil(C / 64)words (+ O(k * W)if building the producer mask fromknames on the fly).shared_channels/union_channelsO(W + m)(O(W * m)Pythonint)Computes mask_a & mask_bormask_a | mask_binO(W)and peels off themset bits (O(1)per bit on hardware words via trailing-zero count).audience(channels)O(sum of \|subscribers[cid]\|)Unions the ksubscriber sets from the inverted index (O(k * ceil(N / 64))ifsubscribers[cid]is stored as a consumer bitset).Space complexity:
O(M * payload_bytes)for single-copy payloads +O(M * k)integers for per-channel logs and tag tuples +O(N * s)for cursors and inverted index +O(N * W)words for subscription bitmasks +O(total in-flight leases)for Stage 2 lease state.Scaling to a durable multi-node cluster: - Sliding-window retention: Trim messages older than
T(5 minutes) and maintain abase_offset[cid]integer per log so consumer indices stay valid without shifting array elements; if a stalled consumer lags behindbase_offset[cid], raise an explicit gap error rather than silently skipping messages. - Durability & fast cursor recovery: Appendenqueuerecords andackcheckpoints to a sequential Write-Ahead Log (WAL) flushed to disk withfsync(the OS call forcing buffered disk pages onto physical SSD) every 2–5 ms, paired with periodic snapshots. After restart, recoverpositions[consumer][cid]inO(s log L)via binary search (bisect_left) formax(acked_watermark + 1, sub_start_seq[cid]). - Sharding & the global-sequence trade-off: Shard payloads byhash(seq)and channel logs bycid(adding read replicas for hot 50,000-subscriber channels). Up to ~1–2M msgs/s, a lightweight sequencer assigns monotonicseqbatches on metadata headers while heavy payloads stream directly to storage nodes; beyond one sequencer, switch to independent per-channel offsets and deduplicate multi-channel deliveries on consumers using a bounded sliding set of(producer_id, producer_seq)IDs.
Intuition & how it works
Think of a multi-channel message queue as a central library shelf paired with topic index cards and numbered checkout slips. When a message arrives tagged with both "gpu" and "alerts", we do not photocopy the payload 30 times for 30 readers, nor do we force every reader to walk past every unrelated book in the building. Instead, we stamp the message with one global arrival number (say seq = 41), store one copy of the payload on the main shelf (messages[41]), and append 41 to the "gpu" index card and the "alerts" index card. Each consumer keeps a bookmark on just the index cards they follow plus a single integer scanned_seq recording the highest arrival number already pulled from their cards — so when 41 later appears on their second card, they immediately see 41 <= scanned_seq and skip the duplicate, while a numbered checkout slip (visibility lease) ensures crashed workers safely retry without double-delivering!
Naive designs fail on one of three fronts. Putting all messages into one global log and filtering on dequeue forces a consumer subscribed to 4 of 512 channels to scan ~64 irrelevant messages per match. Copying messages into per-consumer inboxes on enqueue turns one publish on a popular channel into thousands of writes and lets a crashed consumer blow up memory. And storing a 512-bit channel mask on every retained message wastes 64 bytes per message (960 MB for 15M messages) when storing a 2-element integer ID tuple takes ~4 bytes (60 MB).
Walk through a concrete 3-message trace:
- Intern channels to dense IDs:
"gpu" -> 0(bit0b001),"alerts" -> 1(bit0b010),"net" -> 2(bit0b100). Consumerc1subscribes to"gpu"and"alerts"(sub_mask = 0b011,scanned_seq = 0). - Enqueue 3 messages:
m1on{"gpu", "alerts"}getsseq = 1(logs[0] = [1],logs[1] = [1]);m2on{"net"}getsseq = 2(logs[2] = [2]);m3on{"alerts"}getsseq = 3(logs[1] = [1, 3]). - Leased dequeue for
c1: Firstdequeue("c1")checks the heads oflogs[0](1) andlogs[1](1), setsscanned_seq = 1, and leases(seq=1, m1, epoch=101). Once acknowledged, the seconddequeue("c1")seeslogs[0]is exhausted, skips1 <= scanned_seqat the front oflogs[1], advances to3, setsscanned_seq = 3, and leases(seq=3, m3, epoch=102)— deliveringm1once, skippingm2completely, and preserving arrival order. - Bitwise union & intersection: If
c2subscribes to"alerts"and"net"(0b110),c1andc2share0b011 & 0b110 = 0b010(["alerts"]) and together cover0b011 | 0b110 = 0b111(["gpu", "alerts", "net"]), each computed in a single bitwise operation.
Key trade-offs
- Fan-out on read (per-channel logs) vs. fan-out on write (per-consumer inboxes). Appending
seqtokchannel logs keepsenqueueatO(k)whether 2 or 50,000 consumers subscribe, and stalled consumers consume zero extra log memory; the trade-off is anO(s)amortized log-head scan duringdequeue. Per-consumer inboxes giveO(1)dequeueand write-time deduplication, but sufferO(fan-out)write spikes and unbounded per-consumer queues. - Global sequence number vs. independent per-channel offsets. One monotonic
seqcounter orders every channel log on the exact same timeline, giving per-consumer causal order andO(1)-space duplicate skipping viaseq <= scanned_seq. Across a large multi-broker cluster, a single counter becomes a throughput ceiling — requiring either a dedicated metadata sequencer (viable up to ~1–2M msgs/s) or independent per-channel offsets paired with a bounded consumer deduplication window of(producer_id, producer_seq)IDs. - Two-stage cursor + fenced visibility leases vs. immediate fire-and-forget cursor advance. Advancing the cursor and forgetting
seqondequeueloses messages whenever a consumer crashes mid-processing, whereas rewinding channel logs on timeout re-exposes multi-tag duplicates. Separating Stage 1 log merging (scanned_seq) from Stage 2 leased retries (lease_epochfencing tokens — monotonic numbers that reject lateacks from stalled zombie workers — plus a Dead-Letter Queue aftermax_attempts) achieves crash-safe at-least-once delivery without ever re-scanning logs. - Bitmasks vs. compact ID tuples vs. Roaring bitmaps. Interning (mapping channel names to
0 .. C - 1) lets consumer/producer sets live in bitmasks (integers where bitirepresents channeli), computing union and intersection across 512 channels inceil(512 / 64) = 8word operations. Messages carry onlyk ≈ 2tags so compact integer tuples save 16x RAM, and whenCreaches millions of sparse channels, Roaring bitmaps (compressed chunked bitsets) or sorted ID arrays replace dense bitmasks. - Biclique planner + row/column baselines vs. exact ILP solver. Under strict isolation, each channel in a
0/1producer-by-consumer matrix is an all-1s rectangle (biclique), and the exact minimum channel count is the NP-hard Boolean rank. Combining greedy maximal-biclique selection with row-grouped and column-grouped baselines guarantees<= min(distinct rows, distinct cols)in polynomial time while a fooling set (mutually incompatible1-cells that cannot share any channel) certifies optimality whenever upper and lower bounds meet.
Common mistakes
- Delivering a multi-tag message multiple times when a consumer subscribes to two or more of its tags — every correct design must explicitly deduplicate multi-channel matches.
- Accepting late acknowledgements without lease fencing. If Worker A stalls past its lease timeout, Worker B re-claims the message, and Worker A then wakes up and calls
ackwithout checkinglease_epoch, Worker B's in-flight attempt is prematurely marked complete. - Duplicating full message payloads across
kchannel queues, multiplying memory bykinstead of storing payloads once inmessages[seq]and appending 8-byteseqintegers to channel logs. - Using independent per-channel sequence counters (
1, 2, 3...per channel) with a singlescanned_seqinteger, which falsely drops unread messages on quieter channels! - Reusing a deleted channel's integer
cidwhile retained messages or consumer bitmasks still contain that bit, silently routing old tags to a newly created channel. - Claiming bitwise queries are unconditionally
O(1), omittingO(ceil(C / 64))word scaling (and forgetting that immutable Pythonintbit flips copy allceil(C / 64)words unless backed by a mutable word array). - Assuming greedy biclique selection alone always beats
min(rows, cols)(or answering"one channel per producer"without checking column covers and fooling-set lower bounds) — greedy choices can fracture remaining1s unless compared against the grouped row and column baselines.
Follow-up questions
- How would you support conjunctive ('all-of') subscriptions where a consumer only receives messages carrying every tag in a specified set? For bitmasks, the eligibility check changes from
(msg_mask & sub_mask) != 0to(msg_mask & sub_mask) == sub_mask. Duringdequeue, iterate only through the shortest channel log in the required conjunction (saylogs[A]whenlen(logs[A]) <= len(logs[B])) and verify inO(k)time whether candidatemessages[seq]also carriesB, skipping all traffic on busy channels. If many consumers subscribe to the exact same{A, B}pair, materialize an internal derived channelA&Bpopulated atenqueuetime. - How can this fan-out queue be extended to support competing worker pools (consumer groups) that share load? Move Stage 1 (
positions,scanned_seq) and Stage 2 (in_flight,retry_heap,dead_letters) ownership from an individual consumer ID to a named consumer group. When any worker in groupGcallsdequeue("G"), it claims the group's next unique matchingsequnder its own fencedlease_epoch; if that worker crashes beforeack("G", seq, epoch), the expired lease pushesseqintoG's sharedretry_heapso a healthy teammate picks it up automatically. - What data structures change if the broker must support millions of sparse, dynamically created channels? Dense 5M-bit masks would consume
625 KBper consumer, so replacesub_maskwith sorted 32-bit integer arrays (whensis small, computing union/intersection inO(s_a + s_b)via two-pointer merge) or Roaring bitmaps (whensvaries widely). Storelogs[cid]andsubscribers[cid]in hash maps rather than pre-allocating 5M-element arrays, and garbage-collect idle empty channels after retention expires while assigning monotonically increasing 64-bitcids that are never reused.
Follow-up questions
- How would you support conjunctive ('all-of') subscriptions where a consumer only receives messages carrying every tag in a specified set?
- How can this fan-out queue be extended to support competing worker pools (consumer groups) that share load?
- What data structures change if the broker must support millions of sparse, dynamically created channels?
Similar questions
- Ramping Up in Uncharted Systems and Resolving Senior Disagreements
- Dense and Sparse Vector Dot Product
- Iterative C++ Binary Search
- Global Live Video Streaming Platform
- Multi-User Collaborative Document Editor
- Burst-Resilient Multi-Channel Notification Platform