Sub topic 9
Backpressure and Prefetch Limits
This chapter assumes you know what producers, consumers, brokers, and acknowledgements are, and that you have seen competing consumers share one queue. It covers how a queue-based system slows down gracefully when consumers cannot keep up, and how the prefetch limit controls how much work each consumer holds at once.
What backpressure means
Backpressure is the set of signals that tell a fast sender to slow down because the receiver is full. Without it, a producer that publishes faster than consumers can process will grow the queue without bound. The queue then eats broker memory or disk, and the delay between publishing and processing keeps growing.
A queue absorbs short bursts well. It cannot fix a long-term gap between the rate in and the rate out. If producers send 200 messages per second and consumers finish 150 per second, the queue grows by 50 messages every second, forever.
Backpressure can be applied in several places:
| Place | Mechanism | Effect |
|---|---|---|
| Consumer | Prefetch limit | Each consumer holds only a bounded number of unacknowledged messages |
| Broker | Queue length limit, memory or disk alarms | Broker rejects, drops, or blocks publishers |
| Producer | Publisher confirms, timeouts, bounded local buffers | Producer slows down or fails fast |
| Edge | Rate limiting, HTTP 429 or 503 | Callers are told to retry later |
The prefetch limit
Without a limit, many brokers push messages to a consumer as fast as the network allows. A consumer that is busy with one slow message would then hold thousands of others in its local buffer. Those messages are invisible to other consumers, even idle ones.
Prefetch (called the QoS setting in RabbitMQ) caps the number of delivered but unacknowledged messages per consumer. When the cap is reached, the broker stops sending more until the consumer acknowledges some.
The consumer from the earlier chapter already sets it:
import pika
def process(body):
print("handling", body)
def handle(ch, method, properties, body):
try:
process(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.basic_qos(prefetch_count=10)
ch.basic_consume(queue="tasks", on_message_callback=handle, auto_ack=False)
ch.start_consuming()With prefetch_count=10, the broker sends up to 10 messages. After the consumer acknowledges one, the broker sends the next. The consumer's local backlog never exceeds 10.
Prefetch only works with manual acknowledgements. With auto_ack=True, the broker considers a message done the moment it is sent, so nothing is ever "unacknowledged" and the limit has no effect.
Why prefetch matters for fairness
Consider two consumers and a queue of mixed-cost jobs. Suppose the broker hands out messages round-robin without a limit. Consumer A might receive all the slow jobs, while consumer B finishes its share quickly and sits idle. A low prefetch fixes this, because B asks for more as soon as it acknowledges, and so B naturally takes on more work.
Choosing a prefetch value
Prefetch trades latency, throughput, and fairness against each other.
- Prefetch of 1: The fairest setting. Each consumer holds one message at a time. The cost is a network round trip between every message, because the broker waits for the ack before sending the next. For fast handlers this wastes time.
- Moderate prefetch (10 to 50): A common starting point. The next message is already waiting locally when the current one finishes, which keeps the consumer busy.
- High prefetch (hundreds or more): Maximizes throughput for tiny, uniform messages. The risks are unfair distribution, high memory use in the consumer, and a large batch of redelivered messages if the consumer crashes.
A rough rule: the prefetch should cover the round-trip time. If a message takes 5 ms to process and the broker round trip is 5 ms, a prefetch of 2 or 3 keeps the consumer fully busy. If messages take seconds, a prefetch of 1 costs almost nothing, and fairness is worth more.
Consider also what happens on a crash. All unacknowledged messages are returned to the queue and redelivered. A prefetch of 500 means up to 500 messages may be processed twice, which makes the idempotent consumers from earlier chapters more important.
If your consumer processes messages on a thread pool, set the prefetch to at least the number of worker threads. Otherwise the workers starve. Setting it much higher than the pool size just moves messages from the broker's queue into a hidden in-process queue.
Backpressure at the broker
The consumer cannot protect the broker alone. If producers outrun all consumers, the queue grows. Brokers offer limits:
- Maximum queue length. In RabbitMQ, the
x-max-lengthargument caps the number of messages. The overflow behavior is configurable. The defaultdrop-headdiscards the oldest messages.reject-publishrefuses new ones, and publisher confirms then report a nack to the producer. - Message TTL. Messages that wait too long expire. This suits data that becomes useless when stale, such as a live price quote.
- Resource alarms. When memory or disk crosses a threshold, RabbitMQ blocks publishing connections. Producers appear to hang until the alarm clears.
Each choice decides who loses. Dropping the oldest messages favors fresh data. Rejecting publishes pushes the problem back to the producer, which can then slow down, buffer, or return an error to its own caller. Choose deliberately, because the default may silently discard data.
The following sketch shows a producer that declares a bounded queue and reacts when the broker refuses a message:
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(
queue="bounded-tasks",
durable=True,
arguments={"x-max-length": 1000, "x-overflow": "reject-publish"},
)
ch.confirm_delivery()
try:
ch.basic_publish(
exchange="",
routing_key="bounded-tasks",
body=b"resize image 43",
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent),
mandatory=True,
)
print("accepted")
except pika.exceptions.NackError:
print("queue full, slow down")
except pika.exceptions.UnroutableError:
print("no queue matched")
conn.close()confirm_delivery() turns on publisher confirms, so the broker reports whether it accepted each message. The NackError is the backpressure signal. A real producer would respond with a delay and retry, a bounded local buffer, or an error to its caller.
Note that a queue declared once keeps its arguments. Redeclaring it with different x-max-length values fails with a precondition error, so changing limits means a policy or a new queue.
Backpressure in log-based brokers
Log-based brokers such as Kafka work differently. Consumers pull data at their own pace and track an offset, so a slow consumer does not make the broker hold per-message state. The log is retained by time or size, and a slow consumer simply falls behind, which you see as growing lag. Pull-based consumption is itself a form of backpressure: a consumer that is busy does not ask for more. The risk is that a consumer falls so far behind that retention deletes data it never read.
Detecting trouble
Watch these signals, which the monitoring chapter covers in more detail:
- Queue depth rising over time, not just spiking.
- Unacknowledged count pinned at consumers × prefetch, which means consumers are saturated.
- Age of the oldest message.
- Publisher blocked or nack events.
If unacknowledged messages sit well below consumers × prefetch while the queue is deep, the consumers are not the limit. Look for a slow broker connection or a prefetch that is too small for your latency.
Common mistakes
- Leaving prefetch unlimited, then wondering why one consumer is overloaded while others are idle.
- Using
auto_ack=Trueand expecting prefetch to apply. - Setting a prefetch far above the worker count, hiding a backlog inside the process.
- Letting queues grow without a length limit or TTL, so a stalled consumer eventually takes down the broker.
- Ignoring publisher confirms, so a full queue drops messages without the producer noticing.
- Scaling consumers to fix a slow database. Adding consumers only increases the load on the real bottleneck. Backpressure should reach the producer, not just spread across more workers.
Exercise
A queue has 4 consumers, each with prefetch_count=25. The broker shows 100 unacknowledged messages and the queue depth is rising. The average processing time is 2 seconds per message. (a) What does the unacknowledged count tell you? (b) Would raising the prefetch to 100 raise throughput? (c) What is one change that helps?
Show answer
(a) 100 equals 4 × 25, so every consumer is at its prefetch limit and is saturated. The consumers are the bottleneck. (b) No. Processing takes 2 seconds, so the round trip is negligible and consumers already always have work waiting. A higher prefetch only hides more messages inside consumers and makes crash redelivery larger and distribution less fair. (c) Add consumers or speed up processing, if the downstream system can handle the load. Also add a queue length limit with publisher confirms so producers get a signal when the queue is too deep.
Exercise
Why does prefetch have no effect when a consumer uses auto_ack=True?
Show answer
With automatic acknowledgement the broker treats each message as acknowledged as soon as it sends it, so the count of unacknowledged messages stays at zero and never reaches the limit. The broker keeps sending without pause.