Introducing LazyLayers 9.0. Multi-layer caching, intelligent batching and outage recovery.

Explore what’s new

Give your database less work.

You only need getOrSet(key, () => load()). We handle the rest: memory, Redis, batching, stampedes and outages.

npm install lazy-layers-cache
Three app instances each keep a lime L1 memory chip. On the floor, lime paths join them to a shared violet L2, and the L2 to an orange origin database. Above them a teal event bus drops into every chip. In a loop, one value travels the whole way: the middle instance misses its L1 and asks L2, L2 asks the origin, the value is loaded once and comes back to that same instance, which then publishes it on the event bus into the other two, so their next reads are L1 hits. L1 MISS · ask L2 LOADED ONCE set user:42 L1 HIT L1 HIT L1 · in-process memory EVENT BUSRedis · NATS · RabbitMQ · MongoDB SHARED L2Redis · Cloudflare KV ORIGINyour database or API
  • 6,639
  • 500→8
  • 0 errors
  • 1,200→20
  • 169 ms
  • 15/15
  • 100→1
  • 191 ms
  • 1M→1
  • 47k/s
  • −90%
  • 287 MB
  • 71 ms

Inside getOrSet

Complex caching problems. Already handled.

500 keys. 8 script calls.

getOrSetMany reads Redis in one Lua script per 64 keys, then calls your loader once for every miss. Writes and deletes in the same tick batch too. On by default.

How batch scripts work
An app server sends ten calls for different keys along five thin lanes into a teal batching block. One thick lime packet carries them all to the violet Redis drum as a single Lua script, one reply comes back, and the block hands every caller its own value. Captions number each step. 1 · CALLS IN ONE TICK QUEUE UPreads, writes and deletes, any keys 2 · ONE SCRIPT PER 64 KEYSone EVALSHA instead of 64 3 · EVERY CALLER GETS ITS ANSWERwrites before reads, in the order made batchScriptson by default REDIS500 keys · 8 script calls

98.4%fewer Redis script calls: 8 instead of 500

await cache.getOrSetMany(ids, loadUsers)

Your infrastructure. Your layers.

getOrSet reads the nearest layer first: memory, a compressed warm tier, Redis, KV or your own store. Hits further down are copied closer. Each layer has its own size, eviction, deadline and breaker.

How reads move through layers
Four stacked layers: a lime L1 chip on top, a teal compressed warm tier, a violet Redis or KV slab, and the orange origin at the bottom. A read misses L1, finds the value in the warm tier, and it is promoted into L1 on the way back, so the next read is an L1 hit with no network call. 1 · L1 MISSESthe warm tier has it 2 · COPIED CLOSERpromoted into L1 on the way back 3 · NEXT READ: L1 HITno network, no decode L1hot memory · S3-FIFO WARMcompressed memory · LFU REDIS / KVshared by every server ORIGINyour database or API

0network round trips when memory has the value

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

Hot data, served from memory.

Repeat reads of a hot key return from process memory, with no network call. In reference mode you get the stored object back, with nothing to decode.

Trace the read path
A request reaches an app instance and its lime L1 chip answers at once. The shared L2 drum beside it is faded because the read never needed it. L1 hit · no network L2 NOT NEEDED

180 nsper warm hit in reference mode, Apple M5

await cache.getOrSet(`product:${id}`, () => db.products.find(id))

1,200 callers. 20 origin loads.

When many requests miss one key, one load runs and every caller gets its result: in-flight dedupe inside a process, a Redis lease across servers.

How the Redis lease works
Three app instances ask a Redis drum for the lease on one key. The first gets it, loads once from the origin and stores the value. The other two are then woken with that value. LEASE REDIS LEASE ORIGIN · LOADED ONCE

20origin loads for 1,200 callers across 6 servers

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

Redis stopped. Your app didn’t.

Redis or the bus down? Reads fail open to memory and your loader. Loader down too? You get the last good value. When Redis is back, missed writes are repaired and missed invalidations replayed.

How fail-open works
Three app instances share a violet Redis drum and a teal event bus. Redis freezes and a write from the first instance cannot land, while the other instances keep answering reads. When Redis returns it is probed at once, the missed write is repaired, and the missed invalidation is replayed over the bus into both peers, which show a check. 1 · REDIS FREEZESreads fail open to memory and the loader 2 · REDIS IS BACKprobed at once, not after a cooldown 3 · REPAIRED AND REPLAYEDmissed writes rewritten, missed invalidations sent Redis Streams outbox 0 ERRORS IN A 4 S FREEZE

0 errorswhile Redis froze for 4 s on 6 servers

await cache.getOrSet(key, load, { failSafe: { staleTtlMs: 60_000 } })

Memory that knows what to let go.

Memory gets a byte budget. Near the heap or container limit, the cache gives memory back on its own: stale copies first, then what your policy values least. S3-FIFO, LFU, SIEVE, LRU or FIFO.

How memory limits work
An L1 cache drawn as a tray of slots beside a glass column of process memory. Writes drop into free slots and the column rises. When the tray is full, the policy evicts its coldest key to make room. When process memory crosses the 85% heap line, amber stale fail-safe copies leave first, then the policy evicts one more fresh entry, and the column falls back. Captions number each step. 85% heap 1 · WRITES FILL THE BUDGETeach entry is charged its real size 2 · BUDGET FULLthe policy evicts its coldest key 3 · MEMORY PRESSUREthe V8 heap passed 85% of its limit 4 · STALE COPIES GO FIRSTfail-safe snapshots are the cheapest bytes 5 · THEN THE POLICY’S PICKthe least valuable fresh entry 6 · MEMORY GIVEN BACKroom returns once memory is normal L1 · maxMemoryany policy: S3-FIFO · LFU · SIEVE · LRU · FIFO PROCESS MEMORYheap · RSS · container

78.2%hit ratio on skewed traffic with S3-FIFO

await cache.getOrSet(`report:${id}`, () => buildReport(id))

Stop draining your connection pool.

A hit never borrows a connection from your Postgres, MySQL, SQLite or MongoDB pool. On a miss, only a few loads run at once, shared fairly across tenants. The rest wait briefly in your app.

How origin slots work
An app server, a gate with three slots, and a database marked with Postgres, MySQL, SQLite and MongoDB logos. Requests that hit memory bounce straight back without reaching the gate. Three misses reach the gate: two pass through its slots to the database while the third waits in front, then follows. The values come back and are cached. Last, a write travels to the database and the server drops its cached copy. Captions number each step. QUEUED 1 · HITS NEVER TOUCH THE POOLanswered from memory in this process 2 · LOADS ARE CAPPEDa full gate queues the rest, so the pool never runs dry 3 · ONE QUERY, CACHEDthe next reads are hits again 4 · WRITE, THEN INVALIDATEevery server drops its copy of the key originLoadmaxConcurrent · maxQueued ANY DATABASEyour loader runs the query

32loads at once per process by default

await cache.getOrSet(key, () => pool.query(sql))

Change it once. Every server hears it.

Tag what you load. Invalidate a key, pattern or tag once and every server drops its copy, over Redis Streams, Pub/Sub, NATS, RabbitMQ, Durable Objects or MongoDB.

How invalidation travels
Three app instances hang from a teal event bus. A write on the first travels along the bus and drops into the other two, which show a check mark and version v2. WRITE v2 v2 v2 invalidate · prime · fan out

0.8 msuntil a waiting server has a value another loaded

await cache.getOrSet(key, load, { tags: [`tenant:${tenantId}`] })

Get started

Start building in minutes

With your AI coding tool

npx skills add Amon20044/LazyLayers

Then ask your agent:

By hand

npm install lazy-layers-cache
cache.ts
import { setupCache } from 'lazy-layers-cache'

interface User { id: number; name: string }

const cache = await setupCache<string, User>({ redis: false })
const user = await cache.getOrSet('user:42', () => db.users.find(42))

Benchmarks · v9.0.0

Engineered to do less. Built to handle more.

98.4%fewer Redis script calls

500 keys in one tick: 8 Lua scripts, not 500.

19×faster pattern delete

invalidateByPattern on 500 keys.

63%shorter worst event-loop stall

256 KiB to 1 MiB values, compressed off the event loop.

20origin loads for 1,200 callers

6 servers, 20 cold keys: one getOrSet load per key.

Redis script calls for 500 keys

Bulk writes
off500on8
Bulk reads
off500on8
Concurrent reads
off500on8
Bulk deletes
off500on8
Pattern delete
off500on8

Sources: redis-batch.json (2026-12-04, median of 5) and the fleet run.

Features

One call. Production built in.

Unlimited cache layers

Memory, a warm tier, Redis, KV or your own store, read nearest first.

// L1 → warm → Redis → origin
cache.getOrSet(key, load)
Learn more

Intelligent batching

One Lua script per 64 keys for reads, writes and deletes.

// 500 keys, 8 Lua scripts
cache.getOrSetMany(ids, loadUsers)
Learn more

Outage recovery

Fails open, serves the last good value, repairs what Redis missed.

cache.getOrSet(key, load, {
  failSafe: { staleTtlMs: 60_000 },
})
Learn more

Distributed coordination

One load per missing key across every server that shares Redis.

cache.getOrSet(key, load, {
  distributedLock: { ttlMs: 5_000 },
})
Learn more

Off-thread compression

Large values compress on the libuv pool, not the event loop.

// a 1 MiB value, compressed off-thread
cache.getOrSet(key, buildReport)
Learn more

Fair origin scheduling

Waiting loads are served round-robin across tenants.

cache.getOrSet(key, load, {
  originLoad: { tenant: byTenant },
})
Learn more

Adaptive freshness

Reload hot keys before they expire, while callers keep reading.

cache.getOrSet(key, load, {
  earlyRefresh: 0.8,
})
Learn more

Custom Lua execution

Your own Lua on cache keys, fenced against loads in flight.

// fenced against getOrSet loads
cache.runScript('touch', [key], [600_000])
Learn more

Intelligent eviction

A byte budget, with S3-FIFO, LFU, SIEVE, LRU or FIFO.

// evicts by LFU inside maxMemory
cache.getOrSet(key, load)
Learn more

Distributed event buses

Loaded values reach every server: Redis Streams, Pub/Sub, NATS, RabbitMQ.

// every peer gets the loaded value
cache.getOrSet(key, load)
Learn more

Tags and patterns

Invalidate a group of keys without scanning for them.

cache.getOrSet(key, load, {
  tags: ['tenant:42'],
})
Learn more

Observability

Every hit, miss and load is an event, with Prometheus metrics.

// emits hit, miss and load events
cache.getOrSet(key, load)
Learn more

Compared

What you get that others leave to you

FeatureLazy Layers8.0.0bentocache1.6.1cache-manager7.2.9cacheable2.5.0cachified5.6.3async-cache-dedupe3.4.0layered-loader17.0.0
Memory L1 in front of a shared L2one storeone store
One load per key per process
One load per key across servers······
Waiting servers woken when the load ends······
Peer L1 caches kept in sync over a bus···
Peers warmed with the loaded value·····
Stale value when the origin fails·····
Stale-while-revalidate··
Invalidate by tag··partialgroups
Invalidate by pattern······
L1 limited by bytes and process memory······
Cloudflare Workers···KV adapter··
Prometheus metrics·····
Rows fully covered13/137/132/135/132/132/134/13

Read from each library’s README at the version benchmarked, on 2026-11-12. A dash means the README does not mention it, which is not proof the library lacks it. Full table with sources

Cache your next database query.

By hand

npm install lazy-layers-cache

With your AI coding tool

npx skills add Amon20044/LazyLayers