Sub topic 8
Scaling with competing consumers
This chapter assumes you know what a producer, a broker, a queue and an acknowledgement are, and that you have seen basic_ack and basic_qos in the earlier chapters. The examples use Python with pika against a local RabbitMQ broker.
The working model
With competing consumers, several consumer processes read from the same queue. The broker gives each message to exactly one of them. The consumers "compete" for messages, and adding a consumer raises the rate at which the queue drains.
The producer does not change. It still publishes to one queue and does not know how many workers exist. The scaling decision moves to the consuming side, where you can start or stop workers at any time.
This is different from publish/subscribe, covered in a later chapter. In publish/subscribe, every subscriber receives its own copy of each message. Here, the consumers on one queue split the messages between them.
A runnable example
Save this as worker.py. It takes a worker name from the command line and simulates two seconds of work per message.
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}] start {body.decode()}", flush=True)
time.sleep(2)
ch.basic_ack(delivery_tag=method.delivery_tag)
print(f"[{worker_id}] done {body.decode()}", flush=True)
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)
print(f"[{worker_id}] waiting", flush=True)
ch.start_consuming()Save this as publish.py. It sends six jobs.
import pika
conn = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
ch = conn.channel()
ch.queue_declare(queue="tasks", durable=True)
for i in range(6):
ch.basic_publish(
exchange="",
routing_key="tasks",
body=f"job-{i}".encode(),
properties=pika.BasicProperties(delivery_mode=pika.DeliveryMode.Persistent),
)
conn.close()Start python worker.py a and python worker.py b in two terminals, then run python publish.py. Each worker handles about three jobs, and the six jobs finish in roughly six seconds instead of twelve. Start a third worker and the time drops to about four seconds.
How the broker divides the work
RabbitMQ dispatches messages to consumers in turn, but it only dispatches to a consumer that still has room under its prefetch limit. Two rules govern this:
- A message that has been delivered but not acknowledged is "unacked". It is invisible to other consumers.
- A consumer receives a new message only while its unacked count is below
prefetch_count.
If a worker's connection closes before it acknowledges, the broker puts its unacked messages back on the queue. Another worker then picks them up, and the redelivered message is flagged (method.redelivered is True). This is why crashes do not lose work. It is also why the same message can be processed twice: the first worker may have finished the side effect just before it died.
Choosing the number of consumers
A first estimate comes from the arrival rate and the time one message takes to process:
workers needed ≈ arrival rate × average processing time
For example, 50 messages per second at 0.2 seconds each needs about 10 busy workers. Add headroom of 30 to 50 percent so bursts do not build a backlog. If the arrival rate is higher than the capacity of all workers, the queue grows without bound. Monitoring queue depth, which a later chapter covers, is how you notice this.
Workers can be processes, threads, containers or serverless functions. In Python, CPU-bound work needs separate processes because of the global interpreter lock. I/O-bound work, such as calling an HTTP API, can run well in threads or async tasks inside one process.
Prefetch and uneven work
Prefetch controls how much a single worker hoards. The effect is easiest to see with jobs of different lengths.
| Setting | Behavior | Typical use |
|---|---|---|
| `prefetch_count=1` | A worker gets one message at a time. Slow jobs never block waiting messages. | Long or highly variable jobs |
| `prefetch_count=10` to `50` | Fewer network round trips and higher throughput. A slow message can delay others held by the same worker. | Short, uniform jobs |
| No limit | One fast consumer can pull the whole queue into memory while others sit idle. | Avoid |
Suppose a worker prefetches 20 messages and the first one takes a minute. The other 19 wait behind it, even if another worker is idle. Lowering the prefetch count fixes this, at the cost of more round trips. The next chapter treats prefetch as backpressure in more detail.
What breaks when you add consumers
Adding workers is simple. The problems come from what the workers share.
Ordering is lost
With one consumer, messages are handled in queue order. With several, message 2 can finish before message 1, because the workers run in parallel and jobs take different times. A redelivered message also returns to the queue and may be handled after later messages. If order matters for related messages, such as all updates to one account, competing consumers on a plain queue will not preserve it. The ordering chapter covers the fixes, including partitioning by key.
Duplicates become more likely
More workers mean more processes that can crash, time out, or lose a connection mid-job. Every one of those events can trigger redelivery. Treat duplicates as normal and make the handler idempotent, as in the earlier chapter on idempotent consumers. Workers that "check then act" on shared data can also race with each other, so use a database constraint or a transaction rather than an in-memory check.
The bottleneck moves downstream
Ten workers writing to one database can overload it, and the queue then hides the problem until timeouts begin. Scale workers against the capacity of the slowest dependency. A connection pool, a rate limit, or a concurrency cap per worker keeps the total load bounded.
A poison message hits every worker in turn
A message that always fails and is requeued will bounce between workers forever and consume capacity on all of them. Reject it with requeue=False and route it to a dead-letter queue, as covered in the retries chapter.
Shared local state
Workers must not depend on memory or local disk that other workers cannot see. A worker that caches a result in a local dictionary will produce different behavior from its peers. Keep shared state in a database or cache.
Scaling up and down safely
When you stop a worker, let it finish its current message. On SIGTERM, call ch.stop_consuming() and exit after the current acknowledgement. If you kill it instead, the broker requeues the message, which is safe but wastes the partial work and creates a duplicate.
Many teams scale the number of workers from queue depth or from the age of the oldest message. Two cautions apply:
- Add a cooldown between changes. Otherwise the worker count oscillates as the queue empties and refills.
- Set a maximum. Past some point, more workers add load to a database or API without adding throughput.
Scaling out has a limit set by the broker design. In a RabbitMQ classic queue, many consumers can read one queue. In a log-based broker such as Kafka, parallelism within a consumer group is capped by the number of partitions. A group with 6 partitions has at most 6 active consumers, and any extra consumers sit idle. The log-based brokers chapter returns to this.
Exercise
A queue receives 40 messages per second. Each message takes an average of 0.25 seconds to process. Your workers use prefetch_count=50, and one job in a hundred takes about 30 seconds. Roughly how many workers do you need, and what problem might the prefetch setting cause?
Show answer
The base need is 40 × 0.25 = 10 busy workers, so plan for about 13 to 15 with headroom. With a prefetch of 50, a worker that receives a 30-second job keeps up to 49 other messages reserved while it works. Those messages cannot go to idle workers, so latency rises for them. Lower the prefetch count, for example to 1 to 5, so slow jobs hold back fewer messages.
Exercise
Two workers read from one queue. Worker A receives message 7, does the work, and crashes before sending the acknowledgement. What happens to message 7, and what must the handler be able to cope with?
Show answer
The broker detects the closed connection and requeues message 7, marked as redelivered. Worker B receives it and processes it again. The handler must be idempotent, because the first run's side effects may already have happened.