Multi-tier layers
Build a cache from any number of layers: memory tiers with their own eviction policies, Redis, Cloudflare KV and your own stores, with per-layer limits, promotion rules, extensions and diagnostics.
A multi-tier cache keeps data in several stores ordered from nearest to farthest: process memory answers in nanoseconds, a shared store such as Redis lets every server reuse one load, and the database is asked only when every tier misses. In lazy-layers-cache, createCache({ layers }) builds that cache from an ordered list, nearest first, and each layer gets its own eviction policy, byte limit, TTL cap, deadline, concurrency limit and circuit breaker. Use it when two levels are not enough: a small hot set and a larger compact set in memory, a regional Redis in front of a global store, or a store of your own.
import { createCache, memory, redisLayer, kvLayer } from 'lazy-layers-cache'
const cache = createCache({
ttlMs: 60_000,
layers: [
memory({ maxEntries: 10_000, policy: 'sieve', valueMode: 'reference' }),
memory({ name: 'warm', maxMemory: '256MB', policy: 'lfu' }),
redisLayer({ client: redis, limits: { deadline: '50ms' } }),
kvLayer({ namespace: env.CACHE, promote: 'adaptive' }),
],
})The layers
| Layer | Made with | Scope | Notes |
|---|---|---|---|
| Layer 0 | the first memory() | process | The synchronous fast path. Same options as 8.x levels.L1. Leave it out to get one with defaults; memory({ enabled: false }) for none. |
| Extra memory tier | further memory() entries, right after layer 0 | process | Its own maxEntries, maxMemory and policy. Always stores encoded bytes. |
| Redis or Valkey | redisLayer({ client }) | region | Strongly consistent. Hands out leases, so it coordinates loads by default. |
| Cloudflare KV | kvLayer({ namespace }) | global | Eventually consistent: a write can take 60 s or more to reach other locations. Writes run in the background by default. |
| Anything else | storeLayer(store) | region | A store from defineStore, a built-in store, or any 8.x CacheStore. |
| By name | { use: 'redis', ... } | — | For configuration loaded as JSON. Add names with registerLayerType. |
memory() entries must come before every shared layer: an in-process layer behind a network layer is never faster, so that order is a configuration error.
Options of every non-memory layer
| Option | Default | What it does |
|---|---|---|
name | the adapter's kind, numbered if taken | Used in events, metrics and describe(). A duplicate name you wrote is an error. |
ttl | the cache's TTL | TTL of writes that bring none. |
maxTtl | none | Upper bound on any TTL written here, including promoted copies. |
promote | 'always' | 'always', 'never', 'adaptive' (after a second read) or { minHits: 1..15 }. |
admit | all values | { maxValueBytes, minValueBytes } by encoded size. A value this layer will not hold also removes its older copy. |
readOnly | false | Read, never written, deleted or promoted into. For shared replicas. |
write | 'await' | 'background' returns before this layer is written; writes for one key stay in order and are drained on close. Deletes are always awaited. |
limits | 64 in flight, 1,024 queued, 1 s | { maxConcurrent, maxQueue, deadline }. Past the queue, a call fails fast as overload. |
breaker | 5 failures, 5 s | { failureThreshold, cooldown }, or false. |
coordinator | the nearest layer with leases | Make this layer the lease coordinator. It must support leases. |
capabilities | detected | Override what the adapter can do, for stores that cannot be inspected. |
extensions | none | Custom properties; see below. |
Extra memory tiers accept name, promote, maxTtl and admit as well. On layer 0 those settings do not apply, since every read fills it; setting them there is reported as LAYER_OPTION_IGNORED.
How each operation moves through the layers
Read. Nearest layer first. A hit in a farther layer is copied into each promotable layer in front of it, in the background, unless this process changed the key while the read was in flight. If every layer fails, the read fails as unavailable and getOrSet calls your loader, so callers still get a value.
Write and delete. Farthest layer first, so a nearer layer is never left newer than a farther one. Promotable layers are swept once more shortly afterwards, to remove a copy that a concurrent reader promoted from a farther layer before the change reached it. The write fails only when no awaited layer accepted it.
Pattern delete. Each layer deletes by pattern. A layer that cannot, and a read-only layer, stop serving the keys the pattern covers instead.
Load. The coordinator hands out one lease per key. A server that misses everywhere checks the layers behind the coordinator before calling the origin; a hit there fills the coordinator under the same lease. A load whose lease was taken over by another server returns its value to its caller but stores nothing.
When a layer misbehaves
| What happens | What the cache does |
|---|---|
| A call exceeds the layer's deadline | Aborts it through the AbortSignal the adapter received, counts a timeout, moves on. |
| Repeated failures | Opens the breaker: the layer is skipped for the cooldown and shown as degraded. |
| A write or delete fails for a key | Remembers the key; the layer is not read for it until a retry succeeds (every 5 s, in batches). |
| The adapter returns bytes it never stored | Treats them as a miss and reports LAYER_CONTRACT. |
| Too many pending changes to track | Stops reading that layer for its longest TTL rather than risk serving an old value. |
Every one of these is bounded: repair sets, pattern blocks, background queues and the record of recent writes all have fixed limits.
Extensions: custom properties on a layer
Any layer, including memory, takes extensions: namespaced keys (vendor.name or x-name) with JSON values. Without a registered definition they are metadata, shown in describe(). With one, they are validated and can change the layer.
{
"layers": [
{ "use": "memory", "maxEntries": 10000, "extensions": { "lazy.owner": "platform" } },
{
"use": "redis",
"name": "primary",
"extensions": {
"lazy.label": "EU primary",
"acme.region": "eu-west-1",
"acme.encryption": { "keyId": "cache-2026" },
"x-ticket": "OPS-1287"
}
}
]
}Type your own keys by augmenting LayerExtensions, then define what they do:
import { defineExtension } from 'lazy-layers-cache'
declare module 'lazy-layers-cache' {
interface LayerExtensions {
'acme.region': 'eu-west-1' | 'us-east-1'
'acme.encryption': { keyId: string }
}
}
export const encryption = defineExtension({
key: 'acme.encryption',
description: 'Encrypts values at rest',
requires: { consistency: 'strong' },
kinds: ['redis'],
validate: (value) =>
typeof (value as { keyId?: unknown })?.keyId === 'string' ? undefined : 'needs a keyId',
mount: ({ keyId }) => ({
wrapStore: (store) => encryptingStore(store, keyId),
options: { maxTtl: '1h' }, // a default; what the user wrote wins
describe: { encrypted: true, keyId },
}),
})
createCache({ layers, extensions: [encryption] })None of this can break the cache. An unknown key, a key without a namespace, a value that fails validation, a layer that lacks a required capability, a value that is not plain JSON, or a mount that throws each becomes a diagnostic, and the layer runs without that extension. Pass strict: true to turn error diagnostics into a CacheConfigError at startup instead.
Writing a store
defineStore adapts any backend that can get, set and delete bytes. The cache adds expiry, encoding and the deadline signal.
import { defineStore, storeLayer, AdapterUnavailableError } from 'lazy-layers-cache'
const dynamo = defineStore({
name: 'dynamo',
capabilities: { consistency: 'strong' },
async get(key, { signal }) {
const item = await client.get({ Key: { pk: key } }, { abortSignal: signal })
return item?.value // Uint8Array or undefined
},
async set(key, value, ttlMs, { signal }) {
await client.put({ Item: { pk: key, value, ttl: Math.ceil((Date.now() + ttlMs) / 1000) } }, { abortSignal: signal })
},
async delete(key, { signal }) {
await client.delete({ Key: { pk: key } }, { abortSignal: signal })
},
mapError: (error) =>
isThrottle(error) ? new AdapterUnavailableError('dynamo', 'any', 'overload', { cause: error }) : error,
})
createCache({ layers: [memory(), storeLayer(dynamo, { promote: 'adaptive' })] })storeConformance from lazy-layers-cache/testing runs the same checks the built-in stores pass.
Diagnostics and description
cache.layers.describe() returns every layer as plain JSON: its kind, scope, state, eviction policy, promotion rule, capabilities, extensions and counters, plus the coordinator and the diagnostics. cache.layers.health() returns { ok, layers: [{ name, state }] }.
Each diagnostic has a stable code, a severity, the layer and path it is about, a message and usually a hint. They are written to the cache's logger at their severity, emitted as diagnostic events, and passed to onDiagnostic. DIAGNOSTIC_CODES explains each code:
| Code | Meaning |
|---|---|
EXTENSION_UNKNOWN | No registered extension handles this key; kept as metadata. |
EXTENSION_KEY_INVALID | The key is not namespaced; ignored. |
EXTENSION_INVALID | The value failed validation; not mounted. |
EXTENSION_UNSUPPORTED | The layer lacks a capability the extension needs; not mounted. |
EXTENSION_NOT_JSON | The value is not plain JSON; dropped. |
EXTENSION_MOUNT_FAILED | The extension threw while mounting; the layer runs without it. |
LAYER_DEFAULT_MEMORY | No memory layer was listed, so a default one was added. |
LAYER_NO_COORDINATOR | No layer can lease, so one load per key is per process, not per fleet. |
LAYER_PROMOTE_UNSAFE | A promotable layer sits in front of an eventually consistent one. |
LAYER_CONTRACT | An adapter returned something its contract forbids; treated as a miss. |
LAYER_TTL_CAPPED | A layer's ttl was above its maxTtl and was capped. |
LAYER_OPTION_IGNORED | A setting that does not apply to this layer. |
POLICY_FAILED | A custom eviction policy failed; the layer now evicts in insertion order. |
Problems that make the cache unable to work (an empty list, two layers with the same name, a memory layer after a shared one, an unknown layer type, a store that throws while being created, an invalid option) are collected and thrown together as one CacheConfigError, whose issues each carry a code, path, message and hint.
Questions
Does adding layers slow down a memory hit?
No. Layer 0 keeps the synchronous fast path, and the other layers are only touched on a memory miss. A warm hit measured 380 ns through layers and 373 ns through l1/l2 on the same machine.
What happens when a layer is slow or down?
Each layer has its own deadline (1 s by default), concurrency limit and circuit breaker. A read skips it and tries the next layer; the cache emits layer:error and layer:state events and reports the layer as degraded in cache.layers.health().
Can I keep using l1 and l2?
Yes. createCache({ l1, l2 }) works as in 8.x. layers is the alternative, and the two cannot be combined in one cache.
L1/L2 cache system design
Design a hybrid Node.js cache with in-memory L1 and Redis L2: trade-offs, sizing, TTLs, and when each layer is the right fit.
Eviction and value modes
How L1 decides what to evict (S3-FIFO by default, or LRU, SIEVE, FIFO or your own policy), how it stays within memory limits, and whether it stores copies or objects.