Design an in-memory message queue
hard 80 minBuild 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
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
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.
2004
Java 5 brings
BlockingQueueand its family: bounded waiting between threads in the standard library.2011
LinkedIn releases Apache Kafka as open source: a log on disk with positions kept by readers.
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.
- 1ApproachWhat this question tests, where it gets hard, and how to spend the time.
- 2ScopeAsk what changes the design, then commit to a short list.
- 3API and dataThe contract first, then the data that serves it.
- 4DesignStart with the smallest system that works. Change it only when something breaks.
- 5Deep divesCompare the options before you open them, then say which you would pick.
- 6Explain your choicesAnswer first. Then compare your reasoning.
- 7By levelThe same question is judged differently for mid, senior and staff.
- 8MockAnswer against the clock, then score yourself.
How it works
Step through the idea, or press Play.
Publish. Append with the next number, wake sleepers, return
Understand it
Start here
Newspapers on a clothesline
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
Ask
Does each subscriber get every message, or do they share? Ack? Order? What if it is full?
- 2
Cut
In: topics, subscriptions, poll, ack, redelivery, capacity. Out: disk, network, filters.
- 3
Draw
Log, Subscription, Topic, Broker, Worker.
- 4
Code
take,ack,publish,poll. The rest is names. - 5
Trace
A lease that ends, a late ack, a full topic.
- 6
Extend
Order by key, dead letters, or replay.
Words
Queue or topic?
Three things with similar names
| Plain queue | Observer | This page | |
|---|---|---|---|
| A message goes to | One consumer | All listeners, now | Each subscription, when it asks |
| Kept? | Until taken | No | Until all subscriptions finished it |
| Who runs the handler? | The consumer | The publisher's thread | The reader's thread |
| Home | Producer and consumer | Observer | Here |
Fan out, then share
Questions
Seven questions, and what each answer changes
| Ask | One answer | The other |
|---|---|---|
| Does each reader get every message? | A position for each reader | One queue, first come |
| Must a reader confirm? | Leases, receipts, redelivery | Position moves at once: at most once |
| In order? | A lane for each key | Any order, more workers |
| Full? | Reject: the publisher decides | Wait, or drop the oldest |
| Late subscriber? | From now | From the oldest kept |
| Pull or push? | poll | Handlers, built on poll |
| Restart? | Memory only | A log on disk: another problem |
Design, first try
The design most people draw first
The design to avoid: the publisher calls everybody
1/3One global broker
A single instance for the whole program. Two tests at once share their topics.
usesimplements
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 itDesign, better
The design to reach
The design to reach: one line of messages, and a peg for each reader
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
Who owns what
| Class | Knows | Decides | Does not know |
|---|---|---|---|
Log | Messages and numbers | The number of the next one | Readers |
Subscription | One reader's position and leases | What to offer next | Other readers |
Topic | The line, the pegs, the lock | What may be thrown away, who is woken | What messages mean |
Broker | Names | Nothing | Messages |
Worker | A handler | Ack or nack | Positions |
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
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
| Subscription | next | held | again | finished before |
|---|---|---|---|---|
| 3 | 3 | |||
| stock | 2 | 0 | 0 | |
| Topic | 0: nothing may go |
Promise
What can be said honestly
| Promise | Here | Because |
|---|---|---|
| Every message reaches every subscription | Yes, if it was subscribed before | Nothing is dropped before all finished |
| At least once | Yes | Leases and redelivery |
| Exactly once | No | A worker may finish and die before its ack. See idempotency |
| In order | Offered in order. Not finished in order, with several workers | Two workers run at their own speed |
| Survives a restart | No | Memory |
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
- Apache Kafka: design, consumers and positions
- Redis: streams
- Amazon SQS: visibility timeout
- RabbitMQ: consumer acknowledgements
- tokio: broadcast channel
- Kotlin: BufferOverflow
- Java SE 21 API: SubmissionPublisher
- LMAX Disruptor user guide
- LMAX Disruptor paper
- Guava: EventBus explained
- Node.js: events
- Python: threading, condition objects
- Wikipedia: publish and subscribe pattern
- Wikipedia: Apache Kafka