Core Idea
Synchronous = chờ kết quả (blocking)
So sánh tổng quan
| Synchronous | Asynchronous |
| Flow | Blocking | Non-blocking |
| Latency (user) | Cao | Thấp |
| Throughput | Thấp hơn | Cao hơn |
| Complexity | Thấp | Cao |
| Consistency | Strong | Eventual |
| Failure impact | Cascade | Isolated |
| UX | Chờ | Phản hồi nhanh |
Execution Model
Synchronous
Client → Service A → Service B → Response
⏳ wait
-
Caller bị block
-
Phải đợi downstream xong
Asynchronous
Client → Service A → Queue → ACK
↓
Service B xử lý sau
-
Trả response sớm
-
Xử lý background
1/ Synchronous
Characteristics
-
Request–response trực tiếp
-
Thường dùng HTTP / gRPC
-
Tight coupling giữa services
Ưu điểm
-
Dễ hiểu, dễ debug
-
Error visible ngay
-
Phù hợp transactional logic
Nhược điểm
1) Latency stacking
A → B (100ms) → C (200ms)
Total = 300ms+
2) Cascade failure
-
B down → A fail → user fail
3) Limited scalability
-
Thread bị block → resource waste
Use cases
-
Login / Auth
-
Payment
-
CRUD APIs
-
Real-time validation
2/ Asynchronous
Characteristics
-
Event-driven
-
Message queue / stream
-
Loose coupling
Ưu điểm
1) High throughput
-
Không block → xử lý song song
2) Fault isolation
-
Service B chết → queue giữ message
3) Better UX
Nhược điểm
1) Debug khó
-
Không có stack trace end-to-end
2) Eventual consistency
3) Duplicate processing
Communication Patterns
Sync
-
Message Queue (RabbitMQ)
-
Event Stream (Kafka)
-
Pub/Sub
Consistency Model
| Sync | Async |
| Data correctness | Immediate | Delayed |
| CAP alignment | CP | AP |
| Example | Payment | Notification |
Real System = Hybrid
Không system nào chỉ dùng 1 kiểu
Example: E-commerce
Sync
-
Send email
-
Update analytics
-
Notify shipping
Pitfalls (Interview gold)
Async pitfalls
-
❌ Duplicate events → need idempotency
-
❌ Out-of-order events
-
❌ Message loss (if misconfigured)
Sync pitfalls
-
❌ Timeout
-
❌ Retry storm
-
❌ Circuit breaker needed
Design Patterns
Sync patterns
-
Circuit breaker
-
Timeout
-
Retry with backoff
Async patterns
-
Queue / PubSub
-
Dead Letter Queue (DLQ)
-
Event sourcing
-
Saga pattern
Decision Framework
Use Sync when:
-
Cần kết quả ngay
-
Cần strong consistency
-
User-facing critical path
Use Async when:
-
Task dài / không critical
-
Scale lớn
-
Tolerate delay
One-liner (Interview)
“Use synchronous for critical, real-time operations and asynchronous for scalable, decoupled background processing.”
Mental Model
Sync = correctness first
Advanced Insight
Async không phải “faster”
Sync không phải “bad”
-
Phần quan trọng nhất của system luôn sync