# lazy-layers-cache: full context > lazy-layers-cache is an open-source L1/L2 cache for Node.js and Cloudflare Workers: an in-process L1 in front of an optional shared L2 (Redis, Cloudflare KV or a Durable Object cache tier), read through with `getOrSet`, with stampede protection inside one process and, with a Redis lease, across processes, and invalidation over an event bus. MongoDB can coordinate locks, counters and invalidation, but it is not a shared L2. Current release: 8.0.0. License: MIT. Language: TypeScript, shipped as ESM and CommonJS with type declarations. Runtime dependencies: one (`msgpackr`). Also known as LazyLayers or Lazy Layers. Every number in this file comes from BENCHMARKS.md (https://github.com/Amon20044/LazyLayers/blob/main/BENCHMARKS.md), which names the command, machine, date and statistic for each. The complete documentation, page by page, is served at https://lazy-layers-cache.vercel.app/docs. Append `.md` to a docs URL to read the page as Markdown. ## When to use it Use it when a Node.js service or Cloudflare Worker reads the same data repeatedly from a slower origin (a database, an API) and needs some of: - an in-process cache in front of a shared one (Redis or Cloudflare KV), read through with one call - protection against cache stampedes, in one process and across several instances - invalidation that reaches every instance's in-memory copy - a cache that keeps serving when Redis, the event bus or the origin fails - an in-memory cache bounded by bytes that shrinks before the process runs out of memory. Where another library is the better choice (from BENCHMARKS.md): - Smallest, fastest plain LRU map: `lru-cache`, `quick-lru` or `@isaacs/ttlcache`. They insert faster, hold less per entry, and do nothing else. - Most storage drivers: bentocache ships SQL, DynamoDB, file and Upstash drivers. Lazy Layers ships Redis, Cloudflare KV, Durable Objects and MongoDB, and a conformance kit to add others. - Lowest-overhead read-through on a single process: layered-loader and async-cache-dedupe spend a few hundred nanoseconds per call on misses, where Lazy Layers spends more on bookkeeping that pays off with several processes. ## Install ```bash npm install lazy-layers-cache ``` Requires Node.js 20 or 22+. Use Node.js 22+ for the NATS integration, because its current transitive dependency declares that minimum. Integrations are optional peer dependencies. Importing the package never loads them, and a missing one raises `MissingPeerDependencyError` with the install command. | You use | Also install | | --- | --- | | Redis L2 or Redis Pub/Sub (`setupCache({ redis })`) | `ioredis` | | RabbitMQ event bus | `amqplib` | | NATS event bus | `@nats-io/transport-node @nats-io/jetstream` | | LZ4 or Snappy compression (recommended with Redis) | `lz4-napi snappy` | ## First cache ```js import { setupCache } from 'lazy-layers-cache' const cache = await setupCache({ namespace: 'demo', redis: false }) let loaderCalls = 0 try { const loadUser = async () => { loaderCalls++ return { id: '42', name: 'Ada' } } await cache.getOrSet('user:42', loadUser) const user = await cache.getOrSet('user:42', loadUser) console.log(user.name, loaderCalls) // Ada 1 } finally { await cache.close() } ``` ## Several instances with Redis Set `REDIS_URL`, install `ioredis`, and create one cache per process: ```js import { setupCache } from 'lazy-layers-cache' export const cache = await setupCache({ namespace: 'users-api', redis: { required: true }, }) export function getUser(id) { return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => { const user = await db.users.findById(id, { signal }) return user ?? undefined }) } export async function updateUser(id, patch) { const user = await db.users.update(id, patch) await cache.invalidate(`user:${id}`) // after the write commits return user } ``` `setupCache` reads `REDIS_URL`, creates Redis L2 and Redis Pub/Sub, checks readiness, waits for the event subscription, and manages shutdown. Each instance keeps its own L1. Use the same namespace and Redis service for instances that share cached data. `redis: { required: true }` makes a missing or unhealthy Redis fail startup instead of silently starting isolated L1 caches. `setupCache` defaults to a 10 second L1 TTL and a 32 KiB peer-broadcast ceiling. ## Methods | Task | Method | | --- | --- | | Read a value, loading it on a miss | `getOrSet(key, loader, options?)` | | Refresh after a committed database write | `invalidate(key)` (same as `delete`) | | Invalidate a key family | `invalidateByPattern('tenant:42:*')` (same as `deleteByPattern`) | | Invalidate every value carrying a tag | `invalidateTags(['store:7'])`. Store values with `{ tags }` | | Warm a key before traffic needs it | `prewarm(key, loader)` | | Read or load many keys at once | `getMany(keys)`, `getOrSetMany(keys, loadMissing)` (one loader call for every miss) | | Write or delete many keys | `setMany(entries)`, `deleteMany(keys)` | | Group keys you can clear together | `namespace('tenant:42')`, with its own `clear()`. Namespaces nest | | Read L1 without awaiting | `peekLocal(key)` (synchronous, never touches L2) | | Subscribe to cache events | `on(handler)` (returns an unsubscribe function) | | Release managed resources | `close()` (idempotent) | Only a `getOrSet` loader result is broadcast to peers. A direct `set` is not. Commit database writes before invalidating. Keep loaders read-only and pass the supplied `AbortSignal` to your client. A cache lease reduces duplicate loads but does not authorize a business operation or guarantee exactly-once execution. ## What happens on a read 1. A hit in the built-in L1 returns without awaiting. 2. On a miss, the caller becomes the key's in-flight leader before its first await, so concurrent callers in the process share the L2 read and the load. 3. L2 is read. With RedisStore's v2 key layout and the lock on, the same Lua script takes the key's lease when it is empty. 4. On an L2 miss the loader runs once. With the lease, the value is published to Redis and the lease released in one script: a miss costs 2 Redis round trips (7 in 0.7.0). 5. The value is written to L1. With an event bus, it is broadcast as a `set` event so peers can write it into their own L1 without querying the database (capped by `broadcastSetMaxBytes`, and values with tags are not broadcast). 6. Other instances that missed the same key wait on the lease and are woken by that broadcast, or by a lease announcement, within one bus hop. Without a bus they poll every `pollMs` (50 ms). 7. Redis or bus failures degrade to the origin. Eligible stale data can cover a loader failure, but loader errors, overload or lock deadlines can still reach the caller. ## Stampede protection - In one process: concurrent `getOrSet` callers for the same key share one promise. Measured: 10,000 concurrent callers on one cold key with a 20 ms loader ran the loader once and were all served in 30.8 ms (72.9 ms in 0.7.0). - Across processes: with Redis L2, `getOrSet` takes a per-key lease automatically, renews it while the load runs, and makes other instances wait. With an event bus a waiting server had the value a median 0.81 ms after the other server's load returned, against 36.11 ms when polling every 50 ms (measured against an in-memory Redis double, so this is the cache's own delay, not network time). - Waiting is bounded: by default `max(lock ttlMs, loader hardMs) + pollMs`, 10,050 ms. At the deadline the cache serves eligible stale data or throws `DistributedLockTimeoutError`. - This is stampede protection, not exactly-once execution: Redis failover, process pauses and loaders that ignore their abort signal can allow overlapping origin work. ## Invalidation - By key: `invalidate(key)` removes the key from L1, L2, negative, stale and in-flight state, and publishes a `del` event. - By pattern: `invalidateByPattern('tenant:42:*')` scans L1 and L2 for matching keys and publishes a `pattern` event. Keep patterns tightly prefixed. - By tag: `invalidateTags(tags)` gives each tag a new random token. Entries loaded under an older token read as misses. No key scan, safe across clock skew, and a load that started before the invalidation cannot bring its value back. Without an event bus other instances notice within `tagCheckMs` (1 s by default). - Events carry an ID (duplicates dropped), a source (own events ignored) and, for single keys, a per-key generation, so a late `set` cannot undo a newer delete. Pattern events carry no generation. Event buses: | Transport | Delivery | | --- | --- | | Redis Pub/Sub (the default with `setupCache`) | At most once. No new infrastructure when Redis is already L2 | | NATS Core | At most once. Fastest fan-out | | RabbitMQ | Durable. A queue per server holds invalidations while it is disconnected | | NATS JetStream | Durable. Replayable stream with explicit acks | | Durable Object RPC (`BroadcastEventBus`, coordination entry point) | At most once. Worker shards broadcast to each other | | MongoDB change streams (`MongoChangeStreamEventBus`, coordination entry point) | Gaps are reconciled: while a stream is down, peers stop trusting L1 | With managed Redis Pub/Sub, a subscription gap makes local invalidation state untrusted: the cache bypasses L1, negative entries and stale fallbacks until recovery restores trust. ## Freshness ```js const cache = await setupCache({ namespace: 'users-api', redis: { required: true }, levels: { L1: { valueMode: 'reference' } }, // eviction: S3-FIFO by default earlyRefresh: 0.8, // reload popular keys in the background before they expire staleWhileRevalidate: true, ttlJitter: 0.1, }) ``` - `earlyRefresh: 0.8`: the first `getOrSet` hit after 80% of a value's lifetime returns the cached value and reloads the key once in the background. - `staleWhileRevalidate: true`: an expired value still within `failSafe.staleTtlMs` is returned at once while the key refreshes once in the background. - `ttlJitter: 0.1`: each write's TTL is scaled by a random factor between 0.9 and 1.1, so keys written together do not expire together. - `ms('2.5h')` converts readable durations. - The TTL the cache resolves (per call, then `levels.L2.ttlMs`, then `ttlMs`) is passed to the L2 store with every write. ## L1: eviction, value modes and memory - Eviction policy (`levels.L1.policy`): `'s3fifo'` (default), `'lru'`, `'sieve'`, `'fifo'`, a factory such as `s3fifoPolicy({ promoteAfterHits: 2 })`, or a name registered with `registerEvictionPolicy`. - On the synthetic policy matrix, S3-FIFO had the lowest mean miss ratio (56.39%, against 61.31% for LRU), up to 14.18 points fewer misses than LRU, and was never more than 4.45 points behind it. Use `'lru'` when the popular set is replaced wholesale and fits in the cache. - Admission is on by default: when space is tight, a new value must be worth more per byte than what it would evict. - Value modes: `'encoded'` (default) stores bytes and returns a private copy on every hit. `'reference'` stores the object and returns it without decoding (values deep-frozen outside production). A warm L1 `get()` measured 1,141 ns encoded and 120 ns in reference mode. - Encoded records of up to 2 KiB are kept as compact one-byte strings: 76.1 bytes retained per small entry with LRU and 98.4 with S3-FIFO (276 and 298 before 8.0's compact records). lru-cache retained 57.1 in the same test. - Reference-mode values are charged their heap size from a model of V8's object layout, within 3% for values that own their contents. | Limit | What it counts | Default | | --- | --- | --- | | `maxEntries` | entries | 1,000 | | `maxMemory` | what the caches hold: exact encoded bytes, or the reference-mode model | 20% of effective memory, at most 75% | | `maxProcessMemory` | the process's RSS, whatever holds it | effective memory (container limit or host memory): the cache shrinks at 90% and refuses L1 writes at 100% | | V8 heap | the heap, as a share of its limit | the cache shrinks at 85% and refuses L1 writes at 95% | Writes check the heap and RSS every 1,024 reservations or 4 MiB, so a burst between the 5-second samples cannot exhaust the heap or the container. `MemoryStore` can also be used directly as an in-process cache, with `getSync`, `setSync` and `hasSync`. ## Resilience | Mechanism | Behaviour | | --- | --- | | Fail-open | An L2 read error is a miss and the loader runs. A bus publish failure does not fail a successful load | | Fail-safe | On by default with a 30 second window: a recent value is served when the loader fails or times out | | Negative caching | A loader that returns `undefined` is remembered as a miss (10 s, 10,000 entries by default) | | Circuit breakers | On L2 and the event bus: three consecutive failures open them, then a 30 second cooldown | | Timeouts | Loader soft and hard timeouts with an `AbortSignal` | | Origin gate | Bounds concurrent loader work in each cache instance | | Payload limits | Hostile or corrupt payloads are rejected before decoding. A corrupt value is a miss | ## Cloudflare Workers and KV - Workers: `import { CloudflareWorkerCache } from 'lazy-layers-cache/cloudflare'` with a KV binding. `getOrSet` checks an optional isolate L1, then KV, then the loader. The entry point bundles without Node-only code. - Node.js: `CloudflareKVRestNamespace` with `setupCache({ kv: { namespace } })`. Workers and Node.js read each other's records when they use the same namespace and key prefix. - KV writes use MessagePack with adaptive gzip: payloads of at least 1 KiB are compressed only when gzip saves at least 15%. - KV is eventually consistent (a change can take 60 seconds or more to reach another location) and has no atomic lease, so loads are deduplicated only within one Worker cache object or Node.js process. An optional Cloudflare Queue consumer retries application invalidations. It does not reach every isolate's L1. ## Without Redis: coordination `lazy-layers-cache/coordination` (added in 0.7) gives several instances the shared state Redis usually provides: | You run on | Locks, counters, rate limits, shared keys | Shared L2 | Invalidation between instances | | --- | --- | --- | --- | | Cloudflare Workers | Durable Objects (SQLite) | Durable Object cache tier | Durable Object RPC (`BroadcastEventBus`) | | Node.js with MongoDB | a MongoDB collection | none (L1 per instance) | change streams (`MongoChangeStreamEventBus`) | ```js import { durableObjectCoordination, consumeRateLimit } from 'lazy-layers-cache/coordination' const coordination = durableObjectCoordination({ namespace: env.COORDINATOR, shards: 4 }) await coordination.set('lock:job', workerId, { ifAbsent: true, ttlMs: 30_000 }) // true for one caller const limit = await consumeRateLimit(coordination, `rl:login:${ip}`, { limit: 5, windowMs: 60_000 }) ``` Every operation is atomic. The entry point loads no Redis, NATS, RabbitMQ or native codec code. ## Serialization Values are MessagePack. On Node.js, compression is chosen by packed size: none below 256 bytes, LZ4 below 4 KiB, Zstandard from 4 KiB (LZ4 where Zstandard is unavailable). A compressed payload is kept only when it saves at least 15%. Without `lz4-napi`, LZ4 falls back to Snappy, then Zstandard (Node 22.15+), then no compression. `CACHE_COMPRESSION` sets the process-wide mode (`none`, `gzip`, `zstd`, `auto`, or a JSON tier list). ## Observability - Events: `cache.on(handler)` receives every hit, miss, set, delete, load, timeout, stale serve, broadcast and bus error. It costs nothing until something subscribes. - Dashboard: `observability: true` serves a live dashboard at `/__lazylayers` on `127.0.0.1:7077`. With no credentials configured it generates a random token and prints the URL once. Set `auth.token`, or `auth.username` and `auth.password` together. - Prometheus: metrics at `{route}/metrics` with the prefix `lazycache`, including hits and misses by level, loader duration, stale values served, L1 bytes, evictions by policy, memory pressure, early refreshes and deletes by kind. Selected environment variables: `REDIS_URL`, `LAZY_LAYERS_NAMESPACE`, `CACHE_COMPRESSION`, `LAZY_LAYERS_DEBUG` (opt-in debug logging), `LAZY_OBS_ENABLED`, `LAZY_OBS_ROUTE` (default `/__lazylayers`), `LAZY_OBS_TOKEN`, `LAZY_OBS_PROMETHEUS`, `INSTANCE_ID`. ## Benchmarks Measured on an Apple M5 (10 logical CPUs), Node 24.21, macOS, on 2026-11-12. Competitors at pinned versions, each measurement in a fresh process, median of 5 runs. In-process behaviour only. 8.0.0 against 0.7.0 (same machine and session): | Scenario | 0.7.0 | 8.0.0 encoded | 8.0.0 reference | | --- | ---: | ---: | ---: | | Read-through warm hit (`getOrSet`, 10,000 keys) | 6,490 ns | 1,610 ns | 180 ns | | 10,000 concurrent callers on one cold key (20 ms loader) | 72.9 ms | 30.8 ms | 30.2 ms | | Redis round trips per miss, with the lock | 7 | 2 | 2 | | Delay before a waiting server has the value (with a bus) | 36 ms | 0.8 ms | 0.8 ms | | Runtime dependencies | 8 | 1 | 1 | Read-through caches. Warm hit: 10,000 resident keys. Herd: 10,000 callers, 20 ms loader, one loader call for every library. Skewed: Zipf α = 1.0 over 100,000 keys, capacity 10%. | Library | Warm hit | 10,000-caller herd | Skewed traffic | | --- | ---: | ---: | ---: | | lazy-layers-cache 8.0.0 (reference, SIEVE) | 180 ns | 30.2 ms | 2,011 ns · 75.41% hits | | lazy-layers-cache 8.0.0 (encoded, LRU) | 1,504 ns | 31.0 ms | 4,021 ns · 72.85% hits | | layered-loader 17.0.0 | 220 ns | 25.6 ms | 435 ns · 72.85% hits | | async-cache-dedupe 3.4.0 | 658 ns | 25.1 ms | 911 ns · 72.85% hits | | @epic-web/cachified 5.6.3 | 821 ns | 45.1 ms | 1,150 ns · 72.85% hits | | bentocache 1.6.1 (serialize: false) | 1,120 ns | 89.8 ms | 1,936 ns · 72.85% hits | | bentocache 1.6.1 (default) | 2,429 ns | 114 ms | 3,640 ns · 72.85% hits | | cache-manager 7.2.9 | 9,337 ns | 35.6 ms | 10,635 ns · 72.85% hits | | cacheable 2.5.0 | 9,470 ns | 99.9 ms | 11,003 ns · 72.85% hits | With S3-FIFO, the default, the read-through hit ratio on that traffic is 75.89%. In memory, the hit ratio was 78.23% with S3-FIFO, against 76.64% for quick-lru (which holds up to twice its configured size) and 73.59% for lru-cache. Where it is slower: inserting into a full in-memory cache costs 422 to 573 ns, against 182 to 221 ns for quick-lru and lru-cache, because every write measures the value, charges a shared memory budget and keeps an expiry time. A thundering herd on one process took 28.2 ms against 25.5 ms for async-cache-dedupe in the same session. Read-through over skewed traffic was level with async-cache-dedupe and about twice layered-loader. Not measured yet: Redis over a real network, many instances under load, production traces, throughput under many concurrent connections. ## Compared with other libraries From each library's own README at the version benchmarked (a feature a README does not mention is not proof the library lacks it): - Of the libraries compared (bentocache, cache-manager, cacheable, cachified, async-cache-dedupe, layered-loader), lazy-layers-cache is the only one whose README describes coordinating a load across processes with a distributed lease, waking waiting servers when it finishes, limiting L1 by bytes, and giving memory back under process pressure. - bentocache also has an in-memory L1 in front of a shared L2, a bus (Redis, RabbitMQ) that keeps peers' L1 in sync, grace periods, soft timeouts, tags, namespaces and Prometheus metrics with a Grafana dashboard, and more L2 drivers: Redis, Upstash, SQL, DynamoDB, file and Vercel KV. - cache-manager wraps any Keyv store, several at once, with `refreshThreshold` and `mget`. - cacheable has primary and secondary Keyv stores, CacheSync over pub/sub, tags, namespaces and `setMany` / `getMany`. - @epic-web/cachified uses one store per call (adapters for Redis, Cloudflare KV and SQLite) and supports stale-while-revalidate. - layered-loader has in-memory and Redis layers, Redis pub/sub or SQS sync, preemptive refresh, groups and bulk loads. Full table: https://lazy-layers-cache.vercel.app/docs/comparison ## Upgrading from 0.7 to 8.0 - Wire formats are unchanged, so 0.7 and 8.0 instances can share Redis and an event bus during a rolling deploy. - Redis, RabbitMQ, NATS and the native codecs are optional peer dependencies: install the ones you use. - The dashboard has no built-in credentials. Without configured credentials it generates a token. The `/observelazyily` alias route is removed. - Debug logging is opt-in (`logging.enabled`, `logging.env` or `LAZY_LAYERS_DEBUG`). - With the built-in L1, fail-safe snapshots are taken when a value expires from L1 or is evicted by the entry limit. - Read MIGRATION.md: https://github.com/Amon20044/LazyLayers/blob/main/MIGRATION.md ## Links - Website: https://lazy-layers-cache.vercel.app/ - Docs: https://lazy-layers-cache.vercel.app/docs - FAQ: https://lazy-layers-cache.vercel.app/docs/faq - GitHub: https://github.com/Amon20044/LazyLayers - npm: https://www.npmjs.com/package/lazy-layers-cache - Benchmarks: https://github.com/Amon20044/LazyLayers/blob/main/BENCHMARKS.md - Changelog: https://github.com/Amon20044/LazyLayers/blob/main/CHANGELOG.md - Short index for LLMs: https://lazy-layers-cache.vercel.app/llms.txt