Core Concepts, Exchanges & Queues, Publish/Subscribe, Routing Patterns, Dead Letter Queues, Clustering, Monitoring — message queue mastery.
RabbitMQ 3.13AMQP ProtocolClustering & HA
⏳
Loading cheatsheet...
📐
Core Concepts
FUNDAMENTAL
shell/basic-setup.sh
# ── Install & Run RabbitMQ ──
# Docker (recommended)
docker run -d --name rabbitmq -p 5672:5672 -p 15672:15672 rabbitmq:3-management
# Management UI: http://localhost:15672 (guest/guest)
# ── Key Concepts ──
# Producer: sends messages to an exchange
# Exchange: receives messages, routes to queues
# Queue: stores messages until consumed
# Consumer: receives messages from queues
# Binding: links exchange to queue with a routing key
# ── rabbitmqctl Commands ──
rabbitmqctl status
rabbitmqctl list_queues name messages consumers
rabbitmqctl list_exchanges name type
rabbitmqctl list_bindings
rabbitmqctl list_users
rabbitmqctl add_user admin StrongPass123
rabbitmqctl set_user_tags admin administrator
rabbitmqctl set_permissions -p / admin ".*" ".*" ".*"
rabbitmqctl delete_user guest
rabbitmqctl reset # delete all data
rabbitmqctl force_reset # force reset (cluster)
Exchange Types
Type
Routing
Use Case
direct
Exact match on routing key
Task routing, specific consumers
topic
Pattern match (*.log, order.#)
Flexible routing, log levels
fanout
Broadcast to all bound queues
Events, notifications
headers
Match on message headers
Header-based routing
default
Direct with empty routing key
Fallback exchange
AMQP Protocol Layers
Layer
Description
Transport
TCP connection (port 5672)
Authentication
SASL authentication
Channel
Multiplexed virtual connection
Exchange
Message routing decision
Queue
Message storage & delivery
Consumer
Acknowledgement & flow control
💡
Use the management plugin (rabbitmq:3-management Docker image) for development and monitoring. It provides a web UI at port 15672 for inspecting queues, exchanges, bindings, and connections. Disable guest access in production.
Use topic exchanges for flexible routing. They support pattern matching with * (single word) and # (zero or more words). Use fanout for event broadcasting. Use direct for specific task routing. Use RPC only when you need synchronous-like behavior over AMQP.
Always use manual acknowledgements (noAck: false) in production. Auto-ack loses messages if the consumer crashes before processing. Set a reasonable prefetch count (10-100) to balance throughput and memory usage.
// ── Publisher Confirms (reliable publishing) ──
channel.confirmSelect((err) => {
if (err) throw err;
channel.on('ack', (msgId) => {
console.log('Message confirmed:', msgId);
});
channel.on('nack', (msgId) => {
console.log('Message rejected:', msgId);
// Retry or log failure
});
});
// ── Batch Publish with Confirms ──
async function publishBatch(channel, exchange, messages) {
for (const msg of messages) {
channel.publish(exchange, msg.routingKey, Buffer.from(JSON.stringify(msg.body)), {
persistent: true,
contentType: 'application/json',
});
}
// Wait for all confirms
await new Promise((resolve) => channel.waitForConfirms(resolve));
}
⚠️
Use Quorum Queues for production workloads requiring high availability. They use Raft consensus for leader election and data replication, providing stronger guarantees than classic mirrored queues. Federation connects separate RabbitMQ clusters across data centers.
🎯
Interview Q&A
PREP
Q: What is the difference between exchanges?Direct: routes by exact routing key match. Topic: routes by pattern matching (*.word, #.multiple). Fanout: broadcasts to all bound queues (ignores routing key). Headers: routes by message header matching. Each exchange type serves different routing needs.
Q: How does RabbitMQ ensure message delivery?1) Persistent messages + durable queues survive restarts. 2) Publisher confirms acknowledge receipt at broker. 3) Manual consumer acknowledgements ensure processing. 4) Dead letter queues capture failed messages. 5) Quorum queues with Raft consensus for replication.
Q: What happens when a consumer fails?Unacknowledged messages are requeued and delivered to another consumer. With noAck:false, the consumer must explicitly ack/nack. If the consumer connection drops, messages become unacked and are re-delivered. Use prefetch to limit unacked messages per consumer.
Q: How do you handle duplicate messages?Implement idempotent consumers: check if a message has already been processed (by messageId or deduplication key in a database). Use deduplication tables. Set appropriate prefetch to reduce in-flight messages. Publisher confirms reduce but cannot eliminate duplicates due to retries.
Q: When to use RabbitMQ vs Kafka?RabbitMQ: message routing, task queues, request/reply, lower latency, individual message tracking, smarter consumers. Kafka: event streaming, high throughput, log aggregation, replay, partitioned topics, immutable event log. Use RabbitMQ for work distribution; Kafka for event-driven architecture.
Q: What is a Dead Letter Queue?A queue that receives messages that were rejected (nack with requeue=false), expired (TTL), or dropped (queue full). Configure DLX on the queue with deadLetterExchange. Monitor DLX depth for alerting. Messages can be inspected, republished, or analyzed for patterns.
Q: How does prefetch work?Prefetch (QoS) controls how many unacknowledged messages are delivered to a consumer. channel.prefetch(10) means max 10 unacked messages. Prevents a fast consumer from overwhelming a slow one. Set based on message processing time and desired parallelism.
Q: What are Quorum Queues?Data-safe queue type using Raft consensus for leader election and data replication. Messages are written to a majority of nodes before acknowledgment. Survives node failures. Use instead of classic mirrored queues for production. Slightly lower throughput but much stronger data safety guarantees.
💡
Top RabbitMQ interview topics: exchange types (direct/topic/fanout/headers), routing patterns, acknowledgement (ack/nack), dead letter queues, publisher confirms, prefetch/QoS, quorum queues vs classic, clustering, federation, and RabbitMQ vs Kafka comparison.