0
0
RabbitmqHow-ToBeginner ยท 4 min read

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=False when consuming, which disables manual message rejection.
  • Using basic_reject on multiple messages at once is not supported; use basic_nack for batch rejects.
  • Setting requeue=True without 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: true to put message back in queue, false to 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.