Sub topic 12
Publish/Subscribe and Routing
This chapter assumes you know what producers, consumers, brokers, queues, and acknowledgements are, and that you have read the chapters on competing consumers and ordering. It covers how one message can reach several independent consumers, and how a broker decides which queues get which messages.
Work queues versus publish/subscribe
In a work queue, each message goes to exactly one consumer. Consumers on the same queue compete, and the broker splits the work among them. This fits tasks such as "resize image 42".
In publish/subscribe (pub/sub), a message describes something that happened, such as "order 17 was placed". Several unrelated services may care about it: billing, email, analytics. Each of them needs its own copy. The producer should not know who they are.
The two models combine. Each subscribing service gets its own queue, which holds a copy of every message it is interested in. Inside one service, several instances compete on that service's queue. So pub/sub fans out between services, and competing consumers scale work within a service.
Exchanges, bindings, and routing keys
RabbitMQ separates publishing from queueing with three pieces. This chapter uses its vocabulary because most brokers have an equivalent.
- An exchange receives messages from producers. It stores nothing. It only decides where each message goes.
- A binding is a rule that links an exchange to a queue.
- A routing key is a string the producer attaches to a message. The exchange compares it with the bindings.
The exchange type sets the matching rule.
| Exchange type | Routing rule | Typical use |
|---|---|---|
| direct | Routing key must equal the binding key exactly | Send "error" logs to one queue and "info" logs to another |
| fanout | Ignores the routing key and copies to every bound queue | Broadcast an event to all subscribers |
| topic | Binding key is a pattern with `*` (one word) and `#` (zero or more words) | Select events by category, such as `order.*.eu` |
| headers | Matches on message header values | Rare. Use when a key string cannot express the rule |
The default exchange, named with an empty string, is a direct exchange that routes to the queue whose name equals the routing key. That is why the earlier examples published with exchange="" and routing_key="tasks".
A fanout example
Each subscriber declares its own queue and binds it to the exchange. A subscriber that wants a private, temporary queue can ask the broker for a server-named, exclusive one. The queue disappears when the connection closes.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.exchange_declare(exchange="events", exchange_type="fanout", durable=True)
# Durable, named queue: it keeps collecting messages while the service is down.
ch.queue_declare(queue="billing-events", durable=True)
ch.queue_bind(queue="billing-events", exchange="events")
ch.basic_publish(
exchange="events",
routing_key="",
body=b"order 17 placed",
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent),
)
conn.close()Run the declaration and bind step once per subscribing service, each with its own queue name. Publish after at least one queue is bound. Otherwise the message has nowhere to go.
A topic example
Topic exchanges let a consumer subscribe to a slice of the event stream. Routing keys are dot-separated words such as order.placed.eu.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.exchange_declare(exchange="orders", exchange_type="topic", durable=True)
ch.queue_declare(queue="eu-fulfilment", durable=True)
ch.queue_bind(queue="eu-fulfilment", exchange="orders", routing_key="order.*.eu")
ch.queue_declare(queue="audit", durable=True)
ch.queue_bind(queue="audit", exchange="orders", routing_key="order.#")
for key in ["order.placed.eu", "order.placed.us", "order.cancelled.eu"]:
ch.basic_publish(exchange="orders", routing_key=key, body=key.encode())
conn.close()The results:
order.placed.eugoes to botheu-fulfilmentandaudit.order.placed.usgoes only toaudit.order.cancelled.eugoes to both queues, because*matches any single word, includingcancelled.
A message matched by two bindings that point to the same queue is still delivered to that queue once.
Common mistakes
- Publishing before any queue is bound. Exchanges do not store messages. With no matching binding, the broker drops the message silently by default. Declare and bind queues before the producer starts, or use the mandatory flag with publisher returns so unroutable messages come back to the producer.
- Sharing one queue between different services. The services then compete for messages, and each sees only part of the stream. Give every service its own queue.
- Using temporary queues for services that must not miss events. An exclusive, server-named queue is deleted when the consumer disconnects. Events published during a restart are lost to that subscriber. Use a named, durable queue when the service needs catch-up after downtime.
- Putting routing logic in consumers. If a consumer receives many messages and discards most of them, move the filtering into bindings. The broker then never delivers the unwanted messages.
- Treating the routing key as a stable public contract by accident. Producers and consumers both depend on the key format. Changing
order.placed.eutoeu.order.placedbreaks every binding that uses the old pattern. Document the format and change it deliberately.
Failure behavior in pub/sub
Everything from earlier chapters still applies, but per queue. Each subscriber's queue has its own acknowledgements, retries, dead-letter queue, and backlog. A message that fails in the billing consumer does not affect the email consumer's copy.
Two points need care:
- Publishing is not atomic across queues. In practice the broker enqueues to all matched queues, but a crash can still leave a producer unsure whether the publish succeeded. A producer that retries the publish will create duplicates in every queue. Subscribers need idempotent consumers regardless.
- Slow subscribers accumulate backlog. Unbounded growth in one queue can exhaust broker memory or disk and affect every subscriber. Set a maximum queue length or a message TTL (time to live) for queues where old events lose their value, and monitor queue depth.
How this differs from log-based brokers
In an exchange-and-queue broker, the queue is the unit of storage. The broker deletes a message after the queue's consumer acknowledges it. A new subscriber only sees messages published after its queue was bound.
Log-based brokers, covered in the next chapter, keep an ordered log that consumers read at their own position. Many consumer groups can read the same data, and a new one can start from the beginning. That makes replay natural, where queue-based pub/sub has no replay unless you add it.
Exercise
A topic exchange has these bindings: queue A with shipment.#, queue B with shipment.*.fr, and queue C with *.delivered.*. Which queues receive a message published with routing key shipment.delivered.fr, and which receive shipment.delivered?
Show answer
shipment.delivered.fr matches all three. A matches because # accepts any remaining words. B matches because * takes delivered and the last word is fr. C matches because the three words fit *.delivered.*. shipment.delivered matches only A. B needs three words, and C needs three words, but this key has two. # in shipment.# matches the single remaining word.
Exercise
A team publishes order events to a fanout exchange. The email service uses an exclusive, server-named queue. After the email service restarts, customers miss confirmation emails for orders placed during the restart. What is the cause, and what is the fix?
Show answer
The exclusive queue was deleted when the service disconnected, so the exchange had no binding for the email service while it was down and the events were not kept for it. The fix is for the email service to declare a named, durable queue bound to the exchange. The queue then keeps collecting events during downtime, and the service processes the backlog on restart. The consumer should also be idempotent, because redelivery is still possible.