Junior — Middle
Explain the concept of Prefetch and how it is used in RabbitMQ to manage message delivery.
sobes.tech AI
Answer from AI
Prefetch in RabbitMQ is a mechanism that limits the number of messages a consumer can receive from the broker at once before acknowledging their processing.
This helps control the load on the consumer and prevents situations where it receives too many messages and cannot process them all, which could lead to memory overflow or delays.
For example, if you set the prefetch count to 1, the consumer will receive only one message at a time and will not receive a new one until it acknowledges the current one:
var channel = connection.CreateModel();
channel.BasicQos(0, 1, false); // prefetch count = 1
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
// process message
channel.BasicAck(ea.DeliveryTag, false);
};
channel.BasicConsume(queue: "task_queue", autoAck: false, consumer: consumer);
Thus, prefetch helps balance the load and improve the reliability of message processing.