0
0
RabbitmqHow-ToBeginner ยท 3 min read

How to Use basic_nack in RabbitMQ for Message Rejection

In RabbitMQ, use basic_nack to reject one or more messages from a consumer. It lets you specify if the rejected messages should be requeued or discarded, helping manage message processing failures.
๐Ÿ“

Syntax

The basic_nack method has three main parameters:

  • delivery_tag: The unique ID of the message to reject.
  • multiple: If true, reject all messages up to the delivery tag.
  • requeue: If true, the message is put back on the queue; if false, it is discarded or dead-lettered.
python
channel.basic_nack(delivery_tag=123, multiple=False, requeue=True)
๐Ÿ’ป

Example

This example shows a Python consumer using basic_nack to reject a message and requeue it for later processing.

python
import pika

connection = pika.BlockingConnection(pika.ConnectionParameters('localhost'))
channel = connection.channel()

channel.queue_declare(queue='task_queue', durable=True)

def callback(ch, method, properties, body):
    print(f"Received {body.decode()}")
    try:
        # Simulate processing failure
        raise Exception("Processing error")
    except Exception as e:
        print(f"Error: {e}, rejecting message")
        ch.basic_nack(delivery_tag=method.delivery_tag, multiple=False, requeue=True)

channel.basic_consume(queue='task_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 Error: Processing error, rejecting message
โš ๏ธ

Common Pitfalls

  • Forgetting to set auto_ack=False disables manual message rejection.
  • Setting requeue=True without fixing the cause can cause infinite message redelivery.
  • Using multiple=True rejects multiple messages, which may cause unexpected message loss if misused.
python
## Wrong: auto_ack=True disables nack
channel.basic_consume(queue='task_queue', on_message_callback=callback, auto_ack=True)

## Right: auto_ack=False enables nack
channel.basic_consume(queue='task_queue', on_message_callback=callback, auto_ack=False)
๐Ÿ“Š

Quick Reference

ParameterDescriptionTypical Values
delivery_tagUnique message ID to rejectInteger from message method
multipleReject multiple messages up to delivery_tagTrue or False
requeuePut message back on queue if TrueTrue or False
โœ…

Key Takeaways

Use basic_nack to reject messages and control if they return to the queue.
Always set auto_ack to false to enable manual message rejection.
Be careful with requeue to avoid infinite redelivery loops.
multiple=True rejects all messages up to the given delivery tag.
basic_nack helps handle message processing failures gracefully.