Skip to content

Cluster Management ​

Overview ​

A cluster is a group of cache nodes working together. ClusterManager handles node lifecycle, health monitoring, and automatic failover.

┌─────────────────────────────────────────┐
│           ClusterManager                │
│  ┌─────┐  ┌─────┐  ┌─────┐           │
│  │Node0│  │Node1│  │Node2│           │
│  │ ✅  │  │ ✅  │  │ ❌  │ ← failed  │
│  └─────┘  └─────┘  └─────┘           │
│       ↓         ↓         ↓            │
│    primary   backup   (removed)        │
└─────────────────────────────────────────┘

Singleton Pattern ​

ClusterManager is a singleton — only one instance per application:

typescript
import { ClusterManager } from "distributed-cache";

const cluster = ClusterManager.getInstance();

// Add nodes
cluster.addNode(new CacheNode("node-0", { maxSize: 10000 }));
cluster.addNode(new CacheNode("node-1", { maxSize: 10000 }));
cluster.addNode(new CacheNode("node-2", { maxSize: 10000 }));

Health Monitoring ​

Start heartbeat to detect failed nodes:

typescript
// Check every 5 seconds, mark unhealthy after 3 missed heartbeats
cluster.startHeartbeat(5000, 3);

// Callback when node fails
cluster.setOnNodeFailed((nodeId) => {
  console.log(`Node ${nodeId} failed!`);
  // Optionally: promote backup to primary
});

Node Operations ​

typescript
// Get node for a key (via consistent hashing)
const node = cluster.getNode("user:123");

// Get specific node by ID
const specific = cluster.getNodeById("node-0");

// Get all healthy nodes
const healthy = cluster.getHealthyNodes();

// Get/set primary node
cluster.setPrimary(node0);
const primary = cluster.getPrimary();

// Mark node health status
cluster.markUnhealthy("node-0");
cluster.markHealthy("node-0");

// Remove failed node
cluster.removeNode("node-0");

Cluster Flush ​

Clear all nodes at once:

typescript
const freed = cluster.flushAll();
console.log(`Freed ${(freed / 1024 / 1024).toFixed(2)} MB`);

Statistics ​

typescript
const stats = cluster.getStats();
console.log(stats);
// {
//   totalNodes: 3,
//   healthyNodes: 2,
//   unhealthyNodes: 1,
//   primary: "node-0",
//   totalKeys: 15000
// }

Leader Election ​

When the primary node fails, the cluster elects a new leader:

1. Primary node stops responding to heartbeats
2. ClusterManager marks it unhealthy
3. Next healthy node becomes primary
4. Clients redirect to new primary

Best Practices ​

PracticeWhy
Always set up heartbeatDetect failures quickly
Use setOnNodeFailed callbackReact to failures in real-time
Monitor cluster statsTrack health over time
Set appropriate timeoutToo short = false positives, too long = slow detection

Released under the MIT License.