LazyLayersv9.0.0

Introduction

A multi-layer cache for Node.js and Cloudflare Workers: memory tiers in front of Redis, Cloudflare KV or your own store, read through with getOrSet, kept correct across a fleet.

lazy-layers-cache (LazyLayers) is an open-source multi-layer cache for Node.js and Cloudflare Workers. You stack cache layers nearest first (process memory, a larger memory tier, Redis, Cloudflare KV, a Durable Object tier or a store you write), read through all of them with one getOrSet call, and the cache keeps every server's copy correct after a write. It is MIT-licensed, written in TypeScript, and has one runtime dependency.

import { createCache, memory, redisLayer } from 'lazy-layers-cache'

const cache = createCache({
  layers: [
    memory({ maxEntries: 10_000 }),                      // this process, no decode
    memory({ name: 'warm', maxMemory: '256MB' }),        // larger, compact bytes
    redisLayer({ client: redis, limits: { deadline: '50ms' } }), // shared by every server
  ],
})

const user = await cache.getOrSet(`user:${id}`, () => db.users.find(id))

These docs describe lazy-layers-cache 9.0.0. The wire format is unchanged, so 8.0 and 9.0 servers can share Redis and an event bus during a rolling deploy. Read the changelog and the migration guide before upgrading.

Start here

How does a read work?

A read asks the nearest layer first. Process memory answers without a network call; the warm read-through hit in BENCHMARKS.md costs 180 ns in reference mode. On a miss, the next layer is asked, and a hit there is copied into the nearer layers, always or only once a key is read twice. When every layer misses, getOrSet calls your loader once: concurrent callers in the process share that call, and a Redis lease makes one server load the key for the whole fleet while the others wait for its value. In one recorded run, 10,000 concurrent callers on one cold key ran the loader once.

Each layer after the first has its own deadline, concurrency limit and circuit breaker, so a slow or failing Redis is skipped rather than slowing every read. A write goes farthest first, so a nearer layer is never newer than a farther one.

What does each part do?

PartWhat it does
Memory layersKeep values in the process, limited by entries and bytes, with S3-FIFO eviction by default (LRU, LFU, SIEVE, FIFO or your own)
Shared layersShare values between servers: Redis, Cloudflare KV, a Durable Object tier, or a store you write with defineStore
LeasesLet one server load a missing key for the fleet; the rest are woken when it lands
Event busTells peers to drop a changed key: Redis Pub/Sub, a Redis Streams outbox, RabbitMQ, NATS, Durable Objects or MongoDB change streams
CoordinationOptional locks, counters, rate limits and invalidation without Redis, on Durable Objects or MongoDB

What is new in 9.0?

ChangeWhat it gives you
LayersAny number of layers, each with its own policy, byte limit, TTL cap, deadline and breaker
LFU evictionA built-in policy for traffic where long-term popularity predicts the next read
Redis Streams outboxInvalidations published during an outage are replayed, not lost
Resent invalidations and L2 repairA delete the bus missed is sent again, and a write Redis missed is repaired once it is back
Batch scriptsReads, writes and deletes issued together run as one Lua script per 64 keys: 500 keys, 8 script calls
Your own Luacache.runScript runs Lua on cache keys, fenced against loads in flight
Off-thread compressionLarge values are compressed on the libuv pool, not the event loop
Fair origin loadingOne tenant's burst cannot take every origin slot

How does it behave when something fails?

It fails open: an unreachable layer is treated as a miss, a failing loader can be answered with a recent value, and nothing a cache adapter throws reaches your request. In a recorded run of six servers, each in its own container (BENCHMARKS.md):

  • a 4 s Redis freeze caused no errors, and with the Streams bus no sampled read was more than 56 ms stale;
  • 1,200 callers asking for 20 cold keys across the fleet caused exactly 20 origin loads;
  • moving large values' compression off the main thread cut the worst event-loop stall from 461 ms to 169 ms.

During a Sentinel or Cluster failover, a server cut off from Redis cannot tell its peers about a write until it reconnects, so a few reads were up to 3 to 4 s stale. The database stays the source of truth: use the cache for reads that tolerate the freshness you configure.

Choose the page for your task

TaskRead
Check runtime, modules, or TypeScript requirementsInstallation
Deploy a service with RedisProduction setup
Stack memory tiers, Redis and your own storesMulti-tier layers
Use Cloudflare KV from Workers or Node.jsCloudflare KV system design
Set memory and freshness limitsConfiguration
Handle slow loaders or dependency failuresFailure handling
Inspect entries, events, and metricsObservability
Coordinate a durable payment or order attemptTransaction coordination
Compare it with bentocache, cache-manager, lru-cache and othersComparison
Find a short answerFAQ

Where to next

Questions

What is a multi-layer cache?

A multi-layer (or multi-tier) cache keeps the same data in several stores ordered from nearest to farthest, for example process memory, a larger compressed memory tier, then Redis. A read checks the nearest layer first and copies a farther hit into the nearer layers; a write goes to every layer. The nearest layer answers in nanoseconds, the shared layer lets every server reuse one load, and the database is only asked when every layer misses.

When should I use lazy-layers-cache instead of plain Redis?

When the same keys are read far more often than they change, and Redis latency, Redis load or the cost of a cold key matters. An in-process hit avoids the network entirely, getOrSet makes one server load a missing key for the whole fleet, and the event bus drops stale copies from every server's memory after a write. If every read must see the latest write, read the database instead.

What is new in lazy-layers-cache 9.0?

Caches built from any number of layers, each with its own eviction policy, limits and failure handling; LFU eviction; a Redis Streams outbox that replays invalidations after an outage; invalidations and Redis writes that are resent or repaired once a failed dependency is back; Redis calls batched into Lua scripts; Lua scripts of your own with runScript; compression off the main thread; and fair origin loading across tenants. It was tested with six servers under Redis freezes and failovers.

Is lazy-layers-cache production ready?

It has more than 950 automated tests, including tests against a real Redis, and BENCHMARKS.md records a fleet of six servers under real faults: a 4 s Redis freeze, Sentinel and Cluster failovers and a crashed lease holder, with no errors except 13 lock timeouts during the Cluster failover. Known limits, such as the stale-read window while a failover is in progress, are written down there too.

On this page