How to Use Manual Ack in RabbitMQ: Simple Guide
In RabbitMQ, use
channel.basic_ack(delivery_tag) to manually acknowledge a message after processing it. Set auto_ack to false when consuming messages to enable manual ack control.Syntax
The manual acknowledgment syntax in RabbitMQ involves calling basic_ack on the channel with the message's delivery_tag. This tag uniquely identifies the message to acknowledge.
channel.basic_ack(delivery_tag): Acknowledge the message with the given delivery tag.auto_ack=False: When consuming, disables automatic ack so you can manually control it.
python
channel.basic_ack(delivery_tag)
Example
This example shows a Python consumer using the pika library that disables automatic acknowledgments and manually acks messages after processing.
python
import pika connection = pika.BlockingConnection(pika.ConnectionParameters('localhost')) channel = connection.channel() channel.queue_declare(queue='test_queue') def callback(ch, method, properties, body): print(f"Received: {body.decode()}") # Process the message here ch.basic_ack(delivery_tag=method.delivery_tag) # Manual ack channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=False) print('Waiting for messages. To exit press CTRL+C') channel.start_consuming()
Output
Waiting for messages. To exit press CTRL+C
Received: Hello World
Common Pitfalls
- Forgetting to set
auto_ack=Falsecauses messages to be auto-acknowledged, making manual ack calls ineffective. - Not calling
basic_ackleads to message re-delivery or queue blocking. - Acking the wrong
delivery_tagcan cause message loss or duplication.
python
## Wrong: auto_ack=True disables manual ack channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=True) ## Right: auto_ack=False enables manual ack channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=False)
Quick Reference
| Action | Code Snippet | Description |
|---|---|---|
| Disable auto ack | auto_ack=False | Allows manual control of message acknowledgment |
| Acknowledge message | channel.basic_ack(delivery_tag) | Confirms message processed successfully |
| Reject message | channel.basic_nack(delivery_tag, requeue=True) | Rejects message and optionally requeues it |
Key Takeaways
Set auto_ack to false to enable manual message acknowledgment.
Call basic_ack with the correct delivery_tag after processing each message.
Manual ack prevents message loss and allows retry on failure.
Forgetting manual ack or using auto_ack=True disables manual control.
Use basic_nack to reject and optionally requeue messages.