Apache Kafka là nền tảng streaming phân tán mã nguồn mở, được phát triển ban đầu tại LinkedIn và hiện là dự án Apache top-level. Kafka cho phép xây dựng các ứng dụng xử lý dữ liệu theo thời gian thực (real-time) với khả năng chịu tải cao, độ trễ thấp và độ tin cậy lớn. Kafka được sử dụng bởi hàng nghìn công ty bao gồm Netflix, Uber, Airbnb, và LinkedIn.
Kafka hoạt động như một distributed commit log — messages được ghi theo thứ tự vào topic, lưu trữ trên disk, và có thể replay. Điều này khiến Kafka khác biệt với traditional message brokers: Kafka giữ data lâu hơn, cho phép multiple consumers đọc cùng data, và scale horizontally.
Kiến trúc của Apache Kafka
Topic và Partition
Topic là đơn vị tổ chức dữ liệu trong Kafka. Mỗi topic được chia thành nhiều partition, cho phép parallel processing và horizontal scaling. Dữ liệu trong partition được sắp xếp theo thứ tự và giữ lại trong một khoảng thời gian configurable (default 7 ngày).
Producer và Consumer
Producer gửi messages đến Kafka topic. Consumer đọc messages từ topic. Kafka hỗ trợ consumer groups — nhiều consumers cùng group chia sẻ partition để load balancing. Mỗi partition chỉ được consume bởi 1 consumer trong group.
Broker và Cluster
Kafka broker là server chạy Kafka, lưu trữ và phục vụ messages. Một Kafka cluster bao gồm nhiều brokers, đảm bảo high availability thông qua replication factor. Mỗi partition có 1 leader và N followers — leader handle reads/writes, followers replicate.
Zookeeper và KRaft
Kafka sử dụng Zookeeper để quản lý cluster metadata và leader election. Từ phiên bản 3.3+, Kafka hỗ trợ KRaft mode (Kafka Raft) cho phép vận hành mà không cần Zookeeper — đơn giản hóa deployment và giảm complexity.
Core Concepts
| Concept | Mô tả |
|---|---|
| Topic | Category/feed name mà messages được publish đến |
| Partition | Ordered, immutable sequence của messages trong topic |
| Offset | Unique identifier cho mỗi message trong partition |
| Consumer Group | Group consumers để load balance và parallel processing |
| Replication Factor | Số copies của mỗi partition across brokers |
| Retention | Thời gian giữ data trước khi delete (default 168h) |
Use Cases phổ biến của Kafka
- Event Streaming: Thu thập và xử lý events từ ứng dụng theo thời gian thực. Ví dụ: user click events, IoT sensor data, financial transactions.
- Message Queue: Thay thế traditional message brokers như RabbitMQ khi cần high throughput và message replay.
- Log Aggregation: Thu thập logs từ nhiều services để phân tích và giám sát centralized.
- Change Data Capture (CDC): Theo dõi thay đổi trong database (MySQL, PostgreSQL) và streaming ra Kafka qua Debezium.
- Data Pipelines: Xây dựng data pipelines để di chuyển dữ liệu giữa các hệ thống (database → analytics → data warehouse).
Cài đặt Kafka trên Ubuntu/Debian
# Cài đặt Java JDK (yêu cầu) sudo apt update sudo apt install openjdk-11-jdk -y # Tải Kafka wget https://archive.apache.org/dist/kafka/3.6.1/kafka_2.13-3.6.1.tgz tar -xzf kafka_2.13-3.6.1.tgz mv kafka_2.13-3.6.1 /opt/kafka # Start Zookeeper cd /opt/kafka bin/zookeeper-server-start.sh config/zookeeper.properties & # Start Kafka Broker (terminal mới) bin/kafka-server-start.sh config/server.properties
Các lệnh cơ bản với Kafka
# Tạo topic mới bin/kafka-topics.sh --create --topic my-topic \ --bootstrap-server localhost:9092 \ --partitions 3 --replication-factor 1 # Liệt kê topics bin/kafka-topics.sh --list --bootstrap-server localhost:9092 # Mô tả topic bin/kafka-topics.sh --describe --topic my-topic \ --bootstrap-server localhost:9092 # Gửi message (Producer) bin/kafka-console-producer.sh --topic my-topic \ --bootstrap-server localhost:9092 # Đọc message (Consumer) bin/kafka-console-consumer.sh --topic my-topic \ --bootstrap-server localhost:9092 --from-beginning # Xóa topic bin/kafka-topics.sh --delete --topic my-topic \ --bootstrap-server localhost:9092
Kafka trong Docker
Chạy Kafka với Docker Compose là cách nhanh nhất để development và testing:
version: '3'
services:
zookeeper:
image: confluentinc/cp-zookeeper:7.5.0
environment:
ZOOKEEPER_CLIENT_PORT: 2181
ZOOKEEPER_TICK_TIME: 2000
kafka:
image: confluentinc/cp-kafka:7.5.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-ui:
image: provectuslabs/kafka-ui:latest
depends_on:
- kafka
ports:
- "8080:8080"
environment:
KAFKA_CLUSTERS_0_NAME: local
KAFKA_CLUSTERS_0_BOOTSTRAPSERVERS: kafka:9092
KAFKA_CLUSTERS_0_ZOOKEEPER: zookeeper:2181
Kafka Streams và Kafka Connect
Kafka Streams
Kafka Streams là thư viện Java cho xử lý real-time stream data từ Kafka. Không cần external processing framework (như Spark hay Flink). Streams API cho phép filter, map, aggregate, join, và window operations trực tiếp trong application.
Kafka Connect
Kafka Connect là framework để streaming data giữa Kafka và external systems. Connectors có sẵn cho: JDBC (MySQL, PostgreSQL), Elasticsearch, S3, GCS, MongoDB, JMS. Hai modes: Source (import vào Kafka) và Sink (export từ Kafka).
Schema Registry
Schema Registry (Confluent) quản lý và enforce schema cho Kafka messages. Dùng Apache Avro, JSON Schema, hoặc Protobuf. Schema evolution cho phép thay đổi schema mà không break consumers. Backward, forward, và full compatibility modes.
So sánh Kafka với RabbitMQ
| Tiêu chí | Kafka | RabbitMQ |
|---|---|---|
| Message Retention | Theo thời gian (configurable) | Xóa sau khi consume (ack) |
| Throughput | Rất cao (triệu messages/s) | Thấp hơn (chục nghìn/s) |
| Use Case | Event streaming, log aggregation | Task queue, async processing |
| Protocol | TCP binary (custom) | AMQP, MQTT, STOMP |
| Ordering | Trong partition | Per queue |
| Replay | Có (message retained) | Không (sau khi ack) |
| Consumer Model | Pull-based | Push-based |
Best Practices khi dùng Kafka
- Partition count: Đặt partitions dựa trên throughput cần. Mỗi partition giới hạn throughput của 1 consumer. Rule of thumb: partitions = expected throughput / partition throughput.
- Replication factor >= 3: Đảm bảo data không mất khi broker fail. Min ISR (In-Sync Replicas) >= 2.
- Producer acks=all: Đảm bảo message được replicate trước khi acknowledge. Trade-off: latency cao hơn nhưng data an toàn.
- Consumer offset management: Enable auto-commit cho simple cases, manual commit cho exactly-once processing.
- Monitor lag: Consumer lag là metric quan trọng nhất — khoảng cách giữa producer offset và consumer offset. Alert khi lag tăng.
FAQ – Câu hỏi thường gặp
- Kafka có phải là Database không? Không, Kafka là message broker và event streaming platform. Kafka có thể lưu trữ data tạm thời với configurable retention, nhưng không thay thế database cho queries và transactions.
- Làm sao đảm bảo message không bị mất? Cấu hình
acks=allvàretriestrong producer. Set replication factor >= 3. Enable idempotent producer:enable.idempotence=true. - Sự khác biệt giữa Kafka và Kafka Streams? Kafka là broker (infrastructure). Kafka Streams là thư viện xử lý stream trong application. Streams API cho phép filter, aggregate, join data real-time.
- Kafka có phù hợp cho microservices không? Rất phù hợp. Kafka thường được dùng làm backbone cho event-driven microservices. Topics decouple services, enable async communication, và provide event sourcing.
- Làm thế nào để monitor Kafka? Sử dụng JMX metrics, Prometheus với kafka-exporter, và Grafana dashboards. Key metrics: consumer lag, bytes in/out, active controllers, under-replicated partitions.