RabbitMQ
medium 32 minRabbitMQ is an open-source message broker.
See it run
How a message finds its queues, and what happens until it is acknowledged.
Operations
How an exchange routes
One message through direct, topic, fanout and headers exchanges, and one that fits nowhere.
Step 1 of 6
Direct
One exact match
The routing key error must equal the binding key. Only queue A was bound with error.
Step 1: Direct
def route(kind, bindings, key, headers): if kind == "fanout": return [q for q, _ in bindings] if kind == "direct": return [q for q, b in bindings if b == key] if kind == "topic": return [q for q, b in bindings if topic_match(b, key)] if kind == "headers": return [q for q, b in bindings if b.items() <= headers.items()]- What you get
- Routing without code
- What it costs
- Bindings to manage
In a topic pattern * is exactly one word and # is zero or more words, with dots between words.
In the real world
The same rabbitmq doing real jobs. Pick one and step through it.
Consumers stop. What protects the broker?
Step 1 of 3
Normal day
- Memory
- 20%
- Disk used
- 30%
Messages are taken as fast as they come.
Step 1: Normal day
Common mistakes
The bugs interviewers watch for, with the fix beside each.
Automatic acknowledgement for real work
criticalThe broker deletes the message as soon as it is sent. A crash loses it, and prefetch does not hold back the flow.
Wrongbasic_consume("orders", on_message, auto_ack=True)Rightbasic_consume("orders", on_message, auto_ack=False)# basic_ack after the workPublishing without confirms
criticalA connection can break after the send and before the store. Without a confirm nobody knows.
Wrongchannel.basic_publish("orders", key, body)Rightchannel.confirm_delivery()channel.basic_publish("orders", key, body, persistent, mandatory=True)Requeue at once on failure
majorThe same message comes straight back and spins at full speed. Since 4.3 a nack does not even count towards the limit.
Wrongbasic_nack(tag, requeue=True)Rightbasic_reject(tag, requeue=True) # with delayed retry# or requeue=False to the dead-letter exchangeA connection per message
majorOpening one costs a TCP and login exchange. Keep one open and use a channel per thread.
Wrongfor m in messages: connect().channel().basic_publish(...)Rightconn = connect()channel = conn.channel() # long-lived, one per thread
Interview tips
How to explain it
- Publish to an exchange, with a key.
- Bindings decide which queues get a copy.
- A queue deletes a message when it is acknowledged.
Never lose one
- Quorum queue, persistent messages.
- Publisher confirms and mandatory.
- Manual acks and a dead-letter exchange.
Numbers of 4.4
- Memory alarm at 60%, disk at 50 MB free.
- Delivery limit 20 in quorum queues.
- Largest message 16 MiB by default.
Think again when
- Many readers replay a long history: a log, or a stream.
- One ordered queue must carry more than one leader can.
- Nobody will run it.