🏗️ Architecture

Message Queue

Message Queue (MQ)

A message broker system for asynchronous communication. A Producer puts messages on the queue and a Consumer processes them; RabbitMQ, Apache Kafka, and AWS SQS are representative examples. Reduces coupling between services and improves system stability.

📖 Detailed Explanation

A Message Queue is middleware that enables asynchronous communication between applications. When a sender (Producer) sends a message to a queue, a receiver (Consumer) retrieves and processes the message at its own pace. This pattern removes temporal and spatial coupling between systems.

The core concepts are Producer (creates messages and sends them to the queue), Consumer (retrieves messages from the queue and processes them), Queue/Topic (the buffer where messages are stored), and Broker (the server responsible for message routing and delivery).

The message delivery guarantee levels are At-most-once (at most one time; messages may be lost), At-least-once (at least one time; duplicates are possible), and Exactly-once (exactly one time; the hardest). Most systems use At-least-once by default, and the Consumer side must ensure idempotency.

Comparison of major solutions: RabbitMQ is a traditional message broker that is strong in complex routing, Apache Kafka is a distributed event streaming platform suited to high-volume real-time processing, and AWS SQS is a fully managed service with no operational burden. Redis Streams is useful when a lightweight message queue is needed.

Message queues are used in various scenarios such as order processing, email sending, log collection, event sourcing, and integration between systems. In particular, in a microservices architecture, they are used as the core infrastructure for asynchronous communication between services.

💻 Code Example

# 메시지 큐 예제 - RabbitMQ with Python (pika)
import pika
import json
from dataclasses import dataclass, asdict
from typing import Callable
import time

# ========================================
# Producer (발행자)
# ========================================
class MessageProducer:
    def __init__(self, host: str = 'localhost'):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=host)
        )
        self.channel = self.connection.channel()

    def declare_queue(self, queue_name: str, durable: bool = True):
        """큐 선언 - durable=True면 브로커 재시작 시에도 유지"""
        self.channel.queue_declare(queue=queue_name, durable=durable)

    def publish(self, queue_name: str, message: dict):
        """메시지 발행"""
        self.channel.basic_publish(
            exchange='',
            routing_key=queue_name,
            body=json.dumps(message),
            properties=pika.BasicProperties(
                delivery_mode=2,  # 메시지 영속성 (디스크에 저장)
                content_type='application/json'
            )
        )
        print(f"[x] Sent: {message}")

    def close(self):
        self.connection.close()


# ========================================
# Consumer (소비자)
# ========================================
class MessageConsumer:
    def __init__(self, host: str = 'localhost'):
        self.connection = pika.BlockingConnection(
            pika.ConnectionParameters(host=host)
        )
        self.channel = self.connection.channel()

    def consume(self, queue_name: str, callback: Callable):
        """
        메시지 소비 시작
        - auto_ack=False: 수동 ACK (처리 완료 후 확인)
        - prefetch_count=1: 한 번에 하나씩 처리
        """
        self.channel.queue_declare(queue=queue_name, durable=True)
        self.channel.basic_qos(prefetch_count=1)

        def wrapper(ch, method, properties, body):
            message = json.loads(body)
            try:
                callback(message)
                # 성공 시 ACK - 메시지가 큐에서 제거됨
                ch.basic_ack(delivery_tag=method.delivery_tag)
            except Exception as e:
                print(f"[!] Error: {e}")
                # 실패 시 NACK - 메시지를 다시 큐에 넣음
                ch.basic_nack(delivery_tag=method.delivery_tag, requeue=True)

        self.channel.basic_consume(queue=queue_name, on_message_callback=wrapper)
        print(f"[*] Waiting for messages in {queue_name}")
        self.channel.start_consuming()


# ========================================
# 실제 사용 예제 - 주문 처리 시스템
# ========================================
@dataclass
class OrderEvent:
    order_id: str
    user_id: str
    product_id: str
    quantity: int
    total_price: float


def process_order(message: dict):
    """주문 처리 핸들러 (멱등성 보장 필요)"""
    order_id = message['order_id']

    # 1. 중복 처리 방지 (멱등성)
    if is_already_processed(order_id):
        print(f"[!] Order {order_id} already processed, skipping")
        return

    # 2. 실제 처리 로직
    print(f"[>] Processing order: {order_id}")
    time.sleep(1)  # 처리 시뮬레이션

    # 3. 처리 완료 기록
    mark_as_processed(order_id)
    print(f"[v] Order {order_id} completed")


def is_already_processed(order_id: str) -> bool:
    # Redis나 DB에서 확인 (예시)
    return False

def mark_as_processed(order_id: str):
    # Redis나 DB에 기록 (예시)
    pass


# Producer 사용
if __name__ == "__main__":
    # 주문 생성 (API 서버에서 호출)
    producer = MessageProducer()
    producer.declare_queue('orders')

    order = OrderEvent(
        order_id="ORD-12345",
        user_id="USER-001",
        product_id="PROD-100",
        quantity=2,
        total_price=59000.0
    )
    producer.publish('orders', asdict(order))
    producer.close()


# Consumer 사용 (별도 워커 프로세스)
# consumer = MessageConsumer()
# consumer.consume('orders', process_order)
// 메시지 큐 예제 - Bull (Redis 기반) with Node.js
import Bull from 'bull';
import Redis from 'ioredis';

// ========================================
// Queue 설정
// ========================================
const orderQueue = new Bull('order-processing', {
    redis: {
        host: 'localhost',
        port: 6379
    },
    defaultJobOptions: {
        attempts: 3,           // 실패 시 3회 재시도
        backoff: {
            type: 'exponential',
            delay: 1000        // 1초, 2초, 4초... 간격으로 재시도
        },
        removeOnComplete: 100, // 완료된 작업 100개만 유지
        removeOnFail: 50       // 실패한 작업 50개만 유지
    }
});

// ========================================
// Producer - 작업 추가
// ========================================
interface OrderJob {
    orderId: string;
    userId: string;
    items: Array<{ productId: string; quantity: number }>;
    totalPrice: number;
}

async function addOrderJob(order: OrderJob) {
    const job = await orderQueue.add('process-order', order, {
        priority: order.totalPrice > 100000 ? 1 : 10,  // 고액 주문 우선처리
        delay: 0,                                        // 즉시 실행
        jobId: order.orderId                            // 중복 방지
    });

    console.log(`[Producer] Added job ${job.id}`);
    return job;
}

// ========================================
// Consumer (Worker) - 작업 처리
// ========================================
orderQueue.process('process-order', 5, async (job) => {
    // 동시에 5개 작업 처리
    const order = job.data as OrderJob;

    console.log(`[Worker] Processing order ${order.orderId}`);

    // 진행 상황 업데이트
    await job.progress(10);

    // 1. 재고 확인
    await checkInventory(order.items);
    await job.progress(30);

    // 2. 결제 처리
    await processPayment(order.userId, order.totalPrice);
    await job.progress(60);

    // 3. 배송 요청
    await requestShipment(order.orderId, order.items);
    await job.progress(90);

    // 4. 완료 알림
    await sendNotification(order.userId, order.orderId);
    await job.progress(100);

    return { success: true, orderId: order.orderId };
});

// 헬퍼 함수들 (실제 구현 필요)
async function checkInventory(items: any[]) { /* ... */ }
async function processPayment(userId: string, amount: number) { /* ... */ }
async function requestShipment(orderId: string, items: any[]) { /* ... */ }
async function sendNotification(userId: string, orderId: string) { /* ... */ }

// ========================================
// 이벤트 핸들링
// ========================================
orderQueue.on('completed', (job, result) => {
    console.log(`[Event] Job ${job.id} completed:`, result);
});

orderQueue.on('failed', (job, err) => {
    console.error(`[Event] Job ${job.id} failed:`, err.message);
});

orderQueue.on('stalled', (job) => {
    console.warn(`[Event] Job ${job.id} stalled`);
});

// ========================================
// Dead Letter Queue (DLQ) 처리
// ========================================
const dlq = new Bull('order-dlq', { redis: { host: 'localhost' } });

orderQueue.on('failed', async (job, err) => {
    if (job.attemptsMade >= 3) {
        // 3회 실패 후 DLQ로 이동
        await dlq.add('failed-order', {
            originalJob: job.data,
            error: err.message,
            failedAt: new Date().toISOString()
        });
        console.log(`[DLQ] Moved job ${job.id} to dead letter queue`);
    }
});

// ========================================
// 사용 예시
// ========================================
async function main() {
    // 주문 생성
    await addOrderJob({
        orderId: 'ORD-12345',
        userId: 'USER-001',
        items: [
            { productId: 'PROD-100', quantity: 2 },
            { productId: 'PROD-200', quantity: 1 }
        ],
        totalPrice: 89000
    });
}

main();
# Apache Kafka 아키텍처 개념

# ========================================
# Kafka vs 전통적 메시지 큐 차이점
# ========================================

# 전통적 MQ (RabbitMQ, SQS):
# - Point-to-Point 또는 Pub/Sub
# - 메시지 소비 후 삭제
# - Consumer가 메시지를 "가져감"

# Kafka:
# - 분산 이벤트 스트리밍 플랫폼
# - 메시지를 일정 기간 보관 (재처리 가능)
# - Consumer가 offset으로 위치 관리
# - 파티션을 통한 병렬 처리

# ========================================
# Kafka 핵심 개념
# ========================================

# Topic: 메시지 카테고리 (예: orders, payments)
# Partition: Topic을 나눈 단위, 병렬 처리의 기본
# Producer: 메시지 발행자
# Consumer: 메시지 구독자
# Consumer Group: 같은 토픽을 구독하는 Consumer 집합
# Offset: 파티션 내 메시지 위치
# Broker: Kafka 서버 노드

# ========================================
# 파티션과 Consumer Group
# ========================================

# Topic: orders (3 파티션)
#
# Partition 0: [msg1, msg2, msg5, msg8...]
# Partition 1: [msg3, msg4, msg6, msg9...]
# Partition 2: [msg7, msg10...]
#
# Consumer Group A (주문 처리):
#   Consumer A1 -> Partition 0
#   Consumer A2 -> Partition 1
#   Consumer A3 -> Partition 2
#
# Consumer Group B (분석):
#   Consumer B1 -> 모든 Partition
#
# * 같은 그룹 내 Consumer는 파티션을 나눠 가짐
# * 다른 그룹은 독립적으로 모든 메시지 수신

# ========================================
# Kafka 설정 예시 (docker-compose.yml)
# ========================================
version: '3.8'
services:
  zookeeper:
    image: confluentinc/cp-zookeeper:7.4.0
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181

  kafka:
    image: confluentinc/cp-kafka:7.4.0
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: zookeeper:2181
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://localhost:9092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_AUTO_CREATE_TOPICS_ENABLE: "true"
      KAFKA_LOG_RETENTION_HOURS: 168  # 7일간 보관

  kafka-ui:
    image: provectuslabs/kafka-ui
    ports:
      - "8080:8080"
    environment:
      KAFKA_CLUSTERS_0_NAME: local
      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092

# ========================================
# Kafka CLI 명령어
# ========================================

# 토픽 생성
# kafka-topics --create --topic orders \
#   --bootstrap-server localhost:9092 \
#   --partitions 3 --replication-factor 1

# 메시지 발행
# kafka-console-producer --topic orders \
#   --bootstrap-server localhost:9092

# 메시지 소비 (처음부터)
# kafka-console-consumer --topic orders \
#   --bootstrap-server localhost:9092 \
#   --from-beginning --group order-group

# Consumer Group 상태 확인
# kafka-consumer-groups --describe --group order-group \
#   --bootstrap-server localhost:9092

# ========================================
# 언제 Kafka를 선택하나?
# ========================================
# - 대용량 실시간 데이터 처리 (초당 수만 건)
# - 이벤트 소싱 / CQRS 패턴
# - 로그 집계 및 분석
# - 스트림 처리 (Kafka Streams, Flink)
# - 메시지 재처리가 필요한 경우

# RabbitMQ가 나은 경우:
# - 복잡한 라우팅 로직
# - 전통적인 작업 큐
# - 낮은 지연 시간 (ms 단위)
# - 간단한 설정

🗣️ Say It Like This in Practice

💬 In a System Design Meeting
"If we handle email sending synchronously after payment is completed, the API response becomes slow. If we put an event into the message queue and a separate worker processes it, we can respond to the user right away and still be sure the email gets sent."
💬 In an incident response meeting
"The email server went down briefly, but no messages were lost. They piled up in the message queue, and once the server recovered, everything that had backed up was processed. That's thanks to message persistence and retry settings."
💬 In a Technology Selection Discussion
"Kafka is the right choice for real-time log processing. We have to process hundreds of millions of records a day, and we'll also need to reprocess them later. For a simple task queue, RabbitMQ or Redis Queue would be enough, though."

⚠️ Cautions & Best Practices

❌
Idempotency Not Guaranteed

With At-least-once delivery, duplicate messages can arrive. The Consumer must have idempotency logic that reliably prevents duplicate processing.

❌
Message Ordering Guarantee

With multiple Consumers, the order may get reversed. If order matters, use a single partition or an ordering key.

❌
Dead Letter Queue Not Configured

If messages that fail processing are retried indefinitely, the system will be paralyzed. Be sure to configure a DLQ and monitor it.

✅
Best Practices

Include a unique ID in messages, store processing state, set an appropriate retry policy, configure a DLQ, minimize message size, and set up queue monitoring and alerts.

🔗 Related Terms

📚 Learn More