Skip to main content
07

Design an in-memory pub/sub message queue

HardPub/subMessage queueDelivery guaranteesBackpressure

Design an in-memory pub/sub message queue: producers publish messages to topics, and consumers subscribe to topics and process the messages, each at its own pace.

A typical framing: "Build a small message broker as a library, like a mini Kafka or RabbitMQ inside one process. Several producers and consumers run concurrently. Explain your classes, the delivery guarantees you offer, what happens when a consumer is slow or fails, and how you'd make it durable."

TL;DR

Model a topic as an append-only log of messages with increasing offsets. Each subscription (or consumer group) keeps its own offset, so consumers read independently and a slow consumer never blocks a fast one. Consumers pull (or are pushed to) messages and acknowledge them; the offset only moves forward after an ack, which gives at-least-once delivery. Messages that keep failing go to a dead-letter queue after N retries.

Protect shared state with locks or a single-threaded event loop per topic, and use condition variables or promises so idle consumers wait without busy-polling. Handle backpressure with a bounded log (block producers, drop old messages, or spill to disk). Durability means writing the log to disk (append and fsync) and storing committed offsets, which is exactly how Kafka works.

1. Requirements

Questions worth asking:

  • Is each message delivered to every subscriber (pub/sub fan-out), or to one worker in a group (work queue)? Or both?
  • Which delivery guarantee: at-most-once, at-least-once, effectively exactly-once?
  • Does order matter? Per topic, or per key?
  • What happens to old messages: kept for replay, or deleted after delivery?
  • Durable across restarts, or in memory only?

Functional

  • createTopic, publish(topic, message), subscribe(topic, group).
  • Every subscriber group receives every message; within a group, each message is handled by one consumer.
  • Acknowledge, retry with a limit, and a dead-letter queue.
  • Replay from an earlier offset.

Non-functional

  • Thread-safe under concurrent producers and consumers.
  • Slow consumers don't slow down producers or other consumers (within memory limits).
  • Order preserved per topic (or per partition).

2. Entities and classes

Loading diagram...
Loading diagram...

Two groups read the same log at different offsets: the log is stored once, and fan-out costs only one integer per group.

3. API

ts
interface Broker {
  createTopic(name: string, options?: { maxMessages?: number; retentionMs?: number }): void
  publish(topic: string, payload: unknown, key?: string): number // returns the offset
  subscribe(topic: string, group: string, options?: { maxAttempts?: number }): Subscription
}

interface Subscription {
  /** Waits until at least one message is available or the timeout passes. */
  poll(max: number, timeoutMs: number): Promise<Message[]>
  ack(offset: number): void
  nack(offset: number): void // retry later, or dead-letter after maxAttempts
  seek(offset: number): void // replay
}

A convenience layer can offer push-style handlers on top: subscribe(topic, group, async (msg) => { ... }) that polls in a loop, acks on success and nacks on error.

4. Core logic

ts
class Topic {
  private log: Message[] = []
  private baseOffset = 0 // offset of log[0], grows as old messages are trimmed
  private waiters: (() => void)[] = []

  append(payload: unknown, key?: string): number {
    const offset = this.baseOffset + this.log.length
    this.log.push({ offset, key, payload, timestamp: Date.now() })
    // Wake every consumer waiting for new data.
    this.waiters.splice(0).forEach((wake) => wake())
    return offset
  }

  read(from: number, max: number): Message[] {
    const start = Math.max(from - this.baseOffset, 0)
    return this.log.slice(start, start + max)
  }

  waitForData(): Promise<void> {
    return new Promise((resolve) => this.waiters.push(resolve))
  }

  get endOffset() {
    return this.baseOffset + this.log.length
  }
}

class GroupSubscription implements Subscription {
  private nextOffset: number // next message to hand out
  private inFlight = new Map<number, { msg: Message; deadline: number }>()
  private attempts = new Map<number, number>()

  constructor(
    private topic: Topic,
    private committed: number,
    private dlq: DeadLetterQueue,
    private maxAttempts = 5,
    private visibilityMs = 30_000,
  ) {
    this.nextOffset = committed
  }

  async poll(max: number, timeoutMs: number): Promise<Message[]> {
    this.redeliverExpired()
    if (this.nextOffset >= this.topic.endOffset) {
      await Promise.race([this.topic.waitForData(), sleep(timeoutMs)])
    }
    const batch = this.topic.read(this.nextOffset, max)
    for (const msg of batch)
      this.inFlight.set(msg.offset, { msg, deadline: Date.now() + this.visibilityMs })
    this.nextOffset += batch.length
    return batch
  }

  ack(offset: number) {
    this.inFlight.delete(offset)
    // Commit only up to the lowest unacked offset, so a crash never skips a message.
    const lowestPending = Math.min(...this.inFlight.keys(), this.nextOffset)
    this.committed = Math.max(this.committed, lowestPending)
  }

  nack(offset: number) {
    const entry = this.inFlight.get(offset)
    if (!entry) return
    const tries = (this.attempts.get(offset) ?? 0) + 1
    this.attempts.set(offset, tries)
    if (tries >= this.maxAttempts) {
      this.dlq.add(entry.msg, 'max attempts reached')
      this.ack(offset)
    } else {
      entry.deadline = Date.now() + backoff(tries) // redelivered later
    }
  }

  private redeliverExpired() {
    /* in-flight messages past their deadline go back to the consumers */
  }
}

In JavaScript the event loop already serializes these methods, so no locks are needed. In a multi-threaded language (Java, Go), guard each topic's log and each subscription's state with a lock, and use a condition variable (await/signal) instead of the waiter list.

5. Edge cases and extensions

  • Delivery guarantees:
    • At-most-once: commit the offset before processing. Fast, but a crash loses the message.
    • At-least-once: commit after processing (the design above). A crash causes redelivery, so consumers must be idempotent (dedupe by message id).
    • Exactly-once in practice means at-least-once plus idempotent processing, or writing results and offsets in the same transaction.
  • Ordering: one log gives total order per topic but only one consumer per group can preserve it. To scale, split the topic into partitions by hash(key): order is kept per key (e.g. per order id), and each partition goes to one consumer in the group.
  • Backpressure and memory: cap the log size. When full, either block producers (safest), drop the oldest messages (fine for metrics), or spill to disk. Trim messages that every group has committed past.
  • Poison messages: a message that always crashes the consumer is retried with backoff, then moved to the dead-letter queue so it can't block the partition forever.
  • Durability: append each message to a segment file and fsync (per message or in batches, trading latency for safety). Store committed offsets per group in a small file or table. On restart, rebuild the in-memory index from the files.
  • Push vs. pull: pull lets each consumer control its own rate (Kafka); push gives lower latency but needs per-consumer flow control (RabbitMQ's prefetch).

Common follow-ups

  • "Queue or log: what's the difference?" A queue deletes a message once it's consumed, and competing consumers share the work. A log keeps messages for a retention period, and each group tracks its own position, so new consumers can replay history.
  • "How would you scale it across machines?" Partition topics across brokers, replicate each partition to followers (a leader handles writes), and keep cluster metadata in a coordination service (Raft, ZooKeeper or KRaft in Kafka).
  • "How do you test concurrency?" Run many producers and consumers with random delays, then check invariants: no message lost, none processed twice within a group without a crash, order preserved per key.

What interviewers look for

  • The log + offsets per group model, and clear fan-out vs. work-queue semantics.
  • A deliberate delivery guarantee, with acks, retries and a dead-letter queue.
  • Thread safety and waiting without busy-polling.
  • Backpressure and retention decisions.
  • Ordering via partitions by key, and a path to durability.

Was this helpful?