← Back to the chapter · Previous detail · Next detail →
Technical detail · AMQP Delivery: Guarantees and Acknowledgements
One business effect under redelivery
The producer transaction below covers broker publishing only. The payment provider must durably enforce idempotency_key; checking Redis before the action is only a shortcut. Its 86400-second, 24-hour cache expires and does not atomically record the external effect. A crash after payment but before cache write must still be safe at the provider. Use a separate channel for transactional publishing rather than combining this mode with publisher confirms.
# Producer: Transactional publishing
channel.tx_select()
try:
event_id = payment['event_id'] # Stable across publish retries
channel.basic_publish(
exchange='payments',
routing_key='payment.process',
body=json.dumps(payment),
properties=pika.BasicProperties(delivery_mode=2, message_id=event_id)
)
channel.tx_commit()
except Exception:
channel.tx_rollback()
raise
# Consumer: With deduplication
def callback(ch, method, properties, body):
message_id = properties.message_id
# Check if already processed
if redis.exists(f'processed:{message_id}'):
ch.basic_ack(delivery_tag=method.delivery_tag)
return
try:
result = process_payment(body, idempotency_key=message_id)
redis.setex(f'processed:{message_id}', 86400, '1') # 24h TTL
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)