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
See it run
A numbered line and a peg for each reader: watch positions, receipts and leases.
Operations
Publish and poll
Append, hand out, answer.
Step 1 of 5
Two readers
Mail and stock are subscribed. The line is empty.
Step 1: Two readers
def publish(self, key, body): with self._changed: if len(self._log) >= self._rules.capacity: self._trim() if len(self._log) >= self._rules.capacity: raise TopicFull() message = self._log.append(key, body) self._changed.notify_all() return message.offset- Cost
- O(1)
- Guarantee
- Nothing is removed
Publish does not know who reads.
In the real world
The same in-memory message queue doing real jobs. Pick one and step through it.
The same slow worker, without receipts.
Step 1 of 3
Offered twice
a was too slow, b has message 0 now.
Step 1: Offered twice
def ack(self, offset): self._held.discard(offset) # whose answer is this?Common mistakes
The bugs interviewers watch for, with the fix beside each.
Handlers inside publish
criticalThe slowest handler sets the speed of the publisher, and the first that raises stops the rest.
Wrongfor handler in handlers: handler(body)Rightself._log.append(key, body)self._changed.notify_all()Ack before the work
criticalA crash between them loses the message.
Wrongtopic.ack(name, d.receipt)handler(d.message)Righthandler(d.message)topic.ack(name, d.receipt)Ack by offset
criticalA slow worker confirms what another one is working on.
Wrongtopic.ack(name, message.offset)Righttopic.ack(name, delivery.receipt)No limit
majorA lasting difference of rates fills any memory.
Wrongself._items.append(message)Rightif len(self._log) >= self._rules.capacity: raise TopicFull()Sleeping past a lease
majorA message becomes available and nobody looks until the next publish.
Wrongself._changed.wait(give_up - now)Rightwake = min(give_up, sub.next_expiry())self._changed.wait(wake - now)Subscribe resets
majorA worker that restarts skips what came meanwhile.
Wrongself._subs[name] = Subscription(...)Rightself._subs.setdefault(name, Subscription(...))
Interview tips
Open with
- Each, or shared?
- What does full mean?
- At least once, order by key.
Reject aloud
- No Publisher class.
- No queue for each reader.
- No Singleton.
Prove it
- The late ack.
- Full, then one ack.
- A lease ends in a sleep.
Never
- Promise exactly once.
- Grow without a limit.
- Drop without a count.