Sub topic 15
Monitoring queue health
This chapter assumes you know how acknowledgements, prefetch, retries, and dead-letter queues work, and that you can run a local RabbitMQ broker for the examples. The earlier chapters explained how to build a reliable pipeline. This one covers how to tell whether it is still reliable while it runs.
A queue fails quietly. Producers keep succeeding, the broker stays up, and no HTTP request returns a 500. The only symptom is that work finishes later than it should, or never finishes. Monitoring exists to turn that silence into a signal.
What to measure
No single number describes queue health. You need signals from each point in the path: the producer side, the queue, the consumers, and the dead-letter queue.
| Signal | What it tells you | Typical cause when it looks bad |
|---|---|---|
| Ready depth | Messages waiting for a consumer | Consumers too slow, too few, or absent |
| Unacknowledged count | Messages delivered but not yet acked | Slow handler, stuck consumer, prefetch set too high |
| Consumer count | Connected consumers on the queue | Deploy failure, crash loop, lost connections |
| Message age | How long the oldest message has waited | Sustained backlog, a blocked head of the queue |
| Publish rate and ack rate | Work arriving versus work finishing | Traffic burst or a slowdown downstream |
| Redelivery rate | Messages delivered more than once | Handler crashes, nacks with requeue, poison messages |
| Dead-letter queue depth | Messages that exhausted their retries | Bugs, bad input, an outage in a dependency |
| Broker resources | Memory, disk, file descriptors, alarms | Large backlogs, unbounded queue growth |
The diagram shows where each signal comes from.
Depth alone is misleading
A queue with 50,000 messages can be healthy if consumers are draining it quickly. A queue with 20 messages can be broken if those messages have waited an hour. Depth is a count, and users care about time.
Two measurements are more useful than raw depth:
- Trend. Depth that rises steadily for several minutes means arrivals exceed completions. Depth that spikes and falls is a burst being absorbed, which is what queues are for.
- Age. The age of the oldest message is the delay the slowest user is experiencing. It maps directly to a service-level objective such as "images are resized within 60 seconds".
Reading queue state from code
RabbitMQ lets a client inspect a queue without changing it by using a passive declare. This script reads the ready count and consumer count.
import pika
def queue_stats(channel, name):
ok = channel.queue_declare(queue=name, passive=True)
return ok.method.message_count, ok.method.consumer_count
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ready, consumers = queue_stats(ch, "tasks")
print(f"ready={ready} consumers={consumers}")
if ready > 0 and consumers == 0:
print("ALERT: messages waiting and nobody consuming")
conn.close()For production, do not poll with a script like this. RabbitMQ's management API and its Prometheus plugin expose messages_ready, messages_unacknowledged, and consumers per queue, and your metrics system can store and graph them. The passive declare is useful for tests and quick checks. A passive declare on a queue that does not exist makes the broker close the channel, so open a fresh channel for each check.
Measuring message age
The broker does not report the age of the oldest message directly in a portable way, so you measure it where you can. The producer stamps each message with a timestamp, and the consumer computes how long the message waited.
import time
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.basic_publish(
exchange="",
routing_key="tasks",
body=b"resize image 42",
properties=pika.BasicProperties(
delivery_mode=pika.DeliveryMode.Persistent,
timestamp=int(time.time()),
),
)
def handle(channel, method, properties, body):
age = time.time() - properties.timestamp
print(f"age={age:.1f}s body={body!r}")
channel.basic_ack(delivery_tag=method.delivery_tag)
channel.stop_consuming()
ch.basic_consume(queue="tasks", on_message_callback=handle)
ch.start_consuming()
conn.close()Export this value as a histogram or gauge from the consumer and alert on a high percentile. The measurement has two limits. It only exists while a consumer is running, so a queue with no consumers reports nothing. Alert on consumer count and ready depth for that case. It also depends on the clocks of the producer and consumer hosts agreeing, so keep them synchronized with NTP.
Rates tell you whether you are winning
Compare the publish rate with the ack rate. The difference decides whether a backlog grows or drains.
def backlog_report(depth, publish_rate, ack_rate):
net = publish_rate - ack_rate
if net > 0:
return f"growing by {net:.1f} msg/s: add consumers or slow producers"
if net == 0:
return "steady" if depth == 0 else f"stuck at {depth} messages"
if depth == 0:
return "idle"
seconds = depth / -net
return f"draining, empty in about {seconds:.0f}s"
print(backlog_report(depth=6000, publish_rate=40, ack_rate=100))
print(backlog_report(depth=6000, publish_rate=120, ack_rate=100))
print(backlog_report(depth=0, publish_rate=10, ack_rate=10))The first call prints a drain estimate of 100 seconds. The second reports growth of 20 messages per second. This calculation is what an on-call engineer actually needs: whether the situation resolves by itself.
Failure patterns and what they look like
Each common failure has a distinct signature across the signals.
- No consumers. Consumer count is 0, ready depth climbs, and the ack rate is 0. A deploy failed or the consumer process is crash-looping.
- Stuck consumer. Consumers are connected, unacknowledged count equals consumers times prefetch, and the ack rate is 0. Handlers are blocked on a dependency, or one consumer holds messages it never acks. Because the connection is alive, the broker does not requeue them.
- Poison message. The redelivery rate is high while depth is flat. One message fails and is requeued repeatedly. Rejecting without requeue, together with a dead-letter policy, stops the loop.
- Slow downstream. Consumers are healthy but handler duration rises. The ack rate falls, and depth and age grow.
- Producer burst. Publish rate jumps, depth rises, and then it drains after the burst. This is normal unless age breaches your objective.
- Dead-letter growth. DLQ depth increases. Messages are failing permanently, and someone must inspect them.
What to alert on
Alert on conditions that need a human, and send everything else to a dashboard.
- Message age above the objective for several minutes. This is the symptom users feel, so make it your primary alert.
- Ready depth above zero with zero consumers. Nothing will fix itself.
- Any dead-letter queue message. Page for critical flows and open a ticket for the rest. The DLQ should normally be empty.
- Sustained depth growth. Require the condition to hold for a window such as 10 minutes, so short bursts do not cause pages.
- Broker resource alarms. When RabbitMQ hits a memory or disk alarm, it blocks publishers.
Set a duration on every alert. A threshold with no time window flaps during normal bursts, and teams learn to ignore it.
Lag in log-based brokers
Log-based brokers such as Kafka do not delete messages when they are consumed, so "queue depth" does not exist. The equivalent is consumer lag: the latest offset in a partition minus the offset the consumer group has committed. Track lag per partition. A single stuck partition hides inside a healthy-looking total, because ordering within a partition means one slow message blocks everything behind it.
Exercise
A queue shows ready depth 0, 4 consumers, and a flat ack rate of 0 messages per second. Publishers are sending 30 messages per second. The dashboard looks calm. What is likely wrong, and which two signals confirm it?
Show answer
The queue is probably empty only because the consumers have taken every message and are not finishing them. The messages are delivered but unacknowledged, so ready depth stays at 0 while the handlers are stuck on a blocked dependency or a deadlock. The unacknowledged count, which should sit at consumers times prefetch, and message age (or handler duration) confirm it. The ack rate of 0 against a publish rate of 30 shows work is arriving and not completing.