← Về danh sách bài họcBài 4/20

⚖️ Bài 4: So Sánh Message Broker

⏱️ Thời gian đọc: 22 phút | 📚 Độ khó: Trung bình

🎯 Sau bài học này, bạn sẽ:

1. Bảng So Sánh Tổng Quan

Tiêu chí 🐰 RabbitMQ 🦅 Kafka 🔴 Redis ☁️ SQS
Loại Message Broker Distributed Log In-memory Pub/Sub Managed Queue
Throughput ~50K msg/s ~1M+ msg/s ~500K msg/s ~3K msg/s
Latency ~1ms ~5ms <1ms ~50ms
Lưu trữ Disk/Memory Disk (append-only) Memory only Disk (AWS)
Replay ❌ Không ✅ Có (offset) ❌ Không ❌ Không
Ordering Per queue Per partition Không đảm bảo FIFO queue có
Routing Rất linh hoạt Topic-based Channel-based Đơn giản
Ops phức tạp Trung bình Cao Thấp Rất thấp

2. RabbitMQ — Smart Broker

Triết lý: "Smart broker, dumb consumer" — broker quyết định route message.

Producer ──▶ Exchange ──▶ Queue ──▶ Consumer
             (Routing)   (Store)   (Process)
✅ Ưu điểm: Routing linh hoạt (Direct, Fanout, Topic, Headers), hỗ trợ AMQP/MQTT/STOMP, Management UI, ACK/retry/DLQ built-in
❌ Nhược điểm: Throughput thấp hơn Kafka, không replay message, clustering phức tạp ở scale lớn

3. Apache Kafka — Distributed Log

Triết lý: "Dumb broker, smart consumer" — broker chỉ lưu log, consumer tự quản lý offset.

Producer ──▶ Topic (Partition 0, 1, 2...) ──▶ Consumer Group
             Append-only log                   (tự track offset)
✅ Ưu điểm: Throughput cực cao (1M+ msg/s), replay message, built-in replication, horizontal scaling
❌ Nhược điểm: Routing đơn giản, operations phức tạp, latency cao hơn RabbitMQ, overkill cho app nhỏ

4. Redis Pub/Sub

const Redis = require('ioredis');
const sub = new Redis();

sub.subscribe('notifications');
sub.on('message', (channel, msg) => {
    console.log(`[${channel}]: ${msg}`);
});

const pub = new Redis();
pub.publish('notifications', JSON.stringify({ type: 'order_created' }));
✅ Ưu điểm: Cực nhanh (<1ms), đơn giản, không cần thêm infrastructure
❌ Nhược điểm: Không persist message, không ACK, fire-and-forget
💡 Redis Streams (5.0+) khắc phục nhược điểm: persistence, consumer groups, ACK — tương tự Kafka nhẹ.

5. Amazon SQS — Managed Queue

const AWS = require('aws-sdk');
const sqs = new AWS.SQS({ region: 'ap-southeast-1' });

await sqs.sendMessage({
    QueueUrl: 'https://sqs.../my-queue',
    MessageBody: JSON.stringify({ orderId: 123 })
}).promise();
✅ Ưu điểm: Không cần quản lý infra, auto-scaling, tích hợp AWS
❌ Nhược điểm: Latency cao (~50ms), throughput thấp, vendor lock-in

6. Chọn Broker Nào?

🐰 RabbitMQ: Task queue, RPC, routing phức tạp, ứng dụng vừa
🦅 Kafka: Event streaming, big data, replay, throughput >100K msg/s
🔴 Redis: Real-time notifications, caching + messaging nhẹ
☁️ SQS: AWS ecosystem, serverless (Lambda + SQS)

📝 Tóm Tắt