AlgoViz

Design an in-memory message queue

hard 80 min

Build publish and subscribe in one process: a numbered log, a position for each subscription, leases with receipts, redelivery and dead letters, a rule for a full topic, and order by key.

Watch lesson4:54

Where it shows up

The same pattern appears across everyday software.

  • Apache Kafka consumers

    A consumer sends its offset in the log with each request and gets a chunk from there. It controls its position and can rewind it. The peg of this page, on disk and over a network.

  • Redis Streams

    Consumer groups share a stream. What was handed out and not confirmed is in a pending entries list, and `XAUTOCLAIM` gives idle entries to another consumer: a lease that ends.

  • Amazon SQS visibility timeout

    A received message is hidden for a time. If it is not deleted by then, it can be received again. The lease under another name.

  • RabbitMQ acknowledgements

    Manual acks with a prefetch limit on messages in progress. The documentation warns of requeue loops when consumers cannot process a message, and suggests counting redeliveries.

  • tokio broadcast channel (Rust)

    Every receiver gets every value. When a slow one is overtaken, it gets `Lagged` with the number of values it has missed, and goes on at the oldest one kept. Drop oldest, with a count.

  • Kotlin shared flow

    A buffer for late subscribers, and a rule for a full one: `SUSPEND`, `DROP_OLDEST` or `DROP_LATEST`. Wait, drop oldest, drop newest.

  • Java SubmissionPublisher

    Each subscriber has its own bounded buffer. `submit` waits when one is full, `offer` can drop instead. The push design in the standard library.

  • LMAX Disruptor

    A ring buffer between threads. Producers must not overrun consumers, which is done by adding the consumers' numbers as gating sequences: the slowest reader decides.

  • Guava EventBus

    Publish and subscribe by type of event in one program. An event without any subscriber is wrapped in a `DeadEvent`, so that it can be noticed.

  • Node EventEmitter

    Calls all listeners synchronously, in the order in which they were registered. The observer end of the scale: no memory, and the publisher's thread.