Replication
Tại sao cần Replicate?
Nếu cache node gặp sự cố, toàn bộ dữ liệu trên đó bị mất. Replication sao chép dữ liệu sang backup nodes.
Primary Node: user:123 = "John"
↓ replicate
Backup Node 1: user:123 = "John"
Backup Node 2: user:123 = "John"Cách hoạt động
1. Client SET key value
2. Primary node lưu cục bộ
3. ReplicationManager gửi sang N-1 backup nodes
4. Backup nodes lưu cùng key-value
5. Nếu primary crash → backup phục vụ dữ liệuQuorum Write
Ghi thành công khi majority nodes xác nhận:
3 nodes: ghi thành công nếu 2/3 nodes xác nhận
5 nodes: ghi thành công nếu 3/5 nodes xác nhậnTrade-offs
| Không Replication | Có Replication | |
|---|---|---|
| Tốc độ ghi | Nhanh nhất | Chậm hơn (network) |
| Tốc độ đọc | Nhanh nhất | Nhanh |
| Chống lỗi | Không | Cao |
| Sử dụng bộ nhớ | 1x | 2-3x |
Triển khai
typescript
import { ReplicationManager } from "distributed-cache";
const repl = new ReplicationManager({
replicationFactor: 2, // sao chép sang 2 backup nodes
});
// Khi primary lưu key
repl.replicate("user:123", userData, ["backup-1", "backup-2"]);
// Khi key bị evict
repl.untrackKey("user:123");