RabbitMQ
Batch Processing
Message Consumption
Acknowledgment
Data Management

RabbitMQ: consume messages in batches and ack them all at once

Codemia Knowledge Hub ·

To consume RabbitMQ messages in batches and acknowledge them together, fetch messages with manual acknowledgment, keep their delivery tags, and after the batch is processed call basic_ack with the highest delivery tag and multiple=True. That single ack confirms every message up to and including that tag.

How acknowledgments work

Producers send messages to a queue and consumers read them asynchronously. Normally each message is processed on its own and an acknowledgment (ack) tells RabbitMQ it was handled. If a consumer fails before acking, the message is redelivered, so nothing is lost.

Processing one message at a time suits many workloads, but in high-throughput systems it can become a bottleneck. With batching, the consumer pulls several messages, processes them together, and sends one acknowledgment for the whole batch. The benefits:

  • Reduced Network Overhead: Less frequent acknowledgments reduce network traffic.
  • Higher Throughput: More messages are processed in the same amount of time.
  • Less Frequent Context Switching: Improves CPU usage efficiency in multi-threaded scenarios.

Batch consume and ack with pika

This simplified example uses pika, a Python RabbitMQ client, and assumes a queue that already has messages published to it. Install pika:

bash
pip install pika

Then consume a batch:

python
1import pika
2from pika import connection
3
4# Establish connection and channel
5connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
6channel = connection.channel()
7
8# Ensure the queue exists
9channel.queue_declare(queue='my_queue')
10
11def batch_consume():
12    method_frame, header_frame, body = channel.basic_get(queue = 'my_queue', auto_ack = False)
13    if method_frame:
14        print("Received: %s" % body)
15        return method_frame.delivery_tag
16    else:
17        print("No messages returned")
18        return None
19
20# Batch processing
21batch_size = 10
22delivery_tags = []
23while len(delivery_tags) < batch_size:
24    delivery_tag = batch_consume()
25    if delivery_tag:
26        delivery_tags.append(delivery_tag)
27
28# Acknowledge all messages in the batch
29if delivery_tags:
30    channel.basic_ack(delivery_tag=max(delivery_tags), multiple=True)
31
32# Close the connection
33connection.close()

basic_get fetches one message at a time with auto_ack = False. The script collects delivery tags until it has 10, then sends a single basic_ack. The multiple=True parameter means "acknowledge all messages up to and including the one with this delivery tag." Note that the loop keeps polling until it has a full batch, so on an empty queue it prints "No messages returned" repeatedly.

Choosing a batch size and handling failures

FactorDescriptionImpact
Batch sizeLarger sizes reduce how often you ack, but a failure before the ack means more messages are redelivered and processed again.Balance needed based on risk tolerance and throughput requirements.
Message processing timeLonger processing times might delay acks, affecting message redelivery times if unacknowledged messages are assumed lost.Monitor and adjust batch sizes accordingly.
Error handlingHandling failures while processing batches can be complex as it may require re-consuming the entire batch.Implement robust error recovery mechanisms.

Batching pays off most when the work can be parallelized or is a bulk operation, such as bulk inserts or updates in a database where several messages need to succeed or fail together.


Course
Beginner
27 lessons
10 hours
System Design Fundamentals

Build a strong foundation in designing scalable, reliable distributed systems.

View the course
System Design practice on Codemia

Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.

Practice system design