RabbitMQ là gì?
RabbitMQ là một message broker implement AMQP (Advanced Message Queuing Protocol).
Vai trò chính:
-
Trung gian nhận – lưu – chuyển tiếp message
-
Giúp các service giao tiếp bất đồng bộ
-
Giảm coupling giữa producer và consumer
Không phải lúc nào system cũng nên xử lý synchronous.
Problem của synchronous
-
Service A gọi Service B
-
B chậm / down → A fail
-
Scale khó
-
Tight coupling
Asynchronous communication bằng queue
Producer → Queue → Consumer
Core Concepts
Producer
-
Service gửi message
-
Không cần biết ai consume
Exchange
Exchange quyết định message đi đâu
Producer KHÔNG gửi trực tiếp vào queue, mà gửi vào exchange
Queue
-
Nơi store message
-
Consumer đọc từ queue
Consumer
-
Service xử lý message
-
Có thể scale ngang (multiple consumers)
Binding
-
Rule kết nối exchange ↔ queue
Exchange Types (must know)
Direct Exchange
-
Route theo routing key chính xác
Use case:
-
Task routing
-
Point-to-point
Topic Exchange (rất phổ biến)
Use case:
-
Event-driven systems
-
Microservices events
Fanout Exchange
-
Broadcast tới tất cả queues
-
Ignore routing key
-
Notifications
-
Cache invalidation events
Headers Exchange
-
Route theo headers (ít dùng)
Message Flow (Typical)
Producer
↓
Exchange
↓ (binding rules)
Queue
↓
Consumer
Message Acknowledgement
RabbitMQ KHÔNG auto delete message ngay.
Ack flow
-
Consumer nhận message
-
Xử lý thành công →
ACK
-
Fail →
NACK / requeue
-
Reliability
-
At-least-once delivery
Delivery Guarantees
| Mode | Description |
| At-most-once | Có thể mất message |
| At-least-once | Có thể duplicate |
| Exactly-once | ❌ (rất khó) |
RabbitMQ chủ yếu là at-least-once
Consumer phải idempotent
Dead Letter Queue (DLQ)
DLQ = queue cho message lỗi
Khi message vào DLQ?
-
Retry quá số lần
-
Rejected
-
TTL expired
Retry Pattern
RabbitMQ không có retry native, nhưng có pattern:
TTL + DLX Pattern
-
Fail → push vào retry queue (TTL)
-
TTL expire → forward lại main queue
-
Retry count++
Common Use Cases
Background Jobs
-
Send email
-
Generate reports
-
Image processing
Event-Driven Architecture
-
Order created
-
Payment success
-
User registered
System Decoupling
-
Producer không cần biết consumer
-
Consumer scale độc lập
Rate Smoothing
-
Traffic spike → queue buffer
-
Consumer xử lý theo capacity
RabbitMQ in System Design
When to use RabbitMQ?
-
Need async processing
-
Need guaranteed delivery
-
Task-based workflows
-
Moderate throughput
-
Massive event logs (Kafka better)
-
Real-time streaming analytics
Common Pitfalls
Message Duplication
→ Fix bằng idempotent consumer
Queue Buildup
-
Consumer chậm
-
Memory pressure
-
Scale consumers
-
Back-pressure
-
Monitoring
Single Point of Failure
→ Use:
-
RabbitMQ cluster
-
Mirrored queues