Sub topic 3
The Broker and Its Queues
Prerequisites
This chapter assumes you have read the earlier chapters on why to use a queue and on producers and consumers. You should be comfortable with basic Python and with the idea that a network service can fail between any two calls. The examples use RabbitMQ through the pika library. Running them needs a broker on localhost, for example docker run -p 5672:5672 rabbitmq:3. The concepts apply to most queue-based brokers, and the details that are specific to RabbitMQ are marked.
What the broker does
A broker is a server that sits between producers and consumers. Producers send messages to it and consumers read messages from it. The two sides never connect to each other, and neither needs to know the other's address, language, or whether it is running.
The broker takes on four jobs that would otherwise fall to your application code:
- It accepts messages over the network and stores them.
- It decides which queue each message goes into (routing, covered in a later chapter).
- It hands messages to consumers and tracks which ones are still in flight.
- It applies policies such as size limits, expiry, and dead-lettering.
Because the broker owns this state, a producer can finish its work and exit while messages wait. A consumer can crash and restart without the producer noticing.
Anatomy of a queue
A queue is an ordered buffer of messages that lives inside the broker. Messages are added at the tail and delivered from the head, so a single consumer sees them in first-in, first-out order. A queue has these main attributes:
- Name. Producers and consumers use it to find the queue. Many brokers also let the broker generate a unique name.
- Durability. A durable queue definition survives a broker restart. This is separate from whether the messages inside it survive, which the durability chapter covers.
- Exclusivity. An exclusive queue can be used by one connection only, and it is deleted when that connection closes.
- Auto-delete. The queue is removed after its last consumer disconnects.
- Arguments. Optional settings such as maximum length, message time-to-live, and the dead-letter target.
A queue is not a database. You cannot query it, you cannot read the third message without consuming the first two, and it is designed to be emptied. A queue that grows without bound usually means something is wrong.
Connections and channels
Opening a TCP connection is expensive, so AMQP, the protocol RabbitMQ uses, multiplexes many lightweight channels over one connection. You open one connection per process and one channel per thread or logical task. Channels are not thread-safe in pika's blocking client, so do not share one between threads.
Other brokers use different vocabulary. Amazon SQS is called over HTTP and has no persistent connection. Kafka clients keep connections to several brokers. In every case the client holds some session state, and the broker uses it to know which messages are in flight to which consumer.
Declaring a queue
Producers and consumers both declare the queue they use. Declaring is idempotent. If the queue already exists with the same attributes, the call succeeds and changes nothing. If it does not exist, the broker creates it. This removes any ordering requirement for startup, because whichever side starts first creates the queue.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ok = ch.queue_declare(
queue="tasks",
durable=True,
arguments={"x-max-length": 10000, "x-overflow": "reject-publish"},
)
print("ready:", ok.method.message_count, "consumers:", ok.method.consumer_count)
conn.close()The reply tells you how many messages are ready and how many consumers are attached. That makes the declare call a cheap way to check the queue's state.
Queue state: ready and unacknowledged
A message in a queue is in one of two states. A ready message is waiting for a consumer. An unacknowledged message has been delivered to a consumer, but the consumer has not yet confirmed it. The broker keeps unacknowledged messages so it can put them back if the consumer's connection drops. The next chapter covers acknowledgements in full. For now, note that "queue depth" can mean either ready messages or ready plus unacknowledged, depending on the tool you are reading.
You can inspect a queue without changing it by using a passive declare. This only checks that the queue exists. It never creates one.
import pika
from pika.exceptions import ChannelClosedByBroker
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
try:
ok = ch.queue_declare(queue="tasks", passive=True)
print("ready:", ok.method.message_count, "consumers:", ok.method.consumer_count)
except ChannelClosedByBroker as err:
print("broker closed channel:", err.reply_code, err.reply_text)
conn.close()In RabbitMQ, message_count here counts ready messages only. Messages that are delivered but unacknowledged are not included.
Limits and overflow behavior
A queue has finite capacity, bounded by memory and disk on the broker. Setting a limit turns a slow memory leak into a decision you make on purpose. With x-max-length set, the broker must do something when the queue is full. RabbitMQ offers these choices through x-overflow:
| Policy | Behavior when full | Trade-off |
|---|---|---|
| `drop-head` (default) | Discards the oldest message | Producers never block, but data is lost silently |
| `reject-publish` | Refuses new messages | Producers find out only if they use publisher confirms |
| `reject-publish-dlx` | Refuses new messages and dead-letters them | Keeps the rejected messages for inspection |
Which one is right depends on the data. Sensor readings where only the latest matters suit drop-head. Payment events do not. A rejected publish that the producer never checks is the same as a dropped message, so pair reject-publish with confirms.
A message time-to-live (x-message-ttl) works the same way along the time axis. Messages that wait longer than the TTL are removed or dead-lettered. This suits requests that become useless after a deadline, such as a "send the verification code" job that is stale after ten minutes.
Common errors
Redeclaring with different attributes. If tasks exists as durable and a second client declares it with durable=False, or with a different x-max-length, the broker closes the channel with 406 PRECONDITION_FAILED. Queue attributes cannot be changed by redeclaring. To change them, you delete and recreate the queue, or use a broker-side policy for the settings that support it. Keep the declaration in one shared module so every service uses identical arguments.
Publishing to a queue that does not exist. With RabbitMQ's default exchange, a message whose routing key matches no queue is silently discarded. The publish call returns normally. Declare the queue before publishing, or enable the mandatory flag and publisher confirms so that unroutable messages are reported back.
Assuming durable means safe. A durable queue survives a restart, but its messages are lost unless they were also published as persistent and written to disk. The example in the topic plan uses both durable=True and delivery_mode persistent for this reason.
Exclusive queues that disappear. An exclusive or auto-delete queue vanishes when its connection closes. Using one for a work queue means pending messages are lost on any reconnect. Reserve these for temporary reply or subscription queues.
Letting a queue grow unnoticed. Without a length limit, a stalled consumer lets the queue absorb messages until the broker runs out of memory or disk, and then it affects every other queue on that broker. Set limits and watch queue depth (see the monitoring chapter).
Summary of the working model
The broker is a stateful middleman. It owns queues, queues hold messages in order, and each message is either ready or unacknowledged. Declaring is safe to repeat only when the attributes match. Limits and TTLs define what happens under pressure, and the default behavior often discards data without telling anyone. Most production problems with queues come from configuration the team did not choose on purpose.
Exercise
A service declares the queue emails with durable=True and x-max-length=500. A second service later declares emails with durable=True and no max length. What happens, and how should the team prevent this?
Show answer
The broker rejects the second declaration and closes its channel with 406 PRECONDITION_FAILED, because the arguments differ from the existing queue. The second service cannot start using the queue until it declares it identically. To prevent this, keep the queue name and arguments in one shared configuration that both services import, and change them through a planned migration that deletes and recreates the queue (or through a broker policy, where the setting supports it).
Exercise
A producer publishes to the default exchange with the routing key taks (a typo). The queue is named tasks. The publish call raises no error. Where did the message go, and what two mechanisms would let the producer detect the problem?
Show answer
The default exchange found no queue named taks, so the broker discarded the message. The producer can detect this by publishing with the mandatory flag, so the broker returns unroutable messages, and by enabling publisher confirms so it receives an explicit result for each publish.