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.

Video lesson · Chapter 1 of 6

Make a prediction

0:00 / 4:54

One line, many pegs: pub and sub

1:25Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

An in-memory message queue lets parts of one program talk without calling each other. A publisher appends a message to a topic. Each subscription reads all messages at its own speed.

The topic is a log: messages with numbers that never change. A subscription is a position in it, plus what its workers hold at the moment.

A worker gets a message for a limited time, with a receipt. If it answers, the message is done. If it is silent, the message is offered again.

Why it exists

Direct calls tie the speed and the failures of one part to another. An order should not wait for a mail, and should not fail because of it.

The problem is a favourite because it starts as a map of lists and becomes real with each question: a slow reader, a dead worker, a full memory, an order to keep.

The ideas are the same as in large brokers, so this is also the best way to understand those: positions, leases, dead letters, retention.

A short history

  1. 1987

    The news subsystem of the Isis toolkit is presented at the ACM symposium on operating systems principles: one of the earliest publicly described publish and subscribe systems.

  2. 2004

    Java 5 brings BlockingQueue and its family: bounded waiting between threads in the standard library.

  3. 2011

    LinkedIn releases Apache Kafka as open source: a log on disk with positions kept by readers.

  4. 2011

    LMAX publishes the Disruptor: a ring buffer in memory in place of queues between threads.

Words to know

Topic
A named line of messages.
Offset
The number of a message in its topic. Never used again.
Subscription
One reader's position and leases. Workers with the same name share it.
Lease
A message is yours until a moment. Also called visibility timeout.
Receipt
The number of one hand-over.
Ack, nack
Done. I could not.
At least once
Never lost, perhaps repeated.
Dead letter
A message that used all its tries.
Backpressure
Slowing the sender because the receiver is slow.
Lag
How many messages a subscription is behind.
Retention
The rule for what is kept.

The solution, twice

Reach the regular design first. Then go where a FAANG interviewer digs.

Solve it like an interview

New to it? Start with Approach. Revising? Go straight to the mock.

  1. 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
  2. 2ScopeAsk what changes the design, then commit to a short list.
  3. 3API and dataThe contract first, then the data that serves it.
  4. 4DesignStart with the smallest system that works. Change it only when something breaks.
  5. 5Deep divesCompare the options before you open them, then say which you would pick.
  6. 6Explain your choicesAnswer first. Then compare your reasoning.
  7. 7By levelThe same question is judged differently for mid, senior and staff.
  8. 8MockAnswer against the clock, then score yourself.

How it works

Step through the idea, or press Play.

Step 1 of 3

Publish. Append with the next number, wake sleepers, return

Understand it

Start here

Newspapers on a clothesline

One line of papers, and a peg for each reader
012

What an interviewer looks for

  • Who waits for whom?

    The publisher must not wait for a slow reader, unless you decide that it should.

  • What if a reader dies?

    A lease and a receipt, so that a message is offered again and a late answer is refused.

  • What if it is full?

    Memory ends. Reject, wait or drop: choose one, and say who loses.

  • Which promise?

    At least once, and order within a key. Say both before they ask.

How to spend the round

  1. 1

    Ask

    Does each subscriber get every message, or do they share? Ack? Order? What if it is full?

  2. 2

    Cut

    In: topics, subscriptions, poll, ack, redelivery, capacity. Out: disk, network, filters.

  3. 3

    Draw

    Log, Subscription, Topic, Broker, Worker.

  4. 4

    Code

    take, ack, publish, poll. The rest is names.

  5. 5

    Trace

    A lease that ends, a late ack, a full topic.

  6. 6

    Extend

    Order by key, dead letters, or replay.

Words

Queue or topic?

Three things with similar names

Plain queueObserverThis page
A message goes toOne consumerAll listeners, nowEach subscription, when it asks
Kept?Until takenNoUntil all subscriptions finished it
Who runs the handler?The consumerThe publisher's threadThe reader's thread
HomeProducer and consumerObserverHere
Two workers with one subscription name share its messages, like a queue. Two subscriptions each get all of them, like listeners.

Fan out, then share

Mail and stock each get every order. The two stock workers share theirs.

Questions

Seven questions, and what each answer changes

AskOne answerThe other
Does each reader get every message?A position for each readerOne queue, first come
Must a reader confirm?Leases, receipts, redeliveryPosition moves at once: at most once
In order?A lane for each keyAny order, more workers
Full?Reject: the publisher decidesWait, or drop the oldest
Late subscriber?From nowFrom the oldest kept
Pull or push?pollHandlers, built on poll
Restart?Memory onlyA log on disk: another problem

Design, first try

The design most people draw first

The design to avoid: the publisher calls everybody

MessageBroker- instance: MessageBroker- handlers: Map<String, List>+ getInstance()+ publish(topic, body)+ subscribe(topic, h)

1/3One global broker

A single instance for the whole program. Two tests at once share their topics.

usesimplements

It also remembers nothing. Whoever subscribes a second later, or is restarting, has missed the message. It is an observer list, and not a queue.
Python
class BadBroker:    def __init__(self):        self.handlers = {}    def subscribe(self, topic, handler):        self.handlers.setdefault(topic, []).append(handler)    def publish(self, topic, body):        for handler in self.handlers[topic]:     # in the publisher's thread            handler(body)                        # slow: all wait. Raises: the rest get nothing        # and nothing is kept: whoever was away has missed it
Nine lines. Slow, fragile and forgetful: three faults with one cause. The publisher does the reader's work.

Design, better

The design to reach

The design to reach: one line of messages, and a peg for each reader

0 to nLog+ first: int+ next: int+ append(key, body)+ read(offset): Message+ dropBefore(offset)Message+ offset: int+ key: String+ body: String

1/5A line that only grows

Log gives every message a number, for ever. Messages are never changed, so any number of readers may look at them.

owns (dies together)depends on

Worker depends on a subscription by its name. All calls go through the topic.

Who owns what

ClassKnowsDecidesDoes not know
LogMessages and numbersThe number of the next oneReaders
SubscriptionOne reader's position and leasesWhat to offer nextOther readers
TopicThe line, the pegs, the lockWhat may be thrown away, who is wokenWhat messages mean
BrokerNamesNothingMessages
WorkerA handlerAck or nackPositions

States

The life of one message in one subscription

Each subscription has its own copy of this picture

The hard part

A reader that is too slow

A late answer

The receipt names the hand-over and not the message. So the topic can tell who is answering.

How does the topic know that a message is done?

BreaksHanding it out is enough
How
The position moves at poll.
Limit
A worker that dies takes the message with it. At most once.
Choose when
Readings that nobody misses.
WorksAck by offset
How
ack(0)
Limit
A worker that was too slow confirms a message that another one is working on, perhaps failing on.
Choose when
One worker for each subscription.
StrongAck by receipt, with a lease
How
Every hand-over has its own number and end.
Limit
A map, and the caller keeps the number.
Choose when
Whenever a message may be offered twice.

Memory

What may be thrown away?

Trimming

Mail has finished 0, 1, 2. Stock holds 0, and has finished 1

Subscriptionnextheldagainfinished before
mail33
stock200
Topic0: nothing may go
One message that is held by one reader keeps all that came after it. Watch this number in production.

Promise

What can be said honestly

PromiseHereBecause
Every message reaches every subscriptionYes, if it was subscribed beforeNothing is dropped before all finished
At least onceYesLeases and redelivery
Exactly onceNoA worker may finish and die before its ack. See idempotency
In orderOffered in order. Not finished in order, with several workersTwo workers run at their own speed
Survives a restartNoMemory

Do

  • Number the messages, never change them
  • One position for each subscription
  • Receipts with an end
  • Choose what full means
  • Run handlers without any lock

Do not

  • Call handlers from publish
  • Delete a message at the first read
  • Ack by offset
  • Let the queue grow without a limit
  • Promise exactly once

Summary

The whole topic in one minute.

A topic is one numbered log, and each subscription has its own position. A poll hands out a message with a lease and a receipt. Ack ends it, nack or silence offers it again, and after the last try it becomes a dead letter.

The slowest subscription decides what may be thrown away. When that is not enough, the topic is full, and full must have a meaning: reject, wait or drop. One lock for each topic, handlers outside.

  • A topic is a numbered line. Reading moves a peg and takes nothing away.
  • A poll is a lease with a receipt. No answer in time means: offered again.
  • A late answer has an old receipt and changes nothing.
  • Only what all readers finished may be thrown away. If that is not enough, full has to mean something.
  • One lock for each topic, short steps, handlers outside.
  • At least once, order within a key: say it first.

Sources