How RabbitMQ comes to know whether the prefetch count limit has been reached?

Parag Patil
2 min readMar 17, 2023

In continuation with my previous attempt to answer the question

Can RabbitMQ queues publish records in batches?

Let me further elaborate on how RabbitMQ tracks the consumer’s prefetch count.

RabbitMQ keeps track of the number of unacknowledged messages for each consumer to determine whether the prefetch count limit has been reached. When a consumer processes a message, it sends an acknowledgment back to RabbitMQ. This allows RabbitMQ to update the number of unacknowledged messages for that consumer.

Here’s an outline of how this process works:

  1. Set prefetch count: When creating a consumer, you can set a prefetch count limit using channel.basicQos(prefetchCount). This determines the maximum number of unacknowledged messages that can be delivered to the consumer at a time.
int prefetchCount = 10;
channel.basicQos(prefetchCount);

2. Deliver messages: RabbitMQ delivers messages to the consumer. Each message is associated with a delivery tag, which is a unique identifier within a channel. When a consumer receives a message, RabbitMQ increments the consumer’s unacknowledged message count.

3. Process and acknowledge messages: After processing a message, the consumer sends an acknowledgment to RabbitMQ using the channel.basicAck(deliveryTag, false) method. This tells RabbitMQ that the message has been processed and can be removed from the queue. When RabbitMQ receives an acknowledgment, it decrements the consumer's unacknowledged message count.

4. Check unacknowledged message count: RabbitMQ constantly checks the number of unacknowledged messages for each consumer. If the number of unacknowledged messages reaches the prefetch count limit, RabbitMQ will not deliver more messages to that consumer until it receives acknowledgments for some of the messages, causing the unacknowledged message count to fall below the prefetch count limit.

By managing the unacknowledged message count, RabbitMQ ensures that the prefetch count limit is respected, preventing consumers from becoming overwhelmed with too many messages to process at once.

--

--