Skip to content

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ệu

Quorum 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ận

Trade-offs ​

Không ReplicationCó Replication
Tốc độ ghiNhanh nhấtChậm hơn (network)
Tốc độ đọcNhanh nhấtNhanh
Chống lỗiKhôngCao
Sử dụng bộ nhớ1x2-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");

Released under the MIT License.