RabbitMQ Queue Design Template
Template for documenting RabbitMQ queue, exchange, and binding design: exchange types, queue properties, binding rules, dead letter handling, TTL policies, and capacity planning with code examples.
Overview
Documenting a RabbitMQ topology is easy to skip and painful to reconstruct later — nobody remembers why the payments queue has a 24h TTL until the incident postmortem asks. This template captures the decisions that matter for one service: which exchange type routes the traffic, what the queue tolerates, how failures dead-letter, and how much headroom the setup actually has. Fill it in per service and keep it next to the infrastructure code.
1. Exchange Design
Published messages hit an exchange first; the exchange decides which queues get copies. Choose the type before naming anything, because retrofitting direct-routing semantics onto a fanout isn’t a thing.
1.1 Exchange Type Selection
Exchange type | Use case | Routing key
──────────────┼────────────────────────────────────┼──────────────────
direct | Point-to-point, exact match | Exact string match
topic | Pattern-based routing | Wildcard match (* and #)
fanout | Broadcast to all queues | Ignored
headers | Route by message headers | Header key-value match
1.2 Exchange Naming Convention
<environment>.<domain>.<purpose>.<exchange-type>
Examples:
prod.orders.order-created.direct
prod.notifications.broadcast.fanout
prod.payments.payment-events.topic
staging.users.user-updates.topic
1.3 Exchange Declaration
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host='rabbitmq-prod',
port=5672,
credentials=pika.PlainCredentials(
os.environ['RABBITMQ_USER'],
os.environ['RABBITMQ_PASSWORD'], # never hardcode credentials
),
heartbeat=30,
blocked_connection_timeout=300,
)
)
channel = connection.channel()
# Declare exchange with durability and persistence
channel.exchange_declare(
exchange='prod.orders.order-created.direct',
exchange_type='direct',
durable=True, # survive broker restart
auto_delete=False, # don't delete when queues disconnect
internal=False, # accept publishes from clients
)
2. Queue Design
Messages sit in a queue until some consumer acknowledges the work. Two questions drive every property below: do the messages survive a restart, and what stops one queue from eating all of the node’s memory.
2.1 Queue Properties
Property | Recommended | Description
──────────────────┼─────────────┼──────────────────────────────────
durable | True # Survive broker restart
auto_delete | False # Don't delete when consumers disconnect
exclusive | False # Allow multiple consumers
max_length | Set per Q # Prevent unbounded growth
message_ttl | Set per Q # Expire stale messages
dead_letter_exchange| Set per Q # Route failed messages to DLX
2.2 Queue Naming Convention
<environment>.<domain>.<consumer-service>.<purpose>
Examples:
prod.orders.payment-service.process-payment
prod.notifications.email-service.send-email
prod.payments.audit-service.log-transaction
staging.users.analytics-service.track-signup
2.3 Queue Declaration
# Standard queue with DLX and TTL
args = {
'x-message-ttl': 86400000, # 24 hours in ms
'x-dead-letter-exchange': 'prod.orders.dlx.direct',
'x-dead-letter-routing-key': 'order-payment-failed',
'x-max-priority': 10, # Priority support
'x-max-length': 50000, # Max messages in queue
'x-overflow': 'reject-publish', # Reject new messages when full
}
channel.queue_declare(
queue='prod.orders.payment-service.process-payment',
durable=True,
arguments=args,
)
3. Binding Design
The binding is what actually moves messages from exchange to queue. Too broad and a targeted queue becomes a firehose; too narrow and messages disappear without an error anywhere.
3.1 Binding Rules
# Direct exchange — exact routing key match
channel.queue_bind(
exchange='prod.orders.order-created.direct',
queue='prod.orders.payment-service.process-payment',
routing_key='order.payment.required',
)
# Topic exchange — wildcard routing key match
channel.queue_bind(
exchange='prod.payments.payment-events.topic',
queue='prod.payments.audit-service.log-transaction',
routing_key='payment.*.completed', # matches payment.usd.completed, payment.eur.completed
)
# Fanout exchange — routing key ignored
channel.queue_bind(
exchange='prod.notifications.broadcast.fanout',
queue='prod.notifications.email-service.send-email',
routing_key='', # ignored for fanout
)
3.2 Binding Patterns for Topic Exchanges
Pattern | Matches
─────────────────────┼──────────────────────────────────────────
order.*.created | order.usd.created, order.eur.created
order.# # order.created, order.usd.created, order.usd.created.v2
#.error | any.error, payment.error, orders.error
*.*.completed | order.usd.completed, payment.eur.completed
4. Dead Letter Configuration
Poison messages have two bad endings: retry loops that never stop, or silent drops nobody investigates. The DLX is the third ending — failures parked in a queue a human can inspect and replay.
4.1 Dead Letter Exchange (DLX)
# Declare dead letter exchange
channel.exchange_declare(
exchange='prod.orders.dlx.direct',
exchange_type='direct',
durable=True,
)
# Declare dead letter queue
dlq_args = {
'x-message-ttl': 604800000, # 7 days retention
}
channel.queue_declare(
queue='prod.orders.dlq.failed-messages',
durable=True,
arguments=dlq_args,
)
# Bind DLQ to DLX
channel.queue_bind(
exchange='prod.orders.dlx.direct',
queue='prod.orders.dlq.failed-messages',
routing_key='order-payment-failed',
)
4.2 Dead Letter Triggers
Trigger | Configuration | Behavior
─────────────────────┼──────────────────────────────┼──────────────────────
Message TTL expired | x-message-ttl on queue | Message moves to DLX
Queue length exceeded| x-max-length on queue | Oldest message to DLX
Consumer rejection | basic_reject(requeue=False) | Message moves to DLX
Consumer nack | basic_nack(requeue=False) | Message moves to DLX
5. Consumer Configuration
The consumer side decides how work gets pulled, retried, and acknowledged — and the defaults (auto_ack, unbounded prefetch) are exactly what you want in a demo and not in production.
5.1 QoS (Quality of Service)
# Set prefetch count — limit unacknowledged messages
channel.basic_qos(
prefetch_count=10, # Process 10 messages at a time
prefetch_global=False, # Per-consumer, not per-channel
)
# Start consuming with manual acknowledgment
channel.basic_consume(
queue='prod.orders.payment-service.process-payment',
on_message_callback=process_message,
auto_ack=False, # Manual acknowledgment required
)
5.2 Message Processing
MAX_RETRIES = 3
def process_message(channel, method, properties, body):
try:
message = json.loads(body)
result = handle_payment(message)
if result.success:
channel.basic_ack(delivery_tag=method.delivery_tag)
else:
retry_or_dead_letter(channel, method, properties, body)
except Exception as e:
logger.error(f"Failed to process message: {e}")
channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
def retry_or_dead_letter(channel, method, properties, body):
# headers can be None in pika — guard before reading
headers = dict(properties.headers or {})
retry_count = headers.get('x-retry-count', 0)
if retry_count >= MAX_RETRIES:
# reject without requeue — the DLX catches it
channel.basic_reject(delivery_tag=method.delivery_tag, requeue=False)
return
# basic_reject(requeue=True) returns the original message unchanged,
# so a retry counter must be republished, not requeued.
# republish where the message came from so bindings route it again
headers['x-retry-count'] = retry_count + 1
channel.basic_publish(
exchange=method.exchange,
routing_key=method.routing_key,
body=body,
properties=pika.BasicProperties(headers=headers),
)
channel.basic_ack(delivery_tag=method.delivery_tag)
6. Capacity Planning
Size for the peak, always — a queue that grows faster than consumers drain it eventually hits x-max-length or trips a memory alarm, and RabbitMQ’s answer to both is refusing publishes at the worst possible moment.
6.1 Sizing Worksheet
Metric | Value | Notes
──────────────────────────┼──────────────┼──────────────────────
Expected msg/s (peak) | 500 | Peak throughput
Avg message size | 2 KB | Payload size
Max queue depth | 10,000 # Max messages before backpressure
Consumer count | 5 # Parallel consumers
Consumer throughput (msg/s)| 150 # Per consumer
Total consumer throughput | 750 # 5 x 150
Headroom | 50% # 750 vs 500 peak = 50% headroom
Memory per message | 2.5 KB # Message + RabbitMQ overhead
Max queue memory | 25 MB # 10,000 x 2.5 KB
6.2 Resource Limits
Resource | Limit | Action when exceeded
──────────────────┼────────────────────┼──────────────────────────────
Queue memory | 2 GB per queue # Enable x-max-length or TTL
Total queues | 100 per node # Split across nodes
File descriptors | 10,000 per node # Monitor with rabbitmqctl
Disk space | 50% free minimum # RabbitMQ disk alarm at 50%
Erlang processes | 1M per node # Monitor via management API
Troubleshooting
- Messages are lost on restart: durable queues alone aren’t enough — also publish with
delivery_mode=2and confirm the publish (confirm_delivery), and ack only after processing. - Consumers lag behind the producer: RabbitMQ has no partitions to add — scale horizontally with more consumer instances on the same queue (competing consumers), and tune
prefetch_countso work is spread evenly. - Duplicate messages: RabbitMQ only promises at-least-once delivery — duplicates will happen. Treat them as normal: make consumers idempotent (deduplicate on a message ID or a natural key). See message idempotency.
- Ordering is wrong after scaling consumers: order is only guaranteed within one queue consumed by one consumer. If strict ordering matters, keep a single consumer, use
x-single-active-consumer, or route related messages to the same queue via a consistent-hash exchange. - Queue depth grows while consumers look idle: inspect
rabbitmqctl list_queues name messages_ready messages_unacknowledged. Highunacknowledgedwith low throughput means slow processing or a low prefetch; growingreadymeans consumers are down, unresponsive, or the publisher outpaces the slowest stage. - Messages landing in the DLQ and nobody notices: alert on DLQ depth — a dead-letter queue that grows unmonitored is where production errors go to disappear.
See Also
- Complete Guide to RabbitMQ Architecture
- Message Queues — RabbitMQ, Kafka, and SQS detailed analysis
- Event Streaming with Apache Kafka and Node.js
- Message Processing Idempotency
- Task Queues and RPC with RabbitMQ and AMQP
- RabbitMQ dead-lettering documentation — official DLX and delivery-limit semantics.
- RabbitMQ TTL documentation — message and queue TTL reference.
- CloudAMQP — RabbitMQ best practices — production guidance on queue length, prefetch, and durability.
Frequently Asked Questions
When should I use a direct vs topic exchange?
Direct when your routing keys are fixed strings you control (order.payment.required); topic when callers need patterns (payment.*.completed covers a whole family of keys). A direct exchange is marginally faster — the router does a hash lookup — but pick on semantics, not speed. If you're unsure, direct first; adding wildcards later is a binding change, not a rewrite.
How do I handle poison messages in RabbitMQ?
Configure a dead letter exchange on the queue. When a consumer rejects a message with requeue=False, RabbitMQ routes it to the DLX. Set up a DLQ to store failed messages for inspection. Implement a retry counter in message headers — reject with requeue=True for retries under the limit, and requeue=False after max retries. Monitor DLQ depth and alert when messages accumulate.
What prefetch count should I use?
Start with 10 for most workloads. For slow CPU-bound handlers keep it low (1-5) so work spreads fairly; for fast I/O-bound handlers 50-100 keeps throughput up. Set it too high and one consumer hoards the queue while the rest idle. Watch consumer lag and adjust. Use prefetch_global=False for per-consumer limits.
How do I ensure messages survive broker restarts?
Declare exchanges and queues with durable=True. Publish messages with delivery_mode=2 (persistent). Use confirmation mode on the channel to ensure the broker has accepted the message. Persistence costs latency — the broker fsyncs before confirming — so don't persist messages you can afford to lose. For truly critical ones, publish with mandatory=True and handle basic.return for unroutable messages.
Should I use RabbitMQ or Kafka for my use case?
Use RabbitMQ for point-to-point communication, request-reply patterns, work queues with complex routing, and when you need per-message acknowledgment. Use Kafka for event streaming, high-throughput log aggregation, replay of historical events, and when consumers need to read at their own pace. RabbitMQ suits transactional messaging; Kafka suits event sourcing and analytics pipelines.
Related Resources
Kafka Topic Naming Convention Template
Template for standardizing Kafka topic names across teams: naming pattern, environment prefixes, event suffixes, partition and retention rules.
DocMessage Schema Evolution Policy (Avro, Protobuf, JSON)
A reusable policy for evolving message schemas safely in event-driven systems: compatibility rules, schema registry requirements, versioning, breaking change procedure, migration checklist, and CI enforcement with Avro, Protobuf, and JSON Schema examples.
DocDead Letter Queue Runbook
Operational runbook for triaging, fixing, and replaying dead letter queue messages in Kafka and RabbitMQ, with inspection commands, root cause analysis, and alert rules.
GuideRabbitMQ Architecture: Lifecycle, Queue Types, Failures
Follow a message through RabbitMQ: how exchanges, bindings and queues route it, the three ways it can die, and how to choose between classic, quorum and stream queues on RabbitMQ 4.x.
RecipeTask Queues and RPC with RabbitMQ and AMQP
Distribute background tasks and implement request-reply patterns with RabbitMQ using durable queues, dead-letter exchanges, and prefetch.