Microservices

RabbitMQ Events in Python: Durable Queues, Publisher Confirms and Dead-Lettering

When services call each other synchronously over HTTP, a slow or failing service holds up everything that depends on it. Publishing events through a message broker removes that runtime dependency. The order service records "order created" and moves on, and the notification, analytics and fulfilment services each process the event in their own time, even if one of them is down for an hour.

That resilience isn't automatic. With the wrong queue settings, messages vanish while a consumer is offline, a single bad message loops forever, or the broker loses messages it never confirmed. This guide builds a producer and consumer in Python with RabbitMQ and pika, and makes each of those guarantees explicit.

When Asynchronous Events Fit

Events work well for side effects that don't need to finish before the user gets a response: sending emails, updating search indexes, recording analytics, starting fulfilment. They're a poor fit when the caller needs an answer right now, such as checking stock before confirming an order or authorizing a payment. Those remain synchronous calls, protected with timeouts and retries.

Moving to events also means accepting eventual consistency: for a short time, the notification service may not know about an order the order service has already saved. Design the user experience around that delay instead of hiding it.

RabbitMQ in One Paragraph

Producers publish messages to an exchange. The exchange routes copies to every queue bound to it that matches. Consumers read from queues and acknowledge each message once they've handled it. The important consequence: if no queue is bound when a message is published, the message goes nowhere. Queues, not exchanges, are where messages wait.

Step 1: Run RabbitMQ

Bash
docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:4-management
pip install pika

The management UI at http://localhost:15672 (user and password guest) shows exchanges, queues and message counts, which is useful for checking each step below.

Step 2: Declare the Topology Once

Both services must agree on the exchange, queue and bindings. Keep that in one function, and make everything durable so it survives a broker restart:

Python
# topology.py
import pika

EXCHANGE = "orders"            # topic exchange: routing keys like "order.created"
QUEUE = "notifications.order-events"
DLX = "orders.dlx"
DLQ = "notifications.order-events.dead"


def declare(channel: pika.adapters.blocking_connection.BlockingChannel) -> None:
    channel.exchange_declare(EXCHANGE, exchange_type="topic", durable=True)

    # Dead-letter exchange and queue: rejected messages end up here for inspection.
    channel.exchange_declare(DLX, exchange_type="fanout", durable=True)
    channel.queue_declare(DLQ, durable=True, arguments={"x-queue-type": "quorum"})
    channel.queue_bind(DLQ, DLX)

    # The service's own queue: named, durable, replicated (quorum), with a DLX.
    channel.queue_declare(
        QUEUE,
        durable=True,
        arguments={
            "x-queue-type": "quorum",
            "x-dead-letter-exchange": DLX,
            "x-delivery-limit": 5,   # after 5 redeliveries, dead-letter instead of looping
        },
    )
    channel.queue_bind(QUEUE, EXCHANGE, routing_key="order.*")

Three choices here prevent the most common failures:

  • A named, durable queue per consuming service. Messages accumulate in it while the service is down or being deployed. An exclusive, auto-named queue (queue_declare(queue='', exclusive=True), common in tutorials) is deleted when its consumer disconnects, so every event published in the meantime is lost.
  • A quorum queue. Quorum queues replicate messages across a RabbitMQ cluster and track redeliveries, which enables x-delivery-limit. They're the recommended queue type for data you can't afford to lose.
  • A dead-letter exchange. Messages that are rejected, or exceed the delivery limit, move to a separate queue where someone can inspect them, instead of being dropped or retried forever.

If another service later wants order events, it declares its own queue bound to the same exchange and receives its own copy of each message.

Step 3: Publish with Confirms

Python
# order_service.py
import json
import uuid
from datetime import datetime, timezone

import pika

import topology

connection = pika.BlockingConnection(pika.ConnectionParameters("localhost"))
channel = connection.channel()
topology.declare(channel)
channel.confirm_delivery()  # basic_publish now waits for the broker to accept the message


def publish_order_created(order: dict) -> None:
    event = {
        "event_id": str(uuid.uuid4()),
        "event_type": "order.created",
        "occurred_at": datetime.now(timezone.utc).isoformat(),
        "data": order,
    }
    channel.basic_publish(
        exchange=topology.EXCHANGE,
        routing_key="order.created",
        body=json.dumps(event),
        properties=pika.BasicProperties(
            content_type="application/json",
            delivery_mode=pika.DeliveryMode.Persistent,
            message_id=event["event_id"],
        ),
        mandatory=True,  # raise if no queue is bound for this routing key
    )


publish_order_created({"order_id": "ORD-001", "customer_id": "CUST-456", "total": "150.75"})
connection.close()

delivery_mode=Persistent asks the broker to write the message to disk, but without confirms the producer never learns whether that happened. With confirm_delivery(), basic_publish raises an exception if the broker rejects the message, and with mandatory=True it raises if nothing would receive it. Both are failures you want to know about.

⚠️ Common mistake: Saving the order to the database and then publishing the event as two separate steps. If the process crashes between them, the order exists but no event was ever sent. Or the publish succeeds and the database transaction then rolls back, announcing an order that doesn't exist. The standard fix is the transactional outbox: write the event to an outbox table in the same transaction as the order, and have a separate relay process publish rows from that table and mark them as sent.

Step 4: Consume with Manual Acks

Python
# notification_service.py
import json

import pika

import topology


class PermanentError(Exception):
    """Retrying won't help (bad data, unknown customer)."""


def send_notification(event: dict) -> None:
    ...  # call the email/SMS provider


def already_processed(event_id: str) -> bool:
    ...  # look up event_id in this service's processed_events table


def mark_processed(event_id: str) -> None:
    ...  # insert event_id (unique constraint) in the same transaction as any DB changes


def on_message(channel, method, properties, body):
    try:
        event = json.loads(body)
        if not already_processed(event["event_id"]):
            send_notification(event)
            mark_processed(event["event_id"])
        channel.basic_ack(method.delivery_tag)
    except (json.JSONDecodeError, KeyError, PermanentError):
        # Bad message: send straight to the dead-letter queue.
        channel.basic_reject(method.delivery_tag, requeue=False)
    except Exception:
        # Possibly transient (provider timeout): requeue. The quorum queue's
        # delivery limit dead-letters it after 5 attempts.
        channel.basic_reject(method.delivery_tag, requeue=True)


connection = pika.BlockingConnection(pika.ConnectionParameters("localhost", heartbeat=60))
channel = connection.channel()
topology.declare(channel)
channel.basic_qos(prefetch_count=10)  # at most 10 unacknowledged messages at a time
channel.basic_consume(topology.QUEUE, on_message_callback=on_message)
channel.start_consuming()

Now try the failure case that breaks the naive version. Stop the consumer, run the producer a few times, and look at the management UI: the messages sit in notifications.order-events. Start the consumer again and it processes all of them.

A few details in the consumer:

  • Ack after the work, not before. If the consumer crashes mid-message, RabbitMQ redelivers it.
  • Distinguish permanent from transient failures. Requeueing a malformed message just makes it fail again immediately. Reject it without requeue so it goes to the dead-letter queue.
  • prefetch_count limits how many messages RabbitMQ pushes to a consumer before they're acknowledged. Without it, one consumer can receive the entire backlog while other instances sit idle.
  • Long-running work blocks heartbeats in BlockingConnection. If handling one message can take longer than the heartbeat interval, run the work in a thread and acknowledge with connection.add_callback_threadsafe, or use an asynchronous client such as aio-pika.

Step 5: Make Consumers Idempotent

RabbitMQ delivers messages at least once. After a crash, a network blip or a requeue, the same event can arrive twice. The consumer above records each event_id it has handled and skips duplicates. The record and the work's own database changes should be committed in the same transaction, so a crash can't leave one without the other.

Side effects outside your database, such as the email itself, can still happen twice if the process dies after sending and before recording. Where the provider supports it, pass the event_id as an idempotency key so the provider drops the duplicate.

💡 Tip: Treat event schemas as public APIs. Add fields freely, but never remove or rename one that consumers may depend on. When a breaking change is unavoidable, publish a new event type (order.created.v2) alongside the old one until every consumer has moved.

Operating It

Watch these in the management UI or through the Prometheus plugin (rabbitmq_prometheus):

  • Queue depth and age of the oldest message: steady growth means consumers can't keep up, or have stopped.
  • Messages in dead-letter queues: each one is a failure someone should look at. Alert when the count is above zero.
  • Unacknowledged messages: a high number that never drops usually means a stuck consumer.

Summary

  1. Give each consuming service its own named, durable (quorum) queue, so events wait while the service is down.
  2. Publish with confirms and mandatory, and use a transactional outbox so the database and the event can't disagree.
  3. Ack after processing, reject bad messages without requeue, and cap redeliveries with a dead-letter exchange and a delivery limit.
  4. Make consumers idempotent using the event ID, because delivery is at least once.
  5. Monitor queue depth and dead-letter queues.
Advertisement