Distributed Message Service RabbitMQ

Prefetching Value

2024-06-27 06:40:33

Application Scenario

The so-called message prefetching mechanism defines the maximum number of unacknowledged messages allowed by a consumer on a channel.

Once the number of unacknowledged messages reaches the set prefetch value, RabbitMQ stops delivering more messages unless at least one of the outstanding messages is acknowledged.

How to set the right prefetch value

Generally, increasing prefetching will improve the speed of delivering messages to consumers. Although the auto response transmission rate is optimal, the number of delivered but unprocessed messages also increases in this case, thus increasing the consumer's RAM consumption. Be careful when using automatic or manual ack modes with unlimited preprocessing. The consumer consumes a large number of messages, if not acknowledged, it will cause the memory consumption of the node connected to the consumer to increase, so finding the appropriate prevalue value is a process of trial and error. This value varies for different loads, with values in the range of 100 to 300 usually providing the best throughput without too much risk to the consumer.

A prefetch value of 1 is the most conservative. Of course, this will make throughput very low, especially if the delay of the consumer connection is very high, and in the environment where the consumer connection wait time is relatively long. For most applications, a slightly higher value would be optimal.

Setting prefetch value

The following is the Java sample code for setting prefetch values


ConnectionFactory factory = new ConnectionFactory();

Connection connection = factory.newConnection();

Channel channel = connection.createChannel();

channel.basicQos(20, false);


00g8GDt3ZiFO