Replication
Why Replicate?
If a cache node crashes, all data on it is lost. Replication copies data to backup nodes.
Primary Node: user:123 = "John"
↓ replicate
Backup Node 1: user:123 = "John"
Backup Node 2: user:123 = "John"How It Works
1. Client SET key value
2. Primary node stores locally
3. ReplicationManager sends to N-1 backup nodes
4. Backups store the same key-value
5. If primary crashes → backup serves the dataQuorum Write
Write succeeds when majority of nodes acknowledge:
3 nodes: write succeeds if 2/3 nodes confirm
5 nodes: write succeeds if 3/5 nodes confirmTrade-offs
| No Replication | With Replication | |
|---|---|---|
| Write speed | Fastest | Slower (network) |
| Read speed | Fastest | Fast |
| Fault tolerance | None | High |
| Memory usage | 1x | 2-3x |
Implementation
typescript
import { ReplicationManager } from "distributed-cache";
const repl = new ReplicationManager({
replicationFactor: 2, // copy to 2 backup nodes
});
// When primary stores a key
repl.replicate("user:123", userData, ["backup-1", "backup-2"]);
// When key is evicted
repl.untrackKey("user:123");