Skip to content

Quick Start

Installation

bash
npm install distributed-cache

Basic Usage

typescript
import { CacheNode, ConsistentHash } from "distributed-cache";

// Create cache nodes
const node1 = new CacheNode("node-1", { maxSize: 10000 });
const node2 = new CacheNode("node-2", { maxSize: 10000 });
const node3 = new CacheNode("node-3", { maxSize: 10000 });

// Setup consistent hashing
const hash = new ConsistentHash();
hash.addNode({ id: "node-1" });
hash.addNode({ id: "node-2" });
hash.addNode({ id: "node-3" });

// Store data
const key = "user:123";
const node = hash.getNode(key);
node?.set(key, { name: "John", email: "john@example.com" });

// Retrieve data
const value = node?.get(key);
console.log(value); // { name: "John", email: "john@example.com" }

With TCP Server

typescript
import { CacheServer, CacheClient, CacheNode } from "distributed-cache";

// Start server
const server = new CacheServer({ host: "127.0.0.1", port: 3000 });
server.addNode(new CacheNode("node-1", { maxSize: 10000 }));
await server.start();

// Connect client
const client = new CacheClient({ host: "127.0.0.1", port: 3000 });
await client.connect();

// Use cache
await client.set("product:456", { name: "iPhone", price: 999 });
const product = await client.get("product:456");
console.log(product); // { name: "iPhone", price: 999 }

await client.disconnect();
await server.stop();

Eviction Strategies

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

// LRU (default) — remove least recently used
const lru = new CacheNode("lru", {
  maxSize: 3,
  evictionPolicy: "lru",
});

// LFU — remove least frequently used
const lfu = new CacheNode("lfu", {
  maxSize: 3,
  evictionPolicy: "lfu",
});

// FIFO — remove oldest entry
const fifo = new CacheNode("fifo", {
  maxSize: 3,
  evictionPolicy: "fifo",
});

TTL (Time To Live)

typescript
const node = new CacheNode("node-1");

// Auto-expire after 60 seconds
node.set("session:abc", { userId: 123 }, 60000);

// Custom TTL per key
node.set("temp:data", "value", 5000); // 5 seconds

Persistence

typescript
const node = new CacheNode("node-1");

// Enable file persistence
node.enablePersistence({
  filePath: "./cache-data.json",
  autoSaveInterval: 30000, // auto-save every 30s
});

// Load from disk
node.loadFromDisk();

// Save to disk
node.saveToDisk();

Released under the MIT License.