RabbitMQ Architecture Designer
Purpose & When-To-Use
Trigger conditions:
- You need to design a RabbitMQ topology with exchanges, queues, and routing patterns
- You need to select queue types (classic, quorum, streams) based on durability and replication needs
- You need to configure publisher confirms or consumer acknowledgments for reliability
- You need to set up clustering for high availability with quorum queue replication
- You need to implement dead letter exchange (DLX) error handling or retry patterns
- You need to optimize consumer prefetch or concurrent processing
Complements:
integration-messagequeue-designer: For generic message queue pattern selection (RabbitMQ vs Kafka vs SQS)
messaging-kafka-architect: For Kafka-specific event streaming architectures
microservices-pattern-architect: For saga, CQRS, event sourcing patterns that use RabbitMQ
Out of scope:
- RabbitMQ installation and OS-level configuration (use infrastructure automation)
- Monitoring and alerting setup (use
observability-stack-configurator)
- Client library integration code (use language-specific AMQP client docs)
- Long-term message retention (use Kafka Streams or database for archival)
Pre-Checks
Time normalization:
- Compute
NOW_ET using NIST/time.gov semantics (America/New_York, ISO-8601)
- Use
NOW_ET for all access dates in citations
Verify inputs:
- ✅ Required: At least one message flow definition (publisher → exchange → queue → consumer)
- ✅ Required: RabbitMQ version specified (recommend 4.2+ for Khepri metadata store and quorum queue enhancements)
- ⚠️ Optional: Exchange type preferences (default to topic for flexibility)
- ⚠️ Optional: Queue type (classic, quorum, streams) - default to quorum for durability
- ⚠️ Optional: Clustering requirements (node count, replication factor)
- ⚠️ Optional: Error handling strategy (DLX, retry backoff, TTL)
Validate requirements:
- If high availability needed → quorum queues (since RabbitMQ 3.8, replicated via Raft)
- If ordering required → single active consumer (SAC) or stream queues
- If priorities needed → quorum queues support 2 priorities (high/normal) in RabbitMQ 4.0+
- If broadcasting → fanout exchange
- If complex routing → topic exchange with wildcards
Source freshness:
- RabbitMQ 4.2 latest (2025, Khepri metadata store, stream filters) (accessed
NOW_ET)
- Quorum queues introduced in 3.8, enhanced in 4.0 (priorities, consumer priority for SAC)
- Classic mirrored queues removed in 4.0 (replaced by quorum queues)
Abort if:
- No message flow specified → EMIT TODO: "Define at least one publisher → exchange → queue → consumer flow"
- Queue type unclear → EMIT TODO: "Specify queue requirements: durability (classic/quorum), replication (quorum), or high throughput (streams)"
- Clustering without quorum queues → EMIT TODO: "Use quorum queues for replicated, highly available queues (classic queues are single-node in RabbitMQ 4.x)"
Procedure
T1: Basic RabbitMQ Topology (≤2k tokens, 80% use case)
Scenario: Single exchange, single queue, direct routing, no clustering, basic error handling.
Steps:
Exchange Type Selection:
- Direct: Exact routing key match (e.g.,
order.created → order-processing-queue)
- Topic: Pattern matching with
* (1 word) and # (0+ words) (e.g., audit.events.# matches audit.events.users.signup)
- Fanout: Broadcast to all queues (ignore routing key)
- T1 recommendation: Use topic exchange for flexibility even if only using exact routing initially
Queue Type Selection:
- Classic: Single node, non-replicated (use only for dev/test)
- Quorum: Replicated (Raft consensus), durable, data safety (use for production)
- Streams: High throughput, append-only log (use for event streaming)
- T1 recommendation: Use quorum queue with
x-queue-type=quorum argument
Publisher Configuration:
- Enable publisher confirms for reliability (wait for broker acknowledgment)
- Set delivery mode = 2 for persistent messages (survive broker restart)
- T1 recommendation: Use streaming confirms (handle confirms as they arrive)
Consumer Configuration:
- Use manual acknowledgments (ack after successful processing)
- Set prefetch count = 10 (balance between throughput and backpressure)
- T1 recommendation: Ack after processing, nack+requeue on transient errors
Basic Topology:
- 1 topic exchange (
events)
- 1 quorum queue (
order-processing-queue)
- 1 binding (
order.created → order-processing-queue)
- Publisher →
events exchange with routing key order.created
- Consumer →
order-processing-queue with manual ack + prefetch=10
Output:
- Topology diagram: 1 exchange, 1 queue, 1 binding
- Publisher config: confirms enabled, persistent messages
- Consumer config: manual ack, prefetch=10
Token budget: ≤2000 tokens
T2: Multi-Exchange Routing + DLX Error Handling (≤6k tokens)
Scenario: Multiple exchanges with complex routing, dead letter exchange for errors, quorum queues, retry with backoff.
Steps:
Multi-Exchange Topology:
Pattern: Separate exchanges for different message types or bounded contexts
- Example:
orders-exchange (topic) → routes to order-processing-queue, order-audit-queue
payments-exchange (topic) → routes to payment-processing-queue
notifications-exchange (fanout) → broadcasts to all notification queues
Topic Exchange Routing Patterns:
Wildcards:
* matches exactly one word (e.g., order.*.created matches order.online.created but not order.created)
# matches zero or more words (e.g., audit.# matches audit.users, audit.users.signup, audit)
Example bindings:
order.created → order-processing-queue (exact match)
order.# → order-audit-queue (all order events)
payment.processed → payment-processing-queue
notification.* → notification-email-queue, notification-sms-queue (broadcast via topic)
Dead Letter Exchange (DLX) Setup:
Use cases:
- Handle messages rejected by consumers (nack without requeue)
- Handle messages exceeding TTL (time-to-live)
- Handle messages exceeding delivery limit (quorum queues default limit=20)
Configuration via policy (recommended):
{
"pattern": "order-processing-queue",
"definition": {
"dead-letter-exchange": "dlx-exchange",
"dead-letter-routing-key": "order.processing.failed",
"message-ttl": 86400000,
"delivery-limit": 20
}
}
DLX topology:
- Main queue:
order-processing-queue (quorum)
- Dead letter exchange:
dlx-exchange (topic)
- Dead letter queue:
dlx-order-processing-queue (quorum, for manual inspection)
- Binding:
order.processing.failed → dlx-order-processing-queue
Retry with Backoff Pattern:
Pattern: Use TTL + DLX to implement delayed retries
- Step 1: Consumer nacks message without requeue → DLX routes to
retry-queue-5s (TTL=5s)
- Step 2: After 5s, message expires → routes back to main queue via DLX
- Step 3: Repeated failures trigger delivery limit → routes to final DLX for manual handling
Example:
- Main queue:
order-processing-queue
- Retry queue 1:
retry-order-5s (TTL=5s, DLX=orders-exchange)
- Retry queue 2:
retry-order-30s (TTL=30s, DLX=orders-exchange)
- Final DLX:
dlx-order-processing-queue (manual inspection)
Quorum Queue Configuration:
Arguments:
x-queue-type=quorum (replicated queue)
x-quorum-initial-group-size=3 (replication factor, odd number for Raft consensus)
x-delivery-limit=20 (max redeliveries before DLX, default in RabbitMQ 4.0+)
x-max-priority=2 (RabbitMQ 4.0+ supports exactly 2 priorities: normal and high)
Publisher priority:
- Publish with
priority=5 (high priority, delivered 2:1 ratio vs normal)
- Publish with
priority=0 or no priority (normal priority)
Consumer Acknowledgment Strategies:
Manual ack (recommended):
- Process message →
basic.ack (remove from queue)
- Transient error (network timeout) →
basic.nack + requeue=true (redelivery)
- Permanent error (invalid data) →
basic.nack + requeue=false (send to DLX)
Prefetch tuning:
- Low prefetch (1-10): Better fairness, lower throughput
- High prefetch (50-100): Higher throughput, risk of consumer overload
- Recommendation: Start with prefetch=10, tune based on processing time and consumer count
Output:
- Multi-exchange topology (orders, payments, notifications)
- Topic routing patterns with wildcards
- DLX error handling with retry backoff
- Quorum queue configuration
- Publisher/consumer config (confirms, acks, prefetch)
Token budget: ≤6000 tokens
T3: Clustering + Streams + Advanced Patterns (≤12k tokens)
Scenario: Multi-node cluster with quorum queue replication, stream queues for high throughput, federation for multi-DC.
Steps:
Clustering Topology:
Best practices:
- Odd number of nodes: 3, 5, or 7 nodes (Raft consensus requires majority)
- Equal peers: All nodes are equal (no leader/follower at cluster level, but quorum queues use Raft leader election)
- Network requirements: Nodes must resolve hostnames, ports 4369 (epmd), 25672 (inter-node), 5672 (AMQP) open
- Avoid 2-node clusters: No clear majority during network partitions
Example 3-node cluster:
- Node 1:
rabbit@node1.example.com
- Node 2:
rabbit@node2.example.com
- Node 3:
rabbit@node3.example.com
- Erlang cookie: same on all nodes (authentication)
Quorum queue replication:
- Quorum queues replicate across 3 nodes (configurable via
x-quorum-initial-group-size)
- Raft leader elected automatically (handles writes)
- Followers replicate data (handle reads if leader down)
- Survives minority node failures (e.g., 1 node down in 3-node cluster)
Stream Queues for High Throughput:
Use case: Event streaming, audit logs, high-volume data ingestion (millions of messages/sec)
Characteristics:
- Append-only log (like Kafka topics)
- Multiple consumers can read from same offset
- Retention based on size or time (not per-consumer)
- RabbitMQ 4.2: SQL filter expressions (4M+ msg/sec filtering with Bloom filters)
Configuration:
{
"x-queue-type": "stream",
"x-max-age": "7D",
"x-stream-max-segment-size-bytes": 500000000
}
Consumer offset tracking:
- Consumer specifies offset:
first, last, next, or timestamp
- Offset stored server-side (like Kafka consumer groups)
Consistent Hashing Exchange (Plugin):
Use case: Shard messages across multiple queues for horizontal scaling
Pattern:
- Consistent hashing exchange routes based on routing key hash
- Messages with same routing key always go to same queue (ordering guarantee)
- Add/remove queues with minimal redistribution
Example:
- Exchange:
sharded-orders (type=x-consistent-hash)
- Queues:
orders-shard-0, orders-shard-1, orders-shard-2
- Routing key:
user-123 → always routes to same shard
Federation for Multi-DC:
Use case: Replicate messages across datacenters without clustering (clusters require low-latency networks)
Pattern:
- Upstream (DC1):
orders-exchange
- Downstream (DC2):
orders-exchange-federated (receives messages from DC1)
- Federation link: DC2 pulls messages from DC1
orders-exchange
Benefits:
- Survives WAN latency and network partitions (unlike clustering)
- Independent RabbitMQ clusters in each DC
- Messages flow one-way (upstream → downstream)
Advanced Publisher Patterns:
Transactional publishing (avoid, heavyweight):
- AMQP transactions (
tx.select, tx.commit) → very slow, blocks channel
- Use publisher confirms instead (asynchronous, higher throughput)
Batch publishing:
- Publish multiple messages, then wait for confirms in batch
- Higher throughput than individual confirms
- Risk: larger batch = longer recovery time on failure
Single Active Consumer (SAC) for Ordering:
Use case: Ensure messages processed in order by allowing only one consumer at a time
Configuration:
- Queue argument:
x-single-active-consumer=true
- RabbitMQ selects one consumer as active, others wait
- Automatic failover to standby consumer if active consumer dies
- RabbitMQ 4.0+: Consumer priority for SAC (higher priority consumers selected first)
Message Priority in Quorum Queues:
RabbitMQ 4.0+ feature:
- Quorum queues support exactly 2 priorities: high and normal
- No upfront declaration needed (unlike classic queues)
- Consumers receive 2:1 ratio of high to normal priority messages (avoid starvation)
- Publish with
priority=5 (high) or priority=0/unset (normal)
Output:
- 3-node cluster topology with quorum queue replication
- Stream queue configuration for high-throughput use cases
- Consistent hashing exchange for sharding
- Federation setup for multi-DC replication
- SAC and message priority patterns
Token budget: ≤12000 tokens
Decision Rules
Exchange type selection:
- Direct: Exact routing, one-to-one (e.g., task queues, RPC)
- Topic: Pattern matching, one-to-many with hierarchical routing (e.g., event bus, audit logs)
- Fanout: Broadcast, one-to-all (e.g., notifications, cache invalidation)
- Headers: Route by message headers (rare, use topic instead)
Queue type selection:
- Classic: Dev/test only (single node, non-replicated in RabbitMQ 4.x)
- Quorum: Production (replicated, durable, Raft consensus, survives node failures)
- Streams: High throughput + retention (append-only, multi-consumer reads, event streaming)
Clustering decisions:
- Single node: Dev/test, <1000 msg/sec
- 3-node cluster: Production, high availability, survives 1 node failure
- 5-node cluster: Mission-critical, survives 2 node failures
- 7+ node cluster: Rare (Raft consensus overhead increases, consider federation instead)
Prefetch tuning:
- 1-10: Low throughput, fair distribution, consumer processing time >100ms
- 10-50: Medium throughput, balanced, consumer processing time 10-100ms
- 50-100: High throughput, consumer processing time <10ms
Error handling strategy:
- Transient errors:
nack + requeue=true (network timeout, downstream unavailable)
- Permanent errors:
nack + requeue=false → DLX (invalid data, schema mismatch)
- Retry with backoff: DLX → TTL queue → re-route to main queue after delay
- Poison messages: Delivery limit (default=20) → DLX for manual inspection
Abort conditions:
- Quorum queue replication factor >cluster size → reduce to match node count
- Prefetch >1000 → risk of consumer memory exhaustion
- Classic queues in production → migrate to quorum queues for durability
Output Contract
Topology schema:
exchanges:
- name: <exchange_name>
type: direct|topic|fanout|headers
durable: true|false
auto_delete: true|false
queues:
- name: <queue_name>
type: classic|quorum|stream
durable: true|false
arguments:
x-queue-type: quorum
x-quorum-initial-group-size: 3
x-delivery-limit: 20
x-max-priority: 2 # RabbitMQ 4.0+ only
x-single-active-consumer: true|false
bindings:
- exchange: <exchange_name>
queue: <queue_name>
routing_key: <pattern> # e.g., order.created, order.#, *
policies:
- name: <policy_name>
pattern: <queue_regex>
definition:
dead-letter-exchange: <dlx_exchange>
dead-letter-routing-key: <dlx_routing_key>
message-ttl: <milliseconds>
delivery-limit: 20
Publisher config:
# Publisher confirms
channel.confirm_delivery()
# Persistent messages
channel.basic_publish(
exchange='orders-exchange',
routing_key='order.created',
body=message,
properties=pika.BasicProperties(
delivery_mode=2, # persistent
priority=5 # high priority (RabbitMQ 4.0+)
)
)
Consumer config:
# Manual ack + prefetch
channel.basic_qos(prefetch_count=10)
def callback(ch, method, properties, body):
try:
process(body)
ch.basic_ack(delivery_tag=method.delivery_tag)
except TransientError:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
except PermanentError:
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) # → DLX
channel.basic_consume(queue='order-processing-queue',
Required fields:
- Topology:
exchanges[], queues[], bindings[]
- Exchange:
name, type
- Queue:
name, type (classic/quorum/stream)
- Binding:
exchange, queue, routing_key
Examples
Example: E-commerce Order Processing with DLX
Topology:
- Exchange:
orders-exchange (topic)
- Queue:
order-processing-queue (quorum, x-quorum-initial-group-size=3)
- DLX:
dlx-exchange (topic)
- DLX Queue:
dlx-order-processing-queue (quorum, manual inspection)
- Binding:
order.created → order-processing-queue
- DLX Binding:
order.processing.failed → dlx-order-processing-queue
Policy (DLX config):
{
"pattern": "order-processing-queue",
"definition": {
"dead-letter-exchange": "dlx-exchange",
"dead-letter-routing-key": "order.processing.failed",
"delivery-limit": 20
}
}
Publisher:
channel.basic_publish(
exchange='orders-exchange',
routing_key='order.created',
body=json.dumps(order),
properties=pika.BasicProperties(delivery_mode=2)
)
Consumer:
def process_order(ch, method, properties, body):
try:
order = json.loads(body)
# Process order (may fail)
charge_payment(order)
ch.basic_ack(delivery_tag=method.delivery_tag)
except PaymentGatewayDown: # Transient error
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)
except InvalidPaymentMethod: # Permanent error
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) # → DLX
Quality Gates
Token budgets:
- T1: ≤2000 tokens (single exchange + queue + basic config)
- T2: ≤6000 tokens (multi-exchange + DLX + routing patterns)
- T3: ≤12000 tokens (clustering + streams + federation)
Safety:
- ❌ Never: Hardcode credentials in topology definitions
- ❌ Never: Use classic queues for production (single node, no replication)
- ✅ Always: Enable publisher confirms for reliability
- ✅ Always: Use manual acks for consumers (process then ack)
- ✅ Always: Use quorum queues for durability (replicated, Raft consensus)
Auditability:
- All topology definitions in version control (Git)
- Policies defined via management API or config (not hardcoded queue arguments)
- DLX queues monitored for poison messages
- Consumer ack/nack rates tracked (avoid excessive requeues)
Determinism:
- Same topology definition = same exchange/queue/binding creation
- Quorum queue leader election deterministic (Raft)
- Topic routing deterministic (same routing key → same queue)
Performance:
- Prefetch tuned for consumer processing time (avoid memory exhaustion)
- Quorum queue replication factor ≤ node count
- Stream queues for >10k msg/sec throughput
- Publisher confirms in batches for higher throughput (not individual)
Resources
Official Documentation:
Client Libraries:
- Python: pika (AMQP 0-9-1 client)
- Java: amqp-client (official Java client)
- Node.js: amqplib
- Go: amqp091-go
Related Skills:
integration-messagequeue-designer: Generic message queue pattern selection
messaging-kafka-architect: Kafka-specific event streaming
microservices-pattern-architect: Saga, CQRS, event sourcing with RabbitMQ
observability-stack-configurator: Monitoring RabbitMQ with Prometheus + Grafana
1---2name: rabbitmq-architecture-designer3description: Design RabbitMQ architectures with exchanges, quorum queues, routing patterns, clustering, dead letter exchanges, and AMQP best practices.4license: MIT5---67# RabbitMQ Architecture Designer89## Purpose & When-To-Use1011**Trigger conditions:**1213* You need to design a RabbitMQ topology with exchanges, queues, and routing patterns14* You need to select queue types (classic, quorum, streams) based on durability and replication needs15* You need to configure publisher confirms or consumer acknowledgments for reliability16* You need to set up clustering for high availability with quorum queue replication17* You need to implement dead letter exchange (DLX) error handling or retry patterns18* You need to optimize consumer prefetch or concurrent processing1920**Complements:**2122* `integration-messagequeue-designer`: For generic message queue pattern selection (RabbitMQ vs Kafka vs SQS)23* `messaging-kafka-architect`: For Kafka-specific event streaming architectures24* `microservices-pattern-architect`: For saga, CQRS, event sourcing patterns that use RabbitMQ2526**Out of scope:**2728* RabbitMQ installation and OS-level configuration (use infrastructure automation)29* Monitoring and alerting setup (use `observability-stack-configurator`)30* Client library integration code (use language-specific AMQP client docs)31* Long-term message retention (use Kafka Streams or database for archival)3233---3435## Pre-Checks3637**Time normalization:**3839* Compute `NOW_ET` using NIST/time.gov semantics (America/New_York, ISO-8601)40* Use `NOW_ET` for all access dates in citations4142**Verify inputs:**4344* ✅ **Required:** At least one message flow definition (publisher → exchange → queue → consumer)45* ✅ **Required:** RabbitMQ version specified (recommend 4.2+ for Khepri metadata store and quorum queue enhancements)46* ⚠️ **Optional:** Exchange type preferences (default to topic for flexibility)47* ⚠️ **Optional:** Queue type (classic, quorum, streams) - default to quorum for durability48* ⚠️ **Optional:** Clustering requirements (node count, replication factor)49* ⚠️ **Optional:** Error handling strategy (DLX, retry backoff, TTL)5051**Validate requirements:**5253* If high availability needed → quorum queues (since RabbitMQ 3.8, replicated via Raft)54* If ordering required → single active consumer (SAC) or stream queues55* If priorities needed → quorum queues support 2 priorities (high/normal) in RabbitMQ 4.0+56* If broadcasting → fanout exchange57* If complex routing → topic exchange with wildcards5859**Source freshness:**6061* RabbitMQ 4.2 latest (2025, Khepri metadata store, stream filters) (accessed `NOW_ET`)62* Quorum queues introduced in 3.8, enhanced in 4.0 (priorities, consumer priority for SAC)63* Classic mirrored queues removed in 4.0 (replaced by quorum queues)6465**Abort if:**6667* No message flow specified → **EMIT TODO:** "Define at least one publisher → exchange → queue → consumer flow"68* Queue type unclear → **EMIT TODO:** "Specify queue requirements: durability (classic/quorum), replication (quorum), or high throughput (streams)"69* Clustering without quorum queues → **EMIT TODO:** "Use quorum queues for replicated, highly available queues (classic queues are single-node in RabbitMQ 4.x)"7071---7273## Procedure7475### T1: Basic RabbitMQ Topology (≤2k tokens, 80% use case)7677**Scenario:** Single exchange, single queue, direct routing, no clustering, basic error handling.7879**Steps:**80811. **Exchange Type Selection:**82 * **Direct:** Exact routing key match (e.g., `order.created` → `order-processing-queue`)83 * **Topic:** Pattern matching with `*` (1 word) and `#` (0+ words) (e.g., `audit.events.#` matches `audit.events.users.signup`)84 * **Fanout:** Broadcast to all queues (ignore routing key)85 * **T1 recommendation:** Use **topic** exchange for flexibility even if only using exact routing initially86872. **Queue Type Selection:**88 * **Classic:** Single node, non-replicated (use only for dev/test)89 * **Quorum:** Replicated (Raft consensus), durable, data safety (use for production)90 * **Streams:** High throughput, append-only log (use for event streaming)91 * **T1 recommendation:** Use **quorum queue** with `x-queue-type=quorum` argument92933. **Publisher Configuration:**94 * Enable **publisher confirms** for reliability (wait for broker acknowledgment)95 * Set **delivery mode = 2** for persistent messages (survive broker restart)96 * **T1 recommendation:** Use streaming confirms (handle confirms as they arrive)97984. **Consumer Configuration:**99 * Use **manual acknowledgments** (ack after successful processing)100 * Set **prefetch count = 10** (balance between throughput and backpressure)101 * **T1 recommendation:** Ack after processing, nack+requeue on transient errors1021035. **Basic Topology:**104 * 1 topic exchange (`events`)105 * 1 quorum queue (`order-processing-queue`)106 * 1 binding (`order.created` → `order-processing-queue`)107 * Publisher → `events` exchange with routing key `order.created`108 * Consumer → `order-processing-queue` with manual ack + prefetch=10109110**Output:**111112* Topology diagram: 1 exchange, 1 queue, 1 binding113* Publisher config: confirms enabled, persistent messages114* Consumer config: manual ack, prefetch=10115116**Token budget:** ≤2000 tokens117118---119120### T2: Multi-Exchange Routing + DLX Error Handling (≤6k tokens)121122**Scenario:** Multiple exchanges with complex routing, dead letter exchange for errors, quorum queues, retry with backoff.123124**Steps:**1251261. **Multi-Exchange Topology:**127128 **Pattern:** Separate exchanges for different message types or bounded contexts129 * **Example:**130 * `orders-exchange` (topic) → routes to `order-processing-queue`, `order-audit-queue`131 * `payments-exchange` (topic) → routes to `payment-processing-queue`132 * `notifications-exchange` (fanout) → broadcasts to all notification queues1331342. **Topic Exchange Routing Patterns:**135136 **Wildcards:**137 * `*` matches exactly one word (e.g., `order.*.created` matches `order.online.created` but not `order.created`)138 * `#` matches zero or more words (e.g., `audit.#` matches `audit.users`, `audit.users.signup`, `audit`)139140 **Example bindings:**141 * `order.created` → `order-processing-queue` (exact match)142 * `order.#` → `order-audit-queue` (all order events)143 * `payment.processed` → `payment-processing-queue`144 * `notification.*` → `notification-email-queue`, `notification-sms-queue` (broadcast via topic)1451463. **Dead Letter Exchange (DLX) Setup:**147148 **Use cases:**149 * Handle messages rejected by consumers (nack without requeue)150 * Handle messages exceeding TTL (time-to-live)151 * Handle messages exceeding delivery limit (quorum queues default limit=20)152153 **Configuration via policy (recommended):**154 ```json155 {156 "pattern": "order-processing-queue",157 "definition": {158 "dead-letter-exchange": "dlx-exchange",159 "dead-letter-routing-key": "order.processing.failed",160 "message-ttl": 86400000,161 "delivery-limit": 20162 }163 }164 ```165166 **DLX topology:**167 * Main queue: `order-processing-queue` (quorum)168 * Dead letter exchange: `dlx-exchange` (topic)169 * Dead letter queue: `dlx-order-processing-queue` (quorum, for manual inspection)170 * Binding: `order.processing.failed` → `dlx-order-processing-queue`1711724. **Retry with Backoff Pattern:**173174 **Pattern:** Use TTL + DLX to implement delayed retries175 * **Step 1:** Consumer nacks message without requeue → DLX routes to `retry-queue-5s` (TTL=5s)176 * **Step 2:** After 5s, message expires → routes back to main queue via DLX177 * **Step 3:** Repeated failures trigger delivery limit → routes to final DLX for manual handling178179 **Example:**180 * Main queue: `order-processing-queue`181 * Retry queue 1: `retry-order-5s` (TTL=5s, DLX=`orders-exchange`)182 * Retry queue 2: `retry-order-30s` (TTL=30s, DLX=`orders-exchange`)183 * Final DLX: `dlx-order-processing-queue` (manual inspection)1841855. **Quorum Queue Configuration:**186187 **Arguments:**188 * `x-queue-type=quorum` (replicated queue)189 * `x-quorum-initial-group-size=3` (replication factor, odd number for Raft consensus)190 * `x-delivery-limit=20` (max redeliveries before DLX, default in RabbitMQ 4.0+)191 * `x-max-priority=2` (RabbitMQ 4.0+ supports exactly 2 priorities: normal and high)192193 **Publisher priority:**194 * Publish with `priority=5` (high priority, delivered 2:1 ratio vs normal)195 * Publish with `priority=0` or no priority (normal priority)1961976. **Consumer Acknowledgment Strategies:**198199 **Manual ack (recommended):**200 * Process message → `basic.ack` (remove from queue)201 * Transient error (network timeout) → `basic.nack` + `requeue=true` (redelivery)202 * Permanent error (invalid data) → `basic.nack` + `requeue=false` (send to DLX)203204 **Prefetch tuning:**205 * Low prefetch (1-10): Better fairness, lower throughput206 * High prefetch (50-100): Higher throughput, risk of consumer overload207 * **Recommendation:** Start with prefetch=10, tune based on processing time and consumer count208209**Output:**210211* Multi-exchange topology (orders, payments, notifications)212* Topic routing patterns with wildcards213* DLX error handling with retry backoff214* Quorum queue configuration215* Publisher/consumer config (confirms, acks, prefetch)216217**Token budget:** ≤6000 tokens218219---220221### T3: Clustering + Streams + Advanced Patterns (≤12k tokens)222223**Scenario:** Multi-node cluster with quorum queue replication, stream queues for high throughput, federation for multi-DC.224225**Steps:**2262271. **Clustering Topology:**228229 **Best practices:**230 * **Odd number of nodes:** 3, 5, or 7 nodes (Raft consensus requires majority)231 * **Equal peers:** All nodes are equal (no leader/follower at cluster level, but quorum queues use Raft leader election)232 * **Network requirements:** Nodes must resolve hostnames, ports 4369 (epmd), 25672 (inter-node), 5672 (AMQP) open233 * **Avoid 2-node clusters:** No clear majority during network partitions234235 **Example 3-node cluster:**236 * Node 1: `rabbit@node1.example.com`237 * Node 2: `rabbit@node2.example.com`238 * Node 3: `rabbit@node3.example.com`239 * Erlang cookie: same on all nodes (authentication)240241 **Quorum queue replication:**242 * Quorum queues replicate across 3 nodes (configurable via `x-quorum-initial-group-size`)243 * Raft leader elected automatically (handles writes)244 * Followers replicate data (handle reads if leader down)245 * Survives minority node failures (e.g., 1 node down in 3-node cluster)2462472. **Stream Queues for High Throughput:**248249 **Use case:** Event streaming, audit logs, high-volume data ingestion (millions of messages/sec)250251 **Characteristics:**252 * Append-only log (like Kafka topics)253 * Multiple consumers can read from same offset254 * Retention based on size or time (not per-consumer)255 * RabbitMQ 4.2: SQL filter expressions (4M+ msg/sec filtering with Bloom filters)256257 **Configuration:**258 ```json259 {260 "x-queue-type": "stream",261 "x-max-age": "7D",262 "x-stream-max-segment-size-bytes": 500000000263 }264 ```265266 **Consumer offset tracking:**267 * Consumer specifies offset: `first`, `last`, `next`, or timestamp268 * Offset stored server-side (like Kafka consumer groups)2692703. **Consistent Hashing Exchange (Plugin):**271272 **Use case:** Shard messages across multiple queues for horizontal scaling273274 **Pattern:**275 * Consistent hashing exchange routes based on routing key hash276 * Messages with same routing key always go to same queue (ordering guarantee)277 * Add/remove queues with minimal redistribution278279 **Example:**280 * Exchange: `sharded-orders` (type=`x-consistent-hash`)281 * Queues: `orders-shard-0`, `orders-shard-1`, `orders-shard-2`282 * Routing key: `user-123` → always routes to same shard2832844. **Federation for Multi-DC:**285286 **Use case:** Replicate messages across datacenters without clustering (clusters require low-latency networks)287288 **Pattern:**289 * Upstream (DC1): `orders-exchange`290 * Downstream (DC2): `orders-exchange-federated` (receives messages from DC1)291 * Federation link: DC2 pulls messages from DC1 `orders-exchange`292293 **Benefits:**294 * Survives WAN latency and network partitions (unlike clustering)295 * Independent RabbitMQ clusters in each DC296 * Messages flow one-way (upstream → downstream)2972985. **Advanced Publisher Patterns:**299300 **Transactional publishing (avoid, heavyweight):**301 * AMQP transactions (`tx.select`, `tx.commit`) → very slow, blocks channel302 * **Use publisher confirms instead** (asynchronous, higher throughput)303304 **Batch publishing:**305 * Publish multiple messages, then wait for confirms in batch306 * Higher throughput than individual confirms307 * Risk: larger batch = longer recovery time on failure3083096. **Single Active Consumer (SAC) for Ordering:**310311 **Use case:** Ensure messages processed in order by allowing only one consumer at a time312313 **Configuration:**314 * Queue argument: `x-single-active-consumer=true`315 * RabbitMQ selects one consumer as active, others wait316 * Automatic failover to standby consumer if active consumer dies317 * **RabbitMQ 4.0+:** Consumer priority for SAC (higher priority consumers selected first)3183197. **Message Priority in Quorum Queues:**320321 **RabbitMQ 4.0+ feature:**322 * Quorum queues support exactly **2 priorities**: high and normal323 * No upfront declaration needed (unlike classic queues)324 * Consumers receive **2:1 ratio** of high to normal priority messages (avoid starvation)325 * Publish with `priority=5` (high) or `priority=0`/unset (normal)326327**Output:**328329* 3-node cluster topology with quorum queue replication330* Stream queue configuration for high-throughput use cases331* Consistent hashing exchange for sharding332* Federation setup for multi-DC replication333* SAC and message priority patterns334335**Token budget:** ≤12000 tokens336337---338339## Decision Rules340341**Exchange type selection:**342343* **Direct:** Exact routing, one-to-one (e.g., task queues, RPC)344* **Topic:** Pattern matching, one-to-many with hierarchical routing (e.g., event bus, audit logs)345* **Fanout:** Broadcast, one-to-all (e.g., notifications, cache invalidation)346* **Headers:** Route by message headers (rare, use topic instead)347348**Queue type selection:**349350* **Classic:** Dev/test only (single node, non-replicated in RabbitMQ 4.x)351* **Quorum:** Production (replicated, durable, Raft consensus, survives node failures)352* **Streams:** High throughput + retention (append-only, multi-consumer reads, event streaming)353354**Clustering decisions:**355356* **Single node:** Dev/test, <1000 msg/sec357* **3-node cluster:** Production, high availability, survives 1 node failure358* **5-node cluster:** Mission-critical, survives 2 node failures359* **7+ node cluster:** Rare (Raft consensus overhead increases, consider federation instead)360361**Prefetch tuning:**362363* **1-10:** Low throughput, fair distribution, consumer processing time >100ms364* **10-50:** Medium throughput, balanced, consumer processing time 10-100ms365* **50-100:** High throughput, consumer processing time <10ms366367**Error handling strategy:**368369* **Transient errors:** `nack + requeue=true` (network timeout, downstream unavailable)370* **Permanent errors:** `nack + requeue=false → DLX` (invalid data, schema mismatch)371* **Retry with backoff:** DLX → TTL queue → re-route to main queue after delay372* **Poison messages:** Delivery limit (default=20) → DLX for manual inspection373374**Abort conditions:**375376* Quorum queue replication factor >cluster size → reduce to match node count377* Prefetch >1000 → risk of consumer memory exhaustion378* Classic queues in production → migrate to quorum queues for durability379380---381382## Output Contract383384**Topology schema:**385386```yaml387exchanges:388 - name: <exchange_name>389 type: direct|topic|fanout|headers390 durable: true|false391 auto_delete: true|false392393queues:394 - name: <queue_name>395 type: classic|quorum|stream396 durable: true|false397 arguments:398 x-queue-type: quorum399 x-quorum-initial-group-size: 3400 x-delivery-limit: 20401 x-max-priority: 2 # RabbitMQ 4.0+ only402 x-single-active-consumer: true|false403404bindings:405 - exchange: <exchange_name>406 queue: <queue_name>407 routing_key: <pattern> # e.g., order.created, order.#, *408409policies:410 - name: <policy_name>411 pattern: <queue_regex>412 definition:413 dead-letter-exchange: <dlx_exchange>414 dead-letter-routing-key: <dlx_routing_key>415 message-ttl: <milliseconds>416 delivery-limit: 20417```418419**Publisher config:**420421```python422# Publisher confirms423channel.confirm_delivery()424425# Persistent messages426channel.basic_publish(427 exchange='orders-exchange',428 routing_key='order.created',429 body=message,430 properties=pika.BasicProperties(431 delivery_mode=2, # persistent432 priority=5 # high priority (RabbitMQ 4.0+)433 )434)435```436437**Consumer config:**438439```python440# Manual ack + prefetch441channel.basic_qos(prefetch_count=10)442443def callback(ch, method, properties, body):444 try:445 process(body)446 ch.basic_ack(delivery_tag=method.delivery_tag)447 except TransientError:448 ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)449 except PermanentError:450 ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) # → DLX451452channel.basic_consume(queue='order-processing-queue', on_message_callback=callback)453```454455**Required fields:**456457* Topology: `exchanges[]`, `queues[]`, `bindings[]`458* Exchange: `name`, `type`459* Queue: `name`, `type` (classic/quorum/stream)460* Binding: `exchange`, `queue`, `routing_key`461462---463464## Examples465466### Example: E-commerce Order Processing with DLX467468**Topology:**469470* Exchange: `orders-exchange` (topic)471* Queue: `order-processing-queue` (quorum, x-quorum-initial-group-size=3)472* DLX: `dlx-exchange` (topic)473* DLX Queue: `dlx-order-processing-queue` (quorum, manual inspection)474* Binding: `order.created` → `order-processing-queue`475* DLX Binding: `order.processing.failed` → `dlx-order-processing-queue`476477**Policy (DLX config):**478479```json480{481 "pattern": "order-processing-queue",482 "definition": {483 "dead-letter-exchange": "dlx-exchange",484 "dead-letter-routing-key": "order.processing.failed",485 "delivery-limit": 20486 }487}488```489490**Publisher:**491492```python493channel.basic_publish(494 exchange='orders-exchange',495 routing_key='order.created',496 body=json.dumps(order),497 properties=pika.BasicProperties(delivery_mode=2)498)499```500501**Consumer:**502503```python504def process_order(ch, method, properties, body):505 try:506 order = json.loads(body)507 # Process order (may fail)508 charge_payment(order)509 ch.basic_ack(delivery_tag=method.delivery_tag)510 except PaymentGatewayDown: # Transient error511 ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)512 except InvalidPaymentMethod: # Permanent error513 ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False) # → DLX514```515516---517518## Quality Gates519520**Token budgets:**521522* **T1:** ≤2000 tokens (single exchange + queue + basic config)523* **T2:** ≤6000 tokens (multi-exchange + DLX + routing patterns)524* **T3:** ≤12000 tokens (clustering + streams + federation)525526**Safety:**527528* ❌ **Never:** Hardcode credentials in topology definitions529* ❌ **Never:** Use classic queues for production (single node, no replication)530* ✅ **Always:** Enable publisher confirms for reliability531* ✅ **Always:** Use manual acks for consumers (process then ack)532* ✅ **Always:** Use quorum queues for durability (replicated, Raft consensus)533534**Auditability:**535536* All topology definitions in version control (Git)537* Policies defined via management API or config (not hardcoded queue arguments)538* DLX queues monitored for poison messages539* Consumer ack/nack rates tracked (avoid excessive requeues)540541**Determinism:**542543* Same topology definition = same exchange/queue/binding creation544* Quorum queue leader election deterministic (Raft)545* Topic routing deterministic (same routing key → same queue)546547**Performance:**548549* Prefetch tuned for consumer processing time (avoid memory exhaustion)550* Quorum queue replication factor ≤ node count551* Stream queues for >10k msg/sec throughput552* Publisher confirms in batches for higher throughput (not individual)553554---555556## Resources557558**Official Documentation:**559560* RabbitMQ 4.1.0 release (Khepri metadata store, quorum queue enhancements): https://www.rabbitmq.com/blog/2025/04/15/rabbitmq-4.1.0-is-released (accessed `NOW_ET`)561* Quorum queues: https://www.rabbitmq.com/docs/quorum-queues (accessed `NOW_ET`)562* Exchanges and routing: https://www.rabbitmq.com/docs/exchanges (accessed `NOW_ET`)563* Clustering: https://www.rabbitmq.com/docs/clustering (accessed `NOW_ET`)564* Dead letter exchanges: https://www.rabbitmq.com/docs/dlx (accessed `NOW_ET`)565* Publishers: https://www.rabbitmq.com/docs/publishers (accessed `NOW_ET`)566* Consumers: https://www.rabbitmq.com/docs/consumers (accessed `NOW_ET`)567568**Client Libraries:**569570* Python: pika (AMQP 0-9-1 client)571* Java: amqp-client (official Java client)572* Node.js: amqplib573* Go: amqp091-go574575**Related Skills:**576577* `integration-messagequeue-designer`: Generic message queue pattern selection578* `messaging-kafka-architect`: Kafka-specific event streaming579* `microservices-pattern-architect`: Saga, CQRS, event sourcing with RabbitMQ580* `observability-stack-configurator`: Monitoring RabbitMQ with Prometheus + Grafana