← Back to the chapter · Previous detail · Next detail →
Technical detail · AMQP Delivery: Guarantees and Acknowledgements
Compare transient and acknowledged delivery
# Producer: No confirms
channel.basic_publish(
exchange='sensors',
routing_key='temperature',
body='22.5',
properties=pika.BasicProperties(delivery_mode=1) # Transient
)
# Consumer: Auto-acknowledge
channel.basic_consume(
queue='sensor_data',
on_message_callback=callback,
auto_ack=True # Message removed immediately on delivery
)
In the acknowledged example, allocate the job ID once and preserve it across retries. mandatory=True makes an unroutable publish observable; confirm success alone is not proof of a matched binding. Declare the durable queue separately. The requeue branch is illustrative and needs a bounded retry policy.
# Producer: With confirms
channel.confirm_delivery()
try:
channel.basic_publish(
exchange='orders',
routing_key='order.created',
mandatory=True,
body=json.dumps(order),
properties=pika.BasicProperties(
delivery_mode=2, # Persistent
message_id=order['event_id'] # Stable across retries
)
)
except pika.exceptions.UnroutableError:
# Handle unroutable message
retry_or_log(order)
# Consumer: Manual acknowledgment
def callback(ch, method, properties, body):
try:
process_order(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
channel.basic_consume(
queue='orders',
on_message_callback=callback,
auto_ack=False # Manual ACK required
)