πŸ—οΈ Architecture

RabbitMQ

RabbitMQ

An open-source message broker. AMQP protocol, flexible routing.

πŸ“– Detailed Explanation

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:

  • Producer: Creates messages and sends them to the Exchange
  • Exchange: Distributes messages to Queues according to routing rules (Direct, Topic, Fanout, Headers)
  • Queue: A buffer where messages are actually stored
  • Binding: A rule that connects an Exchange to a Queue
  • Consumer: Consumes messages from a Queue

Exchange types:

  • Direct: Exact routing key matching (point-to-point)
  • Topic: Pattern matching (*.logs, error.#)
  • Fanout: Broadcasts to all connected queues
  • Headers: Routing based on message headers

Key features:

  • Reliability: Message persistence, Publisher Confirms, Consumer Acknowledgments
  • Clustering: Configures multiple nodes as a cluster to ensure high availability
  • Mirroring: Data replication through Queue Mirroring (Classic) or Quorum Queues (recommended)
  • Management UI: Provides a web-based management console (port 15672)
  • Plugin system: Extensible with Federation, Shovel, Delayed Message, and more

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.

πŸ’» Code Example

Python - pika library

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()

Node.js - amqplib

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 - RabbitMQ cluster

# 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

πŸ—£οΈ Examples of Practical Conversations

Technical meeting

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."

Technical Interview

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."

Incident response

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

⚠️ Cautions

πŸ”— Related Terms

Message Queue AMQP Apache Kafka Pub-Sub Pattern Event-Driven Architecture Dead Letter Queue

πŸ“š Learn More