Advanced multi-layer caching library with memory, Redis, and file storage. Features automatic invalidation strategies, cache warming, and comprehensive analytics.
- Multi-Layer Caching: Memory → Redis → File system with automatic promotion
- Invalidation Strategies: LRU, LFU, TTL-based, and manual invalidation
- Cache Warming: Pre-populate cache on startup
- Tag-Based Invalidation: Group and invalidate related cache entries
- Analytics: Hit/miss rates, access times, and per-layer statistics
- Universal: Works in Node.js, React, and browser environments
- TypeScript: Full type safety and IntelliSense support
npm install cache-composerFor Redis support:
npm install cache-composer ioredisimport { CacheComposer } from 'cache-composer';
const cache = new CacheComposer();
// Set a value
await cache.set('user:123', { name: 'John', age: 30 });
// Get a value
const user = await cache.get('user:123');
// Get or set with loader
const data = await cache.getOrSet('expensive-data', async () => {
return await fetchExpensiveData();
}, { ttl: 60000 }); // 1 minute TTLimport { CacheComposer } from 'cache-composer';
import Redis from 'ioredis';
const redis = new Redis();
const cache = new CacheComposer({
memory: {
enabled: true,
maxSize: 1000,
ttl: 60000, // 1 minute
invalidation: { type: 'lru' }
},
redis: {
enabled: true,
client: redis,
ttl: 3600000 // 1 hour
},
file: {
enabled: true,
directory: '.cache',
ttl: 86400000 // 24 hours
},
analytics: true
});import { CacheComposer } from 'cache-composer';
import { useEffect, useState } from 'react';
const cache = new CacheComposer();
function UserProfile({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
cache.getOrSet(`user:${userId}`, async () => {
const response = await fetch(`/api/users/${userId}`);
return response.json();
}, { ttl: 300000 }).then(setUser);
}, [userId]);
return <div>{user?.name}</div>;
}Retrieve a value from cache.
Store a value in cache.
Options:
ttl: Time to live in millisecondstags: Array of tags for grouped invalidation
Remove a key from cache.
Clear all cache entries.
Get from cache or load and cache if missing.
Get multiple keys at once.
Set multiple keys at once.
Delete all entries with a specific tag.
Delete all keys matching a pattern.
Refresh TTL for a key.
Get comprehensive cache statistics.
const stats = cache.getStats();
console.log(`Hit rate: ${(stats.hitRate * 100).toFixed(2)}%`);
console.log(`Total requests: ${stats.totalRequests}`);
console.log(`Memory layer hits: ${stats.layerStats.memory?.hits}`);Reset analytics counters.
Pre-populate cache on startup:
const cache = new CacheComposer({
warmup: {
enabled: true,
keys: [
{
key: 'config',
loader: async () => await loadConfig(),
options: { ttl: 3600000 }
},
{
key: 'popular-items',
loader: async () => await fetchPopularItems()
}
]
}
});Group related cache entries:
// Set with tags
await cache.set('user:123', userData, { tags: ['users', 'profile'] });
await cache.set('user:456', userData2, { tags: ['users', 'profile'] });
// Invalidate all user-related cache
await cache.deleteByTag('users');const cache = new CacheComposer({
memory: {
enabled: true,
maxSize: 1000,
invalidation: {
type: 'lru' // or 'lfu', 'ttl', 'manual'
}
}
});- LRU (Least Recently Used): Evicts least recently accessed items
- LFU (Least Frequently Used): Evicts least frequently accessed items
- TTL: Time-based expiration
- Manual: No automatic eviction
- Layer Order: Memory → Redis → File provides optimal performance
- TTL Strategy: Use shorter TTL for memory, longer for Redis/File
- Batch Operations: Use
mget/msetfor multiple keys - Analytics: Monitor hit rates to optimize cache configuration
Check out the examples directory for more use cases:
Contributions are welcome! Please feel free to submit a Pull Request.
MIT © codecrypt1112