Sub topic 8
Scaling with competing consumers
This chapter assumes you know what a producer, a broker, a queue, and an acknowledgement are from the earlier chapters. The examples use Python and RabbitMQ with the pika library.
The problem: one consumer is too slow
A single consumer handles messages one at a time. If producers add 100 jobs per second and the consumer finishes 20 per second, the queue grows without limit. Making the consumer faster only helps up to a point. The usual fix is to run more consumers.
The competing consumers pattern
In this pattern, several consumers read from the same queue. The broker gives each message to exactly one of them, so the consumers compete for work. Adding a consumer adds capacity, and removing one lowers it. Neither change touches the producer.
This differs from publish/subscribe, covered later. In pub/sub every subscriber gets a copy of each message. Here the consumers split the messages between them.
Running several workers
The worker below reads from the tasks queue. Start it in two or three terminals to see messages divided among the copies.
import sys
import time
import pika
worker_id = sys.argv[1] if len(sys.argv) > 1 else "w1"
def handle(ch, method, properties, body):
print(f"[{worker_id}] handling {body!r}")
time.sleep(1) # simulate slow work
ch.basic_ack(delivery_tag=method.delivery_tag)
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
ch.basic_qos(prefetch_count=1)
ch.basic_consume(queue="tasks", on_message_callback=handle, auto_ack=False)
ch.start_consuming()Run it as python worker.py w1, python worker.py w2, and so on. Then publish several messages with the producer from the earlier chapter. Each message is printed by only one worker.
Why prefetch matters here
RabbitMQ pushes messages to consumers. Without a limit, it sends a large batch to each consumer as soon as the consumer connects. A fast consumer then finishes its batch and sits idle while a slow one still holds many unprocessed messages.
prefetch_count=1 lets each consumer hold one unacknowledged message at a time. A new message goes to whichever consumer is free. This balances load when jobs vary in duration. The cost is an extra network round trip per message. For short jobs, a larger value such as 10 or 50 gives better throughput.
What changes when you scale out
Adding consumers is not free of side effects. Check these points first.
- Ordering is lost. Two consumers can finish messages in a different order than the queue delivered them. If order matters, you need a different design. The ordering chapter covers this.
- Duplicates are still possible. If a consumer dies before it acknowledges, the broker redelivers the message to another consumer. Keep your consumers idempotent.
- Shared resources become the bottleneck. Ten consumers writing to one database can overload it. Scaling consumers only moves the limit.
- Consumers must be stateless. Any consumer may receive any message, so no message can depend on state held in one process.
Common mistakes
- Leaving prefetch unset, which gives uneven load and lets one consumer hoard messages.
- Setting prefetch too high with slow jobs, so messages wait behind a busy consumer while others are idle.
- Adding consumers when the real limit is a downstream service.
- Using
auto_ack=True, which loses a message if the consumer crashes mid-job.
Exercise
Three consumers share one queue with prefetch_count=1. Consumer 2 crashes while handling a message and had not yet acknowledged it. What happens to that message, and what must the consumers be able to tolerate?
Show answer
The broker detects the closed connection and requeues the unacknowledged message, then delivers it to another available consumer. Because the first attempt may have partly completed, consumers must tolerate duplicate processing, so they should be idempotent.