🏗️ Architecture

Apache Kafka

Apache Kafka

A distributed event streaming platform. A core technology for real-time data pipelines with high throughput, durability, and horizontal scalability.

📖 Detailed Explanation

Apache Kafka is an open-source distributed event streaming platform developed at LinkedIn and donated to the Apache Software Foundation. Its key characteristics are high throughput capable of processing millions of messages per second, durability with no data loss through disk-based storage, and horizontal scalability achieved simply by adding brokers.

Core concepts:

• Topic: A category where messages are stored. It is divided into multiple Partitions.
• Partition: A Topic split into units of parallel processing. Message order is guaranteed within each partition.
• Producer: A client that publishes messages to a Topic.
• Consumer: A client that subscribes to messages from a Topic.
• Consumer Group: Multiple Consumers cooperate to consume a single Topic. Each Partition is assigned to only one Consumer within the group.
• Offset: The position of a message within a partition. It tracks how far a Consumer has read.

┌─────────────────────────────────────────────────────────────────────┐ │ Kafka Cluster │ ├─────────────────────────────────────────────────────────────────────┤ │ │ │ Producer ─────┬─────▶ ┌─────────────────────────────────────┐ │ │ │ │ Topic: orders │ │ │ Producer ─────┤ │ ┌───────┐ ┌───────┐ ┌───────┐ │ │ │ │ │ │ P0 │ │ P1 │ │ P2 │ │ │ │ Producer ─────┘ │ │ msg0 │ │ msg1 │ │ msg2 │ │ │ │ │ │ msg3 │ │ msg4 │ │ msg5 │ │ │ │ │ └───────┘ └───────┘ └───────┘ │ │ │ └─────────────────────────────────────┘ │ │ │ │ │ ┌────────────┼────────────┐ │ │ ▼ ▼ ▼ │ │ Consumer 1 Consumer 2 Consumer 3 │ │ (reads P0) (reads P1) (reads P2) │ │ └──────────── Consumer Group ──────────┘ │ └─────────────────────────────────────────────────────────────────────┘

Kafka vs. a typical Message Queue: Traditional message queues such as RabbitMQ delete messages after they are consumed, whereas Kafka retains messages for a configured retention period. As a result, multiple Consumers can consume the same messages independently, and past data can be reprocessed (replayed) when needed.

Use cases: It is widely used for real-time log collection, Event-Driven Architecture microservice communication, CDC (Change Data Capture), real-time analytics, ML feature pipelines, and more. Large-scale services such as Netflix, Uber, and LinkedIn use it as core infrastructure.

💻 Code Example

// === Node.js: KafkaJS (가장 인기 있는 Node Kafka 클라이언트) ===
import { Kafka, Partitioners } from 'kafkajs';

// 1. Kafka 클라이언트 생성
const kafka = new Kafka({
    clientId: 'my-app',
    brokers: ['localhost:9092', 'localhost:9093', 'localhost:9094'],
    // 프로덕션에서는 SASL/SSL 인증 추가
    // ssl: true,
    // sasl: { mechanism: 'scram-sha-256', username: 'user', password: 'pass' }
});

// 2. Producer: 메시지 발행
const producer = kafka.producer({
    createPartitioner: Partitioners.DefaultPartitioner
});

async function produceMessages() {
    await producer.connect();

    // 단일 메시지
    await producer.send({
        topic: 'orders',
        messages: [
            {
                key: 'order-123',  // 같은 key는 같은 partition으로 (순서 보장)
                value: JSON.stringify({
                    orderId: '123',
                    userId: 'user-456',
                    items: [{ sku: 'PROD-001', qty: 2 }],
                    total: 59900,
                    timestamp: Date.now()
                }),
                headers: { 'correlation-id': 'req-abc' }
            }
        ]
    });

    // 배치 전송 (성능 최적화)
    await producer.sendBatch({
        topicMessages: [
            {
                topic: 'orders',
                messages: Array.from({ length: 100 }, (_, i) => ({
                    key: `order-${i}`,
                    value: JSON.stringify({ orderId: i, total: Math.random() * 100000 })
                }))
            }
        ]
    });

    await producer.disconnect();
}

// 3. Consumer: 메시지 구독
const consumer = kafka.consumer({ groupId: 'order-processor' });

async function consumeMessages() {
    await consumer.connect();
    await consumer.subscribe({ topic: 'orders', fromBeginning: false });

    await consumer.run({
        // autoCommit: true (기본값), 수동 커밋이 필요하면 false
        eachMessage: async ({ topic, partition, message }) => {
            const order = JSON.parse(message.value.toString());
            console.log(`[P${partition}] Order ${order.orderId}: ${order.total}원`);

            // 비즈니스 로직 처리
            await processOrder(order);

            // 수동 커밋 시: await consumer.commitOffsets([{ topic, partition, offset: message.offset }]);
        }
    });
}

// 4. 관리자 기능: Topic 생성
const admin = kafka.admin();

async function createTopics() {
    await admin.connect();
    await admin.createTopics({
        topics: [{
            topic: 'orders',
            numPartitions: 6,       // 병렬 처리 수준
            replicationFactor: 3,  // 복제본 수 (브로커 수 이하)
            configEntries: [
                { name: 'retention.ms', value: '604800000' },  // 7일 보존
                { name: 'cleanup.policy', value: 'delete' }
            ]
        }]
    });
    await admin.disconnect();
}
# === Python: kafka-python 또는 confluent-kafka ===
from kafka import KafkaProducer, KafkaConsumer
from kafka.admin import KafkaAdminClient, NewTopic
import json

# 1. Producer 생성
producer = KafkaProducer(
    bootstrap_servers=['localhost:9092'],
    key_serializer=lambda k: k.encode('utf-8') if k else None,
    value_serializer=lambda v: json.dumps(v).encode('utf-8'),
    acks='all',  # 모든 복제본이 기록 확인 후 응답
    retries=3,
    batch_size=16384,  # 배치 크기 (bytes)
    linger_ms=10       # 배치 대기 시간 (ms)
)

# 메시지 발행
def send_order(order):
    future = producer.send(
        topic='orders',
        key=order['order_id'],
        value=order,
        headers=[('source', b'order-service')]
    )
    # 동기 전송 (응답 대기)
    result = future.get(timeout=10)
    print(f"Sent to partition {result.partition}, offset {result.offset}")

send_order({
    'order_id': 'order-123',
    'user_id': 'user-456',
    'total': 59900,
    'items': [{'sku': 'PROD-001', 'qty': 2}]
})

producer.flush()  # 모든 메시지 전송 완료 대기

# 2. Consumer 생성
consumer = KafkaConsumer(
    'orders',
    bootstrap_servers=['localhost:9092'],
    group_id='order-processor',
    auto_offset_reset='earliest',  # 처음부터 읽기 (latest: 최신부터)
    enable_auto_commit=True,
    auto_commit_interval_ms=5000,
    value_deserializer=lambda m: json.loads(m.decode('utf-8'))
)

# 메시지 소비
def process_orders():
    for message in consumer:
        order = message.value
        print(f"[P{message.partition}:O{message.offset}] Order: {order['order_id']}")
        # 비즈니스 로직 처리
        # consumer.commit()  # 수동 커밋 시

# 3. Admin: Topic 생성
admin = KafkaAdminClient(bootstrap_servers=['localhost:9092'])

topic = NewTopic(
    name='orders',
    num_partitions=6,
    replication_factor=3,
    topic_configs={
        'retention.ms': '604800000',  # 7일
        'cleanup.policy': 'delete'
    }
)
admin.create_topics([topic])
# === docker-compose.yml: Kafka + Zookeeper 로컬 환경 ===
version: "3.9"

services:
  # ZooKeeper (Kafka 메타데이터 관리) - KRaft 모드로 대체 가능
  zookeeper:
    image: confluentinc/cp-zookeeper:7.5.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  # Kafka Broker
  kafka:
    image: confluentinc/cp-kafka:7.5.0
    hostname: kafka
    container_name: kafka
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
      - "9101:9101"
    environment:
      KAFKA_BROKER_ID: 1
      KAFKA_ZOOKEEPER_CONNECT: 'zookeeper:2181'
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: PLAINTEXT:PLAINTEXT,PLAINTEXT_HOST:PLAINTEXT
      KAFKA_ADVERTISED_LISTENERS: PLAINTEXT://kafka:29092,PLAINTEXT_HOST://localhost:9092
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
      KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
      KAFKA_GROUP_INITIAL_REBALANCE_DELAY_MS: 0
      KAFKA_JMX_PORT: 9101
      KAFKA_JMX_HOSTNAME: localhost
      # 로그 보존 설정
      KAFKA_LOG_RETENTION_HOURS: 168  # 7일
      KAFKA_LOG_SEGMENT_BYTES: 1073741824  # 1GB
      KAFKA_LOG_RETENTION_CHECK_INTERVAL_MS: 300000

  # Kafka UI (웹 관리 도구)
  kafka-ui:
    image: provectuslabs/kafka-ui:latest
    container_name: kafka-ui
    ports:
      - "8080:8080"
    depends_on:
      - kafka
    environment:
      KAFKA_CLUSTERS_0_NAME: local
      KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:29092
      KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper:2181

# === CLI 명령어 ===
# Topic 생성
# docker exec kafka kafka-topics --create --topic orders --partitions 6 --replication-factor 1 --bootstrap-server localhost:9092

# Topic 목록 확인
# docker exec kafka kafka-topics --list --bootstrap-server localhost:9092

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

# 메시지 확인 (콘솔 컨슈머)
# docker exec kafka kafka-console-consumer --topic orders --from-beginning --bootstrap-server localhost:9092

🗣️ Say It Like This in Practice

💬 In Architecture Design
"If we put Kafka between the order service and the shipping service, they become decoupled. When an order comes in, we publish an event to Kafka, and the shipping service just subscribes and processes it. A failure in the order service doesn't propagate to the shipping service, and even if the shipping service fails, the events remain stored in Kafka and are reprocessed after recovery."
💬 In an Interview
"To guarantee message order in Kafka, you have to use the same key. For example, if you use the order ID as the key, events for the same order go to the same partition, so their order is guaranteed. However, within a Consumer Group each partition is assigned to only one Consumer, so the number of partitions is the upper limit on the number of Consumers."
💬 During Incident Response
"Consumer lag is spiking. I checked with the kafka-consumer-groups command, and processing is slowing down on a specific partition. For now, adding Consumer instances will distribute the load, but fundamentally we need to find the bottleneck in the message processing logic. I'll check whether batch processing or asynchronous I/O can improve it."
💬 In Cost Discussions
"Running it ourselves has lower infrastructure costs but a heavier operational burden. Using a managed service like AWS MSK or Confluent Cloud reduces the operational burden, but you incur costs per message throughput. At around 1 billion messages per month, managed has a better ROI, and beyond that it's worth considering running it yourself."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌
Increasing the partition count later

Increasing the partition count breaks the existing key-to-partition mapping. The same key may go to a different partition, which breaks order guarantees. We recommend designing sufficiently at the start, and if a change is needed, creating a new topic and migrating.

❌
auto.offset.reset not set

This setting determines where a new Consumer Group starts reading when it first subscribes. 'earliest' reads from the beginning, and 'latest' reads from the newest. If it is not set and there is no offset, an error occurs. Set it explicitly to suit your use case.

❌
Ignoring the message size limit

The default message size limit is 1MB. Do not send large files through Kafka. Instead, use a pattern where you store them in S3 and pass only the URL through Kafka.

✅
Ensuring Idempotency

A Consumer may receive the same message multiple times (on retries or rebalancing). Design your message processing logic to be idempotent. Example: check for duplicates by event ID in the DB before processing.

🔗 Related Terms

📚 Learn More