This directory contains practical examples demonstrating real-world use cases of hash-orbit.
All examples are standalone TypeScript files that can be run with:
# Using tsx (recommended)
npx tsx examples/redis-cache-sharding.ts
# Or compile and run
npx tsc examples/redis-cache-sharding.ts --target ES2022 --module NodeNext
node examples/redis-cache-sharding.jsDemonstrates how to distribute cache keys across multiple Redis instances using consistent hashing.
Use case: Horizontal scaling of Redis cache by sharding data across multiple servers.
Key features:
- Add/remove Redis nodes dynamically
- Minimal key redistribution on topology changes
- Deterministic key routing
Shows how to route database queries to the correct shard based on user ID or other partition keys.
Use case: Sharding a large database across multiple servers for improved performance and scalability.
Key features:
- Route queries to correct database shard
- Support for database failover
- Multi-tenant data isolation
Implements sticky session routing where user sessions consistently route to the same application server.
Use case: Load balancing with session affinity for stateful applications.
Key features:
- Session-based routing
- Server health monitoring
- Graceful server removal
Demonstrates using getN() for multi-node data replication across cache servers.
Use case: High availability cache with redundant data copies.
Key features:
- Write to multiple replicas
- Read from primary replica
- Fallback to secondary replicas
import { HashOrbit } from 'hash-orbit';
const ring = new HashOrbit({ replicas: 150 });
// Add initial nodes
ring.add('server-1');
ring.add('server-2');
// Later, add more capacity
ring.add('server-3'); // Only ~33% of keys redistribute// Detect node failure
if (await isNodeDown('server-2')) {
ring.remove('server-2');
// Keys from server-2 automatically redistribute
}const ring = new HashOrbit({ replicas: 200 });
// Add nodes from multiple regions
ring.add('us-east-1:server-1');
ring.add('us-west-2:server-1');
ring.add('eu-west-1:server-1');
// Route to nearest region based on key
const node = ring.get(`user:${userId}`);These examples use mock implementations to avoid external dependencies. In production, you would:
- Replace mock Redis clients with real
redisorioredis - Replace mock database clients with actual database drivers
- Add proper error handling and retry logic
- Implement health checks and monitoring