Memory, Redis, and Disk under one API.
Stampede protection, distributed invalidation, and circuit breakers.
Install it in one line.
npm install layercache
Requests check the fastest layer first. Hits automatically backfill upper layers, and misses execute the fetcher only once.
Measured on a realistic workload with real file I/O and SHA-256 hashing. Node.js v20, Redis 7, single-process run.
The first cache layer returns in microseconds, which changes the entire performance profile of the app before Redis or disk even enter the picture.
When cache entries expire, hundreds of concurrent requests can slam the database at once. layercache prevents that completely.
npx layercache stats|keys|invalidate - manage Redis cache directly from the terminal.import { CacheStack, MemoryLayer, RedisLayer, RedisInvalidationBus, RedisSingleFlightCoordinator } from 'layercache' import Redis from 'ioredis' const redis = new Redis() // L1 invalidation bus across instances const bus = new RedisInvalidationBus({ publisher: redis, subscriber: new Redis() }) // Distributed stampede protection const coordinator = new RedisSingleFlightCoordinator({ client: redis }) export const cache = new CacheStack( [ new MemoryLayer({ ttl: 60, maxSize: 10_000 }), new RedisLayer({ client: redis, ttl: 3600, compression: 'gzip', prefix: 'myapp:' }) ], { invalidationBus: bus, singleFlightCoordinator: coordinator, gracefulDegradation: { retryAfterMs: 10_000 } } ) // Usage: on misses, the fetcher runs only once const user = await cache.get(`user:${id}`, () => db.findUser(id), { ttl: 120, tags: ['users'] }) // Invalidate everything by tag await cache.invalidateByTag('users')
A single middleware line plugs into major Node.js frameworks including Express, Fastify, and NestJS.
import { createExpressCacheMiddleware } from 'layercache' app.get('/api/products', createExpressCacheMiddleware(cache, { ttl: 30, tags: ['products'], keyResolver: (req) => `products:${req.url}` }), productHandler )
411 tests. Full TypeScript types. Apache 2.0 licensed.
A new production-ready baseline for Node.js caching.