RabbitMQ
RabbitMQ
An open-source message broker. AMQP protocol, flexible routing.
RabbitMQ
An open-source message broker. AMQP protocol, flexible routing.
RabbitMQ is an open-source message broker written in Erlang/OTP. It uses AMQP (Advanced Message Queuing Protocol) as its default protocol and also supports various other protocols such as MQTT, STOMP, and HTTP. It was first developed in 2007 by Rabbit Technologies and is currently managed by VMware (Broadcom).
Core components:
Exchange types:
Key features:
Kafka vs RabbitMQ: RabbitMQ is suited to complex routing, request-response patterns, and work queues. Kafka is better suited to high-volume streaming, log collection, and event sourcing. RabbitMQ "pushes" messages, while with Kafka the Consumer "pulls" them.
import pika
import json
# μ°κ²° μ€μ
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(
pika.ConnectionParameters(
host='localhost',
port=5672,
credentials=credentials,
heartbeat=600,
blocked_connection_timeout=300
)
)
channel = connection.channel()
# Exchange λ° Queue μ μΈ
channel.exchange_declare(
exchange='orders',
exchange_type='topic',
durable=True # λΈλ‘컀 μ¬μμ μμλ μ μ§
)
channel.queue_declare(
queue='order_processing',
durable=True,
arguments={
'x-message-ttl': 86400000, # 24μκ° ν λ§λ£
'x-dead-letter-exchange': 'orders_dlx', # μ€ν¨ λ©μμ§ μ²λ¦¬
'x-max-priority': 10 # μ°μ μμ μ§μ
}
)
# Binding μ€μ (Topic Exchange)
channel.queue_bind(
exchange='orders',
queue='order_processing',
routing_key='order.*.created' # order.pizza.created, order.book.created λ±
)
# Producer: λ©μμ§ λ°ν
def publish_order(order_data, order_type):
channel.basic_publish(
exchange='orders',
routing_key=f'order.{order_type}.created',
body=json.dumps(order_data),
properties=pika.BasicProperties(
delivery_mode=2, # λ©μμ§ μμμ±
content_type='application/json',
priority=order_data.get('priority', 0),
headers={'source': 'web-app'}
)
)
print(f"Published order: {order_data['id']}")
# Consumer: λ©μμ§ μλΉ
def on_message(ch, method, properties, body):
try:
order = json.loads(body)
print(f"Processing order: {order['id']}")
# λΉμ¦λμ€ λ‘μ§ μ²λ¦¬
process_order(order)
# μ±κ³΅ μ ACK
ch.basic_ack(delivery_tag=method.delivery_tag)
except Exception as e:
print(f"Error: {e}")
# μ€ν¨ μ NACK (μ¬μλ λλ DLQλ‘ μ΄λ)
ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)
# QoS μ€μ : λμμ μ²λ¦¬ν λ©μμ§ μ μ ν
channel.basic_qos(prefetch_count=10)
# μλΉ μμ
channel.basic_consume(
queue='order_processing',
on_message_callback=on_message,
auto_ack=False # μλ ACK λͺ¨λ
)
print("Waiting for messages...")
channel.start_consuming()
const amqp = require('amqplib');
class RabbitMQService {
constructor() {
this.connection = null;
this.channel = null;
}
async connect() {
this.connection = await amqp.connect({
protocol: 'amqp',
hostname: 'localhost',
port: 5672,
username: 'guest',
password: 'guest',
vhost: '/',
});
// μ°κ²° μλ¬ νΈλ€λ§
this.connection.on('error', (err) => {
console.error('Connection error:', err);
setTimeout(() => this.connect(), 5000);
});
this.channel = await this.connection.createChannel();
// Prefetch μ€μ
await this.channel.prefetch(10);
return this;
}
async setupQueues() {
// Dead Letter Exchange μ€μ
await this.channel.assertExchange('dlx', 'direct', { durable: true });
await this.channel.assertQueue('dead_letters', { durable: true });
await this.channel.bindQueue('dead_letters', 'dlx', 'dead');
// λ©μΈ ν μ€μ
await this.channel.assertExchange('tasks', 'direct', { durable: true });
await this.channel.assertQueue('task_queue', {
durable: true,
arguments: {
'x-dead-letter-exchange': 'dlx',
'x-dead-letter-routing-key': 'dead',
},
});
await this.channel.bindQueue('task_queue', 'tasks', 'process');
}
async publish(exchange, routingKey, message, options = {}) {
const content = Buffer.from(JSON.stringify(message));
// Publisher Confirms νμ±ν
await this.channel.confirmSelect();
return new Promise((resolve, reject) => {
this.channel.publish(exchange, routingKey, content, {
persistent: true,
contentType: 'application/json',
timestamp: Date.now(),
...options,
}, (err) => {
if (err) reject(err);
else resolve(true);
});
});
}
async consume(queue, handler) {
await this.channel.consume(queue, async (msg) => {
if (!msg) return;
try {
const content = JSON.parse(msg.content.toString());
await handler(content, msg.properties);
this.channel.ack(msg);
} catch (error) {
console.error('Processing error:', error);
// 3λ²κΉμ§ μ¬μλ ν DLQλ‘
const retryCount = (msg.properties.headers?.['x-retry-count'] || 0) + 1;
if (retryCount < 3) {
await this.publish(msg.fields.exchange, msg.fields.routingKey,
JSON.parse(msg.content.toString()), {
headers: { 'x-retry-count': retryCount }
});
}
this.channel.nack(msg, false, false);
}
});
}
}
// μ¬μ© μμ
(async () => {
const rabbit = await new RabbitMQService().connect();
await rabbit.setupQueues();
// Producer
await rabbit.publish('tasks', 'process', { taskId: 123, type: 'email' });
// Consumer
await rabbit.consume('task_queue', async (task) => {
console.log('Processing:', task);
});
})();
# docker-compose.yml
version: '3.8'
services:
rabbitmq1:
image: rabbitmq:3.12-management
hostname: rabbitmq1
environment:
- RABBITMQ_ERLANG_COOKIE=secret_cookie
- RABBITMQ_DEFAULT_USER=admin
- RABBITMQ_DEFAULT_PASS=secure_password
ports:
- "5672:5672" # AMQP
- "15672:15672" # Management UI
volumes:
- rabbitmq1_data:/var/lib/rabbitmq
- ./rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf
healthcheck:
test: rabbitmq-diagnostics -q ping
interval: 30s
timeout: 30s
retries: 3
rabbitmq2:
image: rabbitmq:3.12-management
hostname: rabbitmq2
environment:
- RABBITMQ_ERLANG_COOKIE=secret_cookie
depends_on:
- rabbitmq1
volumes:
- rabbitmq2_data:/var/lib/rabbitmq
volumes:
rabbitmq1_data:
rabbitmq2_data:
# rabbitmq.conf
# cluster_formation.peer_discovery_backend = rabbit_peer_discovery_classic_config
# cluster_formation.classic_config.nodes.1 = rabbit@rabbitmq1
# cluster_formation.classic_config.nodes.2 = rabbit@rabbitmq2
# Quorum Queue (κΆμ₯)
# quorum_queue.default_replication_factor = 3
Senior: "Why did you choose RabbitMQ over Kafka as the message broker?"
Developer: "Our service needs complex routing. We distribute orders to different queues by order type, and some need to be broadcast, and RabbitMQ's Exchange types fit that perfectly. Also, guaranteed per-message processing is important, and RabbitMQ's ACK/NACK is intuitive."
Senior: "Is the throughput okay at peak traffic?"
Developer: "For about 20,000β30,000 messages per second, a 3-node cluster is enough. It can't handle hundreds of thousands per second like Kafka, but that's overkill for our workload. Routing flexibility and ease of management mattered more to us."
Interviewer: "What should you do to prevent message loss in RabbitMQ?"
Candidate: "It has to be guaranteed at three levels. First, on the Producer side, you use Publisher Confirms to verify that the message has reached the broker. Second, you set the messages themselves to persistent and declare the Queue as durable so they survive a broker restart. Third, the Consumer is set to auto_ack=False and sends a manual ACK after processing is complete."
Interviewer: "What if the Consumer dies during processing?"
Candidate: "If the connection drops before the ACK, the message becomes unacked and is requeued to another Consumer. To prevent infinite retries, you set up a DLX (Dead Letter Exchange) so that after a certain number of failures the message is moved to a separate queue, where it is analyzed later or handled manually."
Operations team: "The RabbitMQ memory alarm went off and the Consumers keep dying!"
Developer: "I'll check the message count per queue in the Management UI. If unacked messages are piling up, the Consumers can't keep up with processing. The prefetch_count may be too high, or the Consumer logic may be slow."
Operations team: "There are 500,000 ready messages piled up."
Developer: "First, I'll scale out the Consumer instances and check the priority settings so the urgent messages get processed first. Fundamentally, we need to slow down the Producer or switch to a lazy queue so messages are stored on disk instead of in memory."
Take a mock interview on this topic β WIA SOOM AI Interview Β· Start for free