How to Use basic_reject in RabbitMQ: Syntax and Examples
In RabbitMQ,
basic_reject is used to reject a single message received by a consumer. You call it with the message's delivery tag and a boolean to decide if the message should be requeued or discarded.Syntax
The basic_reject method requires two parameters: the delivery tag which identifies the message to reject, and requeue, a boolean that decides if the message should be put back in the queue (true) or discarded/dead-lettered (false).
python
channel.basic_reject(delivery_tag=method.delivery_tag, requeue=True)Example
This example shows a Python consumer using the pika library that rejects a message without requeuing it, so the message is discarded or dead-lettered if configured.
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()}") # Reject the message and do not requeue ch.basic_reject(delivery_tag=method.delivery_tag, requeue=False) channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=False) print('Waiting for messages...') channel.start_consuming()
Output
Waiting for messages...
Received: Hello World
Common Pitfalls
- Forgetting to set
auto_ack=Falsewhen consuming, which disables manual message rejection. - Using
basic_rejecton multiple messages at once is not supported; usebasic_nackfor batch rejects. - Setting
requeue=Truewithout handling can cause message redelivery loops.
python
## Wrong: auto_ack=True disables rejection channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=True) ## Right: auto_ack=False to enable rejection channel.basic_consume(queue='test_queue', on_message_callback=callback, auto_ack=False)
Quick Reference
basic_reject parameters:
delivery_tag: Unique ID of the message to reject.requeue:trueto put message back in queue,falseto discard.
Note: Use basic_nack for rejecting multiple messages.
Key Takeaways
Use basic_reject to reject a single message by its delivery tag.
Set requeue to true to put the message back or false to discard it.
Always consume with auto_ack set to false to enable manual rejection.
For batch message rejection, use basic_nack instead of basic_reject.
Avoid requeue loops by handling rejected messages carefully.