# Configuration (https://lazy-layers-cache.vercel.app/docs/reference/configuration)

> Every option, its exact type, its real default, and what it costs you when it is wrong.



`setupCache` is the production entry point for Node.js. It accepts the full `LazyLayersCache` option surface, resolves L1, a configured Redis or Cloudflare KV L2, and an optional event bus, then applies the bounded setup defaults called out below. The subset that also exists on `CacheOptions` can be overridden per call on `getOrSet` or `prewarm`.

<CodeGroup>
  ```js title="src/cache/index.js"
  import { setupCache } from 'lazy-layers-cache'

  export const cache = await setupCache({
    namespace: 'billing-api',
    redis: { required: true },
  })
  ```

  ```ts title="src/cache/index.ts"
  import { setupCache, type SetupCacheOptions } from 'lazy-layers-cache'
  import type { User } from '../types/user.js'

  const options: SetupCacheOptions<string, User> = {
    namespace: 'billing-api',
    redis: { required: true },
  }

  export const cache = await setupCache<string, User>(options)
  ```
</CodeGroup>

`new LazyLayersCache(options)` remains the low-level constructor. It never creates external infrastructure. Where its defaults differ from `setupCache`, this page names both.

<Warning>
  Keep origin, memory and follower budgets finite. Choose stale serving according to the application's freshness contract: `failSafe: { enabled: false }` is appropriate when stale authorization or other security-sensitive state is forbidden. Disabling singleflight or broadcasting changes backend load/coherence and should be a measured integration decision.
</Warning>

## Lifetime and layers [#lifetime-and-layers]

<ParamField path="ttlMs" type="number" default="3600000">
  Fallback lifetime for every entry, in milliseconds. One hour. Set too high, you serve stale data between invalidations. Set too low, your hit rate collapses and the origin absorbs the difference.
</ParamField>

<ParamField path="ttlJitter" type="number" default="0">
  Scales each write's TTL by a random factor in `[1 - ttlJitter, 1 + ttlJitter]`, the same factor for L1 and L2, so keys written together do not expire together. A fraction from 0 up to, but not including, 1; `0.1` is typical.
</ParamField>

<ParamField path="earlyRefresh" type="number">
  Reloads a value in the background before it expires. With `0.8`, the first `getOrSet` hit after 80% of the value's lifetime (the L2 TTL when there is an L2, otherwise the L1 TTL; when the cache configures no TTL, the store's own) returns the cached value and reloads the key once, through the usual deduplication, origin gate and distributed lock. A reload that fails or finds nothing is retried halfway to expiry. A fraction strictly between 0 and 1. Off by default. See [early refresh](/docs/guides/batches-and-freshness#early-refresh).
</ParamField>

<ParamField path="adaptiveTtl" type="{ minMs?: number; maxMs?: number; factor?: number; maxKeys?: number; fingerprint?: (value) => string | number | bigint }">
  Sets each key's TTL from how often its value changes: `factor` (default `0.5`) times the observed change interval, or times how long the value has been unchanged when that is longer, clamped to `[minMs, maxMs]` (default 1 s to 1 h). Applies to writes without their own TTL, with `ttlJitter` on top. History is kept for `maxKeys` keys (default 10,000). Without `fingerprint`, a hash of the stored bytes decides whether a value changed. Off by default. See [keeping keys fresh](/docs/concepts/freshness#adaptive-ttl).
</ParamField>

<ParamField path="refresh" type="{ sources?: RefreshSource | RefreshSource[]; maxKeys?: number }">
  Where reload signals for `keepFresh` keys come from, such as `redisExpirySource(redis, { store })`. `maxKeys` bounds how many keys `keepFresh` may register (default 10,000). A source that fails is logged and left out. `cache.refresh(key)` works without any source. See [keeping keys fresh](/docs/concepts/freshness).
</ParamField>

<ParamField path="offThread" type="false | { minBytes?: number; maxInFlight?: number }" default="{ minBytes: 65536, maxInFlight: 2 × UV_THREADPOOL_SIZE }">
  Constructor only. Compresses and decompresses large shared-layer values on the libuv thread pool instead of the event loop, so one large value does not stall every other request. A value is still packed to MessagePack on the calling thread; only its compression moves. `minBytes` is the smallest packed payload sent to the pool (decompression uses a quarter of it, measured on the compressed body): below 64 KiB the hop to another thread costs more than it saves. At most `maxInFlight` jobs (8 with the default pool of 4 threads) run at once; past that, work runs inline rather than queueing. The stored bytes are identical either way, a failed compression stores the value uncompressed, and a record that fails to decompress is a miss. A memory hit on an encoded L1 still decodes on the calling thread; use `levels.L1.valueMode: 'reference'` for large values read often. `cache.offThreadStats()` reports `{ offloaded, saturated, inFlight }`. `false` turns it off.
</ParamField>

<ParamField path="tags" type="readonly string[]">
  Per call, on `set`, `getOrSet`, `setMany` and `getOrSetMany`: labels for the value, so `invalidateTags(tags)` can invalidate it with every other value sharing a tag. At most 32 tags, each up to 256 characters. A `getOrSet` with tags serves only a value stored with all of them, and loads any other again. See [invalidating by tag](/docs/concepts/invalidation#invalidating-by-tag).
</ParamField>

<ParamField path="tagCheckMs" type="number" default="1000, or the L1 TTL when shorter">
  Constructor only. With a shared L2 and no event bus, how long a server trusts a tag token it read before reading it again: other servers see an `invalidateTags` within this time. Tokens in steady use are read again in the background, so reads do not wait. `0` reads the tokens before every read of a tagged value. Not used with a trusted bus, which announces each invalidation.
</ParamField>

<ParamField path="staleWhileRevalidate" type="boolean" default="false">
  When a key has expired but its fail-safe snapshot is still held, `getOrSet` returns the snapshot at once and refreshes the key in the background. Needs fail-safe enabled; the window is `failSafe.staleTtlMs`. See [stale-while-revalidate](/docs/guides/batches-and-freshness#stale-while-revalidate).
</ParamField>

<ParamField path="levels.L1" type="{ maxEntries?: number; ttlMs?: number; maxMemory?: MemoryLimit; minMemory?: MemoryLimit; maxProcessMemory?: MemoryLimit; autoEvict?: { enabled?: boolean }; admission?: { enabled?: boolean; maxEntryBytes?: number }; policy?: EvictionPolicyOption; valueMode?: 'encoded' | 'reference'; sizeOf?: (value) => number; freezeValues?: boolean }">
  The in-process layer. `maxEntries` defaults to `1000`. `setupCache` sets `ttlMs` to 10 seconds. The low-level constructor falls back to the cache-wide `ttlMs`, then to one hour.

  The L1 enforces a shared byte budget as well as an entry count.
</ParamField>

<ParamField path="levels.L1.policy" type="'s3fifo' | 'lru' | 'sieve' | 'fifo' | string | EvictionPolicyFactory" default="'s3fifo'">
  Which resident entry leaves when L1 needs room. Eviction is always automatic; the policy decides which entry is least valuable. `s3fifo` had the lowest miss ratio across the policy matrix; `lru` is better only when the whole popular set is replaced at once and fits in the cache. Pass a factory such as `s3fifoPolicy({ promoteAfterHits: 2 })` or `sievePolicy({ maxVisits: 3 })`, or a name added with `registerEvictionPolicy`. See [eviction and value modes](/docs/concepts/eviction).
</ParamField>

<ParamField path="levels.L1.valueMode" type="'encoded' | 'reference'" default="'encoded'">
  `encoded` keeps values in wire form: every read is a private copy and bytes are counted exactly. `reference` keeps the object itself and returns it without decoding, roughly ten times faster on a hit; callers must not modify returned values.
</ParamField>

<ParamField path="levels.L1.sizeOf" type="'estimate' | 'encoded' | (value: unknown) => number" default="'estimate'">
  `reference` mode only. How a stored object is charged to the memory budget. `'estimate'` walks it once and computes its heap size from V8's object layout: within 3% of measured heap for values that own their contents, and high where V8 shares short strings between values. See [how reference-mode values are sized](/docs/concepts/eviction#how-reference-mode-values-are-sized). `'encoded'` encodes it once and charges the exact encoded size; it is slower and rejects values that cannot be encoded. A function returns the bytes yourself.
</ParamField>

<ParamField path="levels.L1.freezeValues" type="boolean" default="true outside production">
  `reference` mode only. Deep-freeze stored values so an accidental mutation fails instead of changing what other callers read.
</ParamField>

<ParamField path="levels.L2" type="{ maxEntries?: number; ttlMs?: number; codec?: CacheCodecOptions }">
  The shared layer. `ttlMs` falls back to the cache-wide `ttlMs`, then to one hour. Keep it well above L1's, because L2 is what survives a deploy.

  `maxEntries` has no default. When set, `RedisStore` enables its optional namespace index and trims the oldest expiry entries on write. This is a bounded, best-effort cache policy under concurrent writers, not a transaction quota.
</ParamField>

<ParamField path="l1" type="CacheStore<K, V> | false">
  A custom in-process store, or `false` to run without one. Defaults to a `MemoryStore` built from your options.

  Disabling L1 costs you a network round trip on every single read, which is most of what you came here for. The one honest reason is a process where a stale local copy is unacceptable for the length of an L1 TTL.
</ParamField>

<ParamField path="l2" type="CacheStore<K, V> | false">
  The shared store. `setupCache` creates a `CloudflareKVStore` when `kv` is set, otherwise a `RedisStore` when a Redis client or URL is available. An explicit `l2` takes precedence. The low-level constructor has no L2 default.
</ParamField>

<ParamField path="kv" type="SetupCloudflareKVOptions | false">
  Pass `{ namespace: CloudflareKVNamespace, store?: CloudflareKVStoreOptions }` to select Cloudflare KV for L2. An explicit KV selection suppresses implicit `REDIS_URL` discovery. Setup checks the namespace with a bounded `list` request and defaults L2 serialization to Worker-compatible HC1 MessagePack with adaptive gzip. `store.compression` defaults to `auto`; set it to `none` to skip compression attempts. Set `redis` explicitly if you also need its Pub/Sub bus. [Cloudflare KV setup](/docs/setups/cloudflare-kv) covers Workers, Node.js, and cost trade-offs.
</ParamField>

<ParamField path="invalidationPublisher" type="CloudflareInvalidationPublisher">
  Optional managed-cache Queue publisher for application invalidations. It acts after local deletion. Node.js can use `CloudflareQueueRestSender`, while a Worker uses a Queue binding. [Application invalidation Queue](/docs/setups/cloudflare-kv#application-invalidation-queue) explains the consumer and delivery limits.
</ParamField>

<ParamField path="versioning.enabled" type="boolean" default="false">
  Appends `::v{generation}` to the storage key, so a delete moves the whole key to a new namespace instead of racing a redelivered write.

  It costs you: after every delete the old versioned entry is orphaned in L2 until its TTL expires, so your L2 holds more keys than your logical keyspace. This is read from the constructor options only, so a per-call `versioning` is ignored.
</ParamField>

TTL resolution runs most specific to least: per-call level, per-call `ttlMs`, constructor level, constructor `ttlMs`, then, for L2, the store's own TTL, then the one hour default. The resolved TTL is passed to the L2 store with every write, so a `RedisStore` built with a different `ttlMs` follows the cache's.

### Sizing L1 [#sizing-l1]

`maxEntries` is still a count. `maxMemory` is the shared process-local byte ceiling for built-in L1 stores, expressed as bytes or a percentage of the effective host or cgroup memory. It defaults to `20%`. `minMemory` sets the lower floor used during pressure recovery. `admission.maxEntryBytes` rejects one oversized value before it evicts a useful working set.

`autoEvict` samples free memory, cgroup pressure, the V8 heap and RSS every 5 seconds, and lowers the target to a share of what the cache holds while pressure lasts. Writes evict to fit whether or not it is enabled, and check the V8 heap and RSS every 1,024 reservations. A `maxMemory` above 75% of effective memory is lowered to 75%. `maxMemory` bounds what the cache holds; `maxProcessMemory` bounds the process, and defaults to effective memory, so the cache gives memory back as the process nears its container limit. See [memory limits and pressure](/docs/concepts/eviction#memory-limits-and-pressure).

| Typical value      | Rough size | 10,000 entries | Reasonable ceiling |
| ------------------ | ---------- | -------------- | ------------------ |
| Session or flag    | \~200 B    | \~2 MB         | 50,000+            |
| User record        | \~2 KB     | \~20 MB        | 10,000             |
| Rendered list page | \~18 KB    | \~180 MB       | 1,000              |

Under Node clustering, every worker keeps its own L1 and process-local byte budget. Divide the host allowance across workers or give each container an explicit memory limit. Lazy Layers does not coordinate one host-wide budget.

<ParamField path="memoryBudget" type="MemoryBudget">
  Share an explicit `MemoryBudget` between cache instances in the same process. Without one, built-in `MemoryStore` instances use the process default budget. Set this at construction time, not per call.
</ParamField>

### RedisStore options [#redisstore-options]

Passed to the `RedisStore` constructor, not to the cache.

<ParamField path="prefix" type="string" default="cache:">
  Namespaces logical keys. The v2 layout adds its version prefix and hash tag before this namespace. Two applications sharing a Redis instance with the same prefix will invalidate each other's keys.
</ParamField>

<ParamField path="indexKey" type="string" default="`${prefix}__index`">
  The optional sorted set that tracks live keys by expiry deadline. Change it only if it collides with something you already store.
</ParamField>

<ParamField path="useIndex" type="boolean" default="false">
  Maintain the index so pattern deletes and `size` use `ZSCAN` instead of scanning the whole keyspace. `levels.L2.maxEntries` selects it automatically. Leave it off when Redis-native TTL and operator-managed eviction are sufficient.
</ParamField>

<ParamField path="scanCount" type="number" default="1000">
  Keys per scan step. Higher finishes sooner and blocks the Redis event loop for longer per step.
</ParamField>

<ParamField path="batchSize" type="number" default="500">
  Keys per delete pipeline. Raising it makes a large invalidation one long stall instead of several short ones.
</ParamField>

<ParamField path="deleteStrategy" type="'unlink' | 'del'" default="unlink">
  `unlink` frees memory on a background thread, so a large delete does not block the Redis event loop. Choose `del` only for a Redis older than 4.0.
</ParamField>

<ParamField path="keyLayout" type="'auto' | 'legacy' | 'v2'" default="'auto'">
  `auto` uses v2 per-entry, same-slot data and lease keys when Redis scripts are available. The v2 and legacy layouts do not dual-read. Drain or backfill the legacy namespace before moving all writers to `v2`.
</ParamField>

<ParamField path="batchScripts" type="{ maxKeys?: number; maxBytes?: number } | false" default="{ maxKeys: 64, maxBytes: 1 MiB }">
  Reads, writes and deletes issued in the same tick run as one Lua script per 64 keys or 1 MiB of payload, instead of one script each. A burst of 500 reads makes 8 script calls, not 500, and a pattern delete of 500 keys takes one script per 64 keys instead of one round trip per key. Writes and deletes of one key keep the order they were made in, and a batched write fences a load in flight exactly as a single write does. A batched read returns at most about 8 MiB; keys past that are read on their own.

  Redis runs one script at a time, so `maxKeys` also bounds how long one script holds Redis: 64 keys take well under a millisecond. Used with the v2 layout on standalone Redis and Sentinel. Redis Cluster keeps one script per key, since each key has its own slot. `false` runs one script per call.
</ParamField>

<ParamField path="scripts" type="Record<string, { lua: string; writes?: boolean; readOnly?: boolean; buffers?: boolean }>">
  Lua scripts of your own, run with `cache.runScript(name, keys, args)` (or `store.runScript`). In the script, `KEYS[1..n]` are the Redis keys of the n cache keys you pass and `KEYS[n+1..2n]` their lease keys; `ARGV` holds your arguments. Values are stored in the cache's own encoding, so a script works best on TTLs, existence and keys of its own; read and write cached values through the cache.

  With `writes: true`, the script is fenced: it deletes the lease keys after it runs, so a load in flight on any server cannot write over the change. `cache.runScript` then drops the keys from memory here and tells peers to drop theirs, so the next read sees what the script left in Redis. `readOnly: true` marks a script that only reads, so ioredis may send it to a replica; leave it unset for anything that writes, `PEXPIRE` included. `buffers: true` returns bulk replies as Buffers. Errors reach the caller. The [Lua scripts guide](/docs/guides/redis-lua-scripts) has more examples.

  ```js
  const cache = await setupCache({
    redis: {
      store: {
        scripts: {
          // Extend the TTL of keys that exist, and report which did.
          touch: {
            lua: `local out = {}
                  for i = 1, #KEYS / 2 do out[i] = redis.call("pexpire", KEYS[i], ARGV[1]) end
                  return out`,
          },
        },
      },
    },
  })
  const touched = await cache.runScript('touch', ['user:1', 'user:2'], [60_000])
  ```
</ParamField>

## Stampede protection [#stampede-protection]

<ParamField path="inflight.enabled" type="boolean" default="true">
  Collapses concurrent callers for one key into a single loader call. Ten thousand simultaneous requests for a cold key produce one query.

  Already on. Setting it to `false` hands every concurrent caller its own loader call, which is the exact thundering herd this library was built to stop.
</ParamField>

<ParamField path="inflight.ttlMs" type="number" default="derived">
  How long an in-flight promise stays joinable. By default this covers the loader hard timeout, the distributed wait budget when locking is active, and a 50 ms margin, with a 5,000 ms minimum. Defaults are 10,050 ms without locking and 20,100 ms with Redis locking. Settled entries are removed immediately.

  An explicit value overrides the derived lifetime. Setting it too low allows a later caller to start another load while the original is still active.
</ParamField>

<ParamField path="inflight.maxEntries" type="number" default="1024">
  Bounds tracked keys. Managed setup can override this default; finite leader/origin admission still applies to untracked loads.

  Past the cap, loads still run, just without dedupe, and each one emits `inflight:bypass`. Setting it to `0` bypasses tracking for every load, which disables dedupe entirely.
</ParamField>

<ParamField path="inflight.maxWaiters" type="number" default="10000">
  Maximum accepted outstanding followers across one cache. Overflow throws `InflightOverloadError` and starts no additional loader. A per-call limit can tighten the constructor budget. Accepted followers release their reservation on success or error; active ignoring-abort work remains accounted until it settles.
</ParamField>

<ParamField path="decodeLimits" type="DeserializeOptions">
  Built-in internal reads default to 25 MiB encoded/expanded limits, depth 128 and 1,000,000 collection/aggregate values. Corrupt, unsupported, invalid UTF-8 or oversized records are misses; valid cached `null` remains a hit. The public one-argument deserializers retain legacy behavior. Redis v2 snapshots require `STRLEN` ACL permission to reject large values before returning their bytes.
</ParamField>

<ParamField path="originLoad" type="{ enabled?: boolean; maxConcurrent?: number; maxQueued?: number; queueTimeoutMs?: number; tenant?: (key) => string; perTenant?: { maxConcurrent?: number; maxQueued?: number } }">
  Bounds concurrent executions that reach the origin loader. Defaults are 32 active loaders, 1024 queued distinct keys, and a 1000 ms queue deadline. In-flight dedupe runs before this gate, and waiting for a distributed lock does not consume an origin slot.

  With `tenant`, waiting loads are served round-robin across tenants and in order within one, so a burst of misses from one tenant cannot make the others wait behind it. `perTenant` caps the slots and queue places one tenant may hold. A `tenant` function that throws puts the key in a shared default tenant.
</ParamField>

<ParamField path="negativeCache.enabled" type="boolean" default="true">
  Remembers that a loader returned `undefined`, so a missing row is not a free pass to hammer the origin on every retry.

  On by default with a 10 second TTL.
</ParamField>

<ParamField path="negativeCache.ttlMs" type="number" default="10000">
  How long a recorded miss suppresses the loader.

  Too long and a row created a second after the miss stays invisible for the rest of that window. Seconds, not minutes.
</ParamField>

<ParamField path="negativeCache.maxEntries" type="number" default="10000">
  Caps remembered misses. Eviction here is oldest-inserted, not LRU.
</ParamField>

<ParamField path="distributedLock.enabled" type="boolean" default="true">
  Serializes cold loads for one key across **servers**, not just within a process. In-flight dedupe already covers one process. This covers the case where fifty servers all miss the same key at the same instant.

  Requires an L2 that implements `acquireLock` and `releaseLock`, which `RedisStore` does. Without one, it is a no-op. With Redis L2, every cold load uses the per-key lock unless you explicitly opt out.
</ParamField>

<ParamField path="distributedLock.ttlMs" type="number" default="10000">
  Lease lifetime. RedisStore renews it automatically while the load and write are active. Custom stores without `renewLock` must finish within this lifetime.
</ParamField>

<ParamField path="distributedLock.waitTimeoutMs" type="number" default="derived">
  Maximum contention wait. Defaults to `max(distributedLock.ttlMs, timeouts.hardMs) + distributedLock.pollMs`, initially 10,050 ms. Waiters recheck the cache and retry released locks. At the deadline, eligible stale data is returned or `DistributedLockTimeoutError` is thrown by default. An explicit value overrides the derived budget.
</ParamField>

<ParamField path="distributedLock.pollMs" type="number" default="50">
  Interval between polls while waiting, without an event bus. Each poll is a real read through L1 and L2 (one round trip with RedisStore's v2 layout), so a small value multiplies L2 traffic across every waiting server.
</ParamField>

<ParamField path="distributedLock.reconcileMs" type="number" default="4 × pollMs">
  With an event bus, waiters are woken as soon as the owner finishes, and poll only every `reconcileMs`, to catch a notification that was lost.
</ParamField>

<ParamField path="distributedLock.onTimeout" type="string" default="throw">
  `throw` uses eligible stale data when fail-safe is enabled, otherwise it raises `DistributedLockTimeoutError`. `load` explicitly permits an unlocked loader after contention times out, which can duplicate another instance's work. No setting is needed for the default protection.
</ParamField>

## Resilience [#resilience]

<ParamField path="failSafe.enabled" type="boolean" default="true">
  Serves the last known value when the loader fails or times out, instead of propagating the error.

  On unless you explicitly disable it. A stale value is returned instead of an origin error while the stale window remains open.
</ParamField>

<ParamField path="failSafe.staleTtlMs" type="number">
  Defaults to `30_000`. How long a value stays usable as a stale fallback past its normal expiry. Raise it when your origin takes a long time to recover, lower it when serving an old value is worse than serving an error.

  The stale copy lives in this process's memory, so it does not survive a restart and is not shared between servers.
</ParamField>

<ParamField path="failSafe.maxEntries" type="number">
  Caps retained stale fallbacks. Defaults to `1000`.
</ParamField>

<ParamField path="failSafe.maxBytes" type="number">
  Caps retained stale fallback bytes. Defaults to `16777216` bytes.
</ParamField>

<ParamField path="timeouts.softMs" type="number">
  No default. Stop waiting on the loader and serve the stale copy.

  It applies **only** when fail-safe is enabled and a stale value exists for that key. In that case the soft timeout is the one that runs and `hardMs` is not consulted at all. Set it near your p99 loader latency, since anything lower trades freshness for latency on every slow load.
</ParamField>

<ParamField path="timeouts.hardMs" type="number" default="10000">
  Gives up on the loader entirely and rethrows, unless a stale copy is available to fall back on.

  Applies whenever the soft path above does not, so it is your only protection on a cold key that has never been loaded.
</ParamField>

Both timeouts abort the `AbortSignal` handed to your loader. If you do not pass that signal into your I/O, the timeout only stops the waiting, not the work.

<ParamField path="resilience.l2CircuitBreaker" type="{ enabled?: boolean; failureThreshold?: number; cooldownMs?: number }">
  Stops calling L2 after repeated failures. `enabled` defaults to `true`, `failureThreshold` to `3`, `cooldownMs` to `30000`.

  While open, every L2 operation is skipped and emits `l2:skipped`, and reads fall through to L1 alone. A threshold of `1` opens on a single blip. A long cooldown keeps you off a recovered Redis. After the cooldown one probe is allowed through, and a single failure reopens the breaker.
</ParamField>

<ParamField path="resilience.l2OperationGate" type="{ maxConcurrent?: number; maxQueued?: number; maxQueuedBytes?: number; queueTimeoutMs?: number; operationTimeoutMs?: number }">
  Bounds L2 work before it reaches the Redis client. Defaults are 64 active operations, 1024 queued operations, 32 MiB queued payload bytes, a 250 ms queue deadline, and a 2000 ms caller deadline. Timed-out Redis work remains accounted until its underlying command settles.
</ParamField>

<ParamField path="resilience.eventBusCircuitBreaker" type="{ enabled?: boolean; failureThreshold?: number; cooldownMs?: number }">
  The same, for bus publishes. Skips emit `event-bus:publish-skipped`.
</ParamField>

<Warning>
  **Sharp edge.** The event-bus circuit breaker and the bus retry queue do not compose. When the breaker is open, publishing returns before it reaches the bus, so the retry queue never buffers that event and it is gone. Peers keep their stale copies until TTL. Keep `cooldownMs` short here, and treat `event-bus:publish-skipped` as a real signal rather than noise.
</Warning>

## Event bus [#event-bus]

<ParamField path="eventBus" type="EventBus">
  The transport that carries invalidations and primed values between servers. `setupCache` creates Redis Pub/Sub when Redis is available. The low-level constructor has no default.

  With `setupCache`, health, connection, and subscription readiness are awaited for you. With the low-level constructor, connect the bus yourself and call `await cache.ready()` before accepting traffic.
</ParamField>

<ParamField path="sync" type="{ onRecovery?: boolean; intervalMs?: number; maxKeysPerRun?: number; concurrency?: number }">
  Compares in-process memory with the shared layer and removes entries that differ; it never writes memory. `onRecovery` runs it when a bus that cannot replay reconnects, instead of emptying memory. `intervalMs` (at least 1000) also runs it periodically, `maxKeysPerRun` keys at a time (default 10,000), resuming where the last run stopped, with `concurrency` reads in flight (default 16). Off by default. `cache.sync()` runs it on demand. A replaying bus such as `RedisStreamEventBus` needs neither.
</ParamField>

<ParamField path="source" type="string">
  Identity stamped on published events, and how a server recognises and ignores its own broadcasts. Defaults to a random per-process id.

  Give it a stable, unique value per server. Two servers sharing one `source` will each ignore the other's events, so invalidations silently stop working between them.
</ParamField>

<ParamField path="subscribeToEvents" type="boolean" default="true">
  Whether this server applies inbound events. Setting it to `false` gives you a publisher that never invalidates itself, which is what you want for a one-off writer process and never what you want for a server that also serves reads.
</ParamField>

<ParamField path="broadcastSet" type="boolean" default="true">
  Publishes a `getOrSet` loader result to every peer, carrying the value itself, so their L1 warms without any of them running the query. On whenever an event bus is configured.

  Setting it to `false` leaves you with delete-only fan-out, which means every server pays for its own copy of every key. Tune `broadcastSetMaxBytes` instead.
</ParamField>

<ParamField path="broadcastSetMaxBytes" type="number">
  `setupCache` defaults to 32 KB. The low-level constructor has no default. This is the encoded event size above which a value is not shipped to peers.

  With no ceiling set, a five megabyte loader result is broadcast in full to every server, on every cold load, over whatever transport you chose. That is the option most likely to hurt you here. Over the limit, the publish is skipped and `set:broadcast-skipped` is emitted with `reason: 'max-bytes'`. The value is still written to L1 and L2 locally.
</ParamField>

<ParamField path="eventDedupeMaxEntries" type="number" default="10000">
  How many recent event ids are remembered for duplicate suppression. Too small on a busy bus and an id ages out of the set before a redelivery arrives, so the duplicate is applied.
</ParamField>

<ParamField path="eventDedupeTtlMs" type="number" default="300000">
  How long each event id is remembered. Five minutes. Keep it above your broker's worst-case redelivery window, which matters on RabbitMQ and JetStream where redelivery is the point.
</ParamField>

<Note>
  Only a `getOrSet` loader result is broadcast. A direct `cache.set()` writes L1 and L2 and emits a local event, but never publishes to the bus, so it will not prime peers. See [the API reference](/docs/reference/api#choosing-between-getorset-get-and-set).
</Note>

### Bus-side options that change correctness [#bus-side-options-that-change-correctness]

Full constructor options for each transport are in the [event bus reference](/docs/reference/event-buses). Two of them decide whether the bus holds up under load.

<ParamField path="retryQueue" type="{ enabled?: boolean; maxSize?: number }">
  Buffers events that failed to publish so they go out on reconnect. `maxSize` defaults to `10000`. Available on every transport. Read the sharp edge above: it cannot help with events the circuit breaker skipped.
</ParamField>

<ParamField path="prefetch" type="number">
  RabbitMQ only, and it has **no default**. It is the only bound on how many invalidations are in flight to your handler at once, because the RabbitMQ handler dispatches without awaiting the result.

  Leave it unset and a slow handler lets unacknowledged deliveries pile up without limit. Set it to a real number, in the tens. The Redis bus bounds the same thing with `handlerConcurrency`.
</ParamField>

## Serialization [#serialization]

`levels.L1.codec` and `levels.L2.codec` select independent write policies for built-in stores. Reads dispatch on the stored HC1 tag, independently of the write policy.

<ParamField path="levels.L1.codec / levels.L2.codec" type="CacheCodecOptions">
  `{ format?: 'msgpack' | 'json', compression?: 'none' | 'gzip' | 'zstd' | 'auto' | CompressionTier[] }`. Omitted fields use the process defaults. Set these at construction or pass level-specific overrides to `getOrSet` or `prewarm`.
</ParamField>

`format: 'json'` stores tagged, uncompressed JSON. It follows JSON value semantics, so use JSON-compatible records. Explicit `format: 'msgpack'` overrides the JSON environment switches for that layer. Without an explicit format, `CACHE_FORMAT=json` or `CACHE_DEBUG_SERIALIZATION=true` selects JSON.

### Compression modes [#compression-modes]

| Mode   | Packed-size tiers                                                                                         |
| ------ | --------------------------------------------------------------------------------------------------------- |
| `auto` | None below 256 B, LZ4 below 4 KiB, then Zstd when available or LZ4 otherwise. This is the shipped default |
| `none` | No compression                                                                                            |
| `gzip` | None below 1 KiB, then gzip                                                                               |
| `zstd` | None below 1 KiB, then Zstd, falling back to LZ4 when unavailable                                         |

All compression modes retain the compressed result only when it saves at least 15% against packed MessagePack.

### Process-wide policy [#process-wide-policy]

```ts
configureCompression(mode: CompressionMode | CompressionTier[]): void
getCompressionTiers(): readonly CompressionTier[]
```

`configureCompression` changes the process-wide default for subsequent writes that omit a layer-specific compression policy. `CACHE_COMPRESSION` initializes that default when the serializer is imported. The last `configureCompression` call wins. `getCompressionTiers` reports this process default, not per-layer overrides.

<CodeGroup>
  ```js title="src/cache/compression.js"
  import { configureCompression } from 'lazy-layers-cache'

  configureCompression([
    { maxBytes: 256, codec: 'none' },
    { maxBytes: 4096, codec: 'lz4' },
    { codec: 'zstd' },
  ])
  ```

  ```ts title="src/cache/compression.ts"
  import { configureCompression } from 'lazy-layers-cache'

  configureCompression([
    { maxBytes: 256, codec: 'none' },
    { maxBytes: 4096, codec: 'lz4' },
    { codec: 'zstd' },
  ])
  ```
</CodeGroup>

<ParamField path="CompressionTier.maxBytes" type="number">
  Exclusive upper bound in packed bytes. Bounds must ascend. Only the last tier may omit this field, meaning all remaining sizes. If every tier has a bound, larger payloads remain uncompressed.
</ParamField>

<ParamField path="CompressionTier.codec" type="'none' | 'gzip' | 'zstd' | 'lz4' | 'snappy'">
  Codec attempted for this band. Unknown names are rejected during tier validation. Unavailable Zstd falls back to LZ4 at write time.
</ParamField>

<ParamField path="ZSTD_AVAILABLE" type="boolean">
  Whether the current `node:zlib` provides Zstd compression and decompression.
</ParamField>

<ParamField path="LZ4_AVAILABLE() / SNAPPY_AVAILABLE()" type="() => boolean">
  Compatibility helpers that return `true` in this release. LZ4 and Snappy are package dependencies.
</ParamField>

`serializeWithStats(value, policy)` reports encoding, original bytes, stored bytes, and compression savings. `deserialize` returns `null` for corrupt data or an unavailable decoder, so a built-in store treats that entry as a miss. See [serialization](/docs/concepts/serialization) for compatibility and measurement guidance.

## Observability [#observability]

<ParamField path="observability" type="boolean | ObservabilityOptions" default="false">
  Off by default, with zero hot-path cost when off. `true` starts the dashboard with the defaults below. Enabling it adds one O(1) handler to the event loop that is already running.
</ParamField>

<Warning>
  The dashboard exposes cache contents and live activity. It is a development and staging tool. Leaving it enabled in production, on default credentials, publishes your cached data to anyone who can reach the port.
</Warning>

<ParamField path="observability.enabled" type="boolean" default="false">
  Master switch. Also enabled by a truthy `LAZY_OBS_ENABLED`.
</ParamField>

<ParamField path="observability.route" type="string" default="/__lazylayers">
  Base route. Normalised to a leading slash with no trailing slash.
</ParamField>

<ParamField path="observability.maxEvents" type="number" default="1000">
  Size of the in-memory ring buffer for the live feed. Never persisted. Raising it costs heap on a process you are already trying to keep small.
</ParamField>

<ParamField path="observability.maxValueBytes" type="number" default="262144">
  Decoded values larger than this are truncated in the UI. 256 KB.
</ParamField>

<ParamField path="observability.maxStreamClients" type="number" default="64">
  Maximum simultaneous SSE clients for each handler. Additional clients receive HTTP 503. A positive safe integer; `LAZY_OBS_MAX_STREAM_CLIENTS` supplies the environment default.
</ParamField>

<ParamField path="observability.maxStreamEventBytes" type="number" default="65536">
  Maximum encoded SSE frame size. Slow streams drop replay, live events and heartbeats until Node signals `drain`; they do not build an application backlog. `LAZY_OBS_MAX_STREAM_EVENT_BYTES` supplies the environment default. The activity collector also bounds each captured event at 64 KiB and marks oversized metadata with `data.truncated: true`.
</ParamField>

<ParamField path="observability.server" type="{ host?: string; port?: number; autoStart?: boolean } | false">
  Standalone server config. `host` defaults to `127.0.0.1`, `port` to `7077`, `autoStart` to `true`. Pass `false` to skip the server and mount `getObservabilityHandler()` on your own instead.

  Changing `host` off localhost exposes the dashboard to your network. Do that only behind real authentication.
</ParamField>

<ParamField path="observability.auth" type="{ username?: string; password?: string; token?: string; disabled?: boolean }">
  Credentials. There are no defaults: with no `username`/`password` pair and no `token`, a random token is generated and printed once at startup. `username` and `password` must be set together. `token` is accepted as `?token=`, as a bearer header, and through the HttpOnly cookie set after a `?token=` visit. `disabled: true` removes authentication entirely.

  The environment variable is `LAZY_OBS_USER`, not `LAZY_OBS_USERNAME`.
</ParamField>

<ParamField path="observability.prometheus" type="boolean | { enabled?: boolean; prefix?: string; public?: boolean }">
  Exposes an exposition endpoint at `{route}/metrics`. `enabled` defaults to `false`, `prefix` to `lazycache`, `public` to `false`. `public: true` allows unauthenticated scrapes of the metrics endpoint while the UI stays behind auth.
</ParamField>

<ParamField path="observability.quiet" type="boolean" default="false">
  Suppresses the one-time startup warning. Silence it only once you have actually secured the dashboard.
</ParamField>

Every option above has an environment variable equivalent. They are listed in the [environment variables reference](/docs/reference/environment-variables).

## Logging [#logging]

<ParamField path="logging.env" type="'development' | 'production' | 'test'">
  Overrides `NODE_ENV` for log verbosity. Defaults to `production` when `NODE_ENV` is `production`, and `development` otherwise. Anything other than `production` prints debug lines on every hit, miss, set and delete.
</ParamField>

<ParamField path="logging.enabled" type="boolean">
  No default. A hard override of the environment check. `true` forces debug logging on in production, which will fill your log pipeline at cache throughput. `false` silences it everywhere, including the error lines that tell you L2 is failing open.
</ParamField>

<ParamField path="logger" type="CacheLogger | CacheLogger[]">
  A logger for this cache only, such as a pino instance: any object with optional `debug`, `info`, `warn` and `error` methods taking `(fields, message)`, and optionally `name`, `minLevel`, `context` (fields added to every line) and `flush` (awaited on close, at most one second). A list sends each line to every logger. A missing method means that level is not logged. A logger that throws, rejects or hangs never affects the cache; its first failure is reported once. When set, `logging.env` and `logging.enabled` do not apply to this cache.
</ParamField>

<ParamField path="events" type="CacheEventHandler[]">
  Handlers registered at construction, equivalent to calling `on` for each. Registering them here is what catches events emitted during startup, before you would have had a chance to subscribe.
</ParamField>

<Note>
  `logging.env` and `logging.enabled` configure the built-in console logger, which is process-wide: the last cache you construct wins for every cache that has no `logger` of its own.
</Note>

## Transaction coordination [#transaction-coordination]

`lazy-layers-cache/transactions` is a separate, primary-only Redis coordination API. It is not configured through `setupCache`, `LazyLayersCacheOptions`, `CacheOptions`, L1, L2, or the event bus. A cache's Redis client is not automatically a transaction authority.

Configure `RedisOperationTransport` with an isolated `namespace`, a diagnostic `authorityId`, and a client that is known to reach a Redis primary. Production clients must explicitly set `enableOfflineQueue: false`, `autoResendUnfulfilledCommands: false`, and `maxRetriesPerRequest` to `0` or `1`. Cluster use additionally requires explicit `clusterValidated: true`. The transport rejects replicas, read-only clients, `keyPrefix`, and uninspectable routing options by default.

`RedisOperationStore` separately controls its lease, retention, and bounded dispatcher. Its defaults are a 30 second lease, seven day retention, 64 active commands, 1,024 queued commands, 4 MiB of queued command data, a 250 ms queue wait, and a 2 second command deadline. These limits constrain coordination traffic. They do not configure cache memory, Redis eviction, or a business transaction.

Read [transaction coordination](/docs/reference/transactions) before using the API. It defines the required durable-record, provider-idempotency, reconciliation, and transactional-outbox responsibilities.

## Per-call overrides [#per-call-overrides]

`getOrSet` takes a third argument of the same `CacheOptions` shape, so one call can differ from the cache-wide policy.

<CodeGroup>
  ```js title="src/reports/annual.js"
  import { cache } from '../cache/index.js'
  import { buildReport } from './build.js'

  export function getAnnualReport() {
    return cache.getOrSet('report:annual', buildReport, {
      ttlMs: 24 * 60 * 60 * 1000,
      timeouts: { hardMs: 30_000 },
    })
  }
  ```

  ```ts title="src/reports/annual.ts"
  import { cache } from '../cache/index.js'
  import { buildReport } from './build.js'
  import type { Report } from '../types/report.js'

  export function getAnnualReport(): Promise<Report | undefined> {
    return cache.getOrSet('report:annual', buildReport, {
      ttlMs: 24 * 60 * 60 * 1000,
      timeouts: { hardMs: 30_000 },
    })
  }
  ```
</CodeGroup>

Overridable per call: `ttlMs`, `levels`, `inflight`, `negativeCache`, `failSafe`, `timeouts` and `distributedLock`.

Constructor only: `memoryBudget`, `originLoad` limits, `l1`, `l2`, `eventBus`, `source`, `subscribeToEvents`, `resilience`, `events`, `eventDedupeMaxEntries`, `eventDedupeTtlMs`, `logging`, `broadcastSet`, `broadcastSetMaxBytes` and `observability`. `versioning` is accepted per call by the type but read from the constructor options only.

## Where to next [#where-to-next]

<CardGroup cols="2">
  <Card title="API reference" icon="code" href="/docs/reference/api">
    The methods that read these options, with full signatures and return types.
  </Card>

  <Card title="Production checklist" icon="clipboard-check" href="/docs/setups/production">
    These numbers chosen for a real instance, in the order you should set them.
  </Card>

  <Card title="Failure handling" icon="shield-check" href="/docs/guides/failure-handling">
    What fail-safe, timeouts and the circuit breakers actually do when the origin is down.
  </Card>
</CardGroup>
