# API (https://lazy-layers-cache.vercel.app/docs/reference/api)

> Managed production setup, every LazyLayersCache method, and the complete export surface.



`setupCache` is the production entry point. It returns a managed `LazyLayersCache`, which is the only object application code needs after startup.

## Find a method [#find-a-method]

| Task                                  | Method                                                                    |
| ------------------------------------- | ------------------------------------------------------------------------- |
| Create and connect a managed cache    | [`setupCache`](#production-setup)                                         |
| Read through the cache                | [`getOrSet`](#getorset)                                                   |
| Warm a key                            | [`prewarm`](#prewarm)                                                     |
| Read or load many keys                | [`getMany`](#getmany-setmany-deletemany), [`getOrSetMany`](#getorsetmany) |
| Read L1 without awaiting              | [`peekLocal`](#peeklocal)                                                 |
| Group keys to clear together          | [`namespace`](#namespace)                                                 |
| Invalidate after a write              | [`invalidate`](#invalidate)                                               |
| Invalidate a key family               | [`invalidateByPattern`](#invalidatebypattern)                             |
| Invalidate every value carrying a tag | [`invalidateTags`](#invalidatetags)                                       |
| Release resources                     | [`close`](#lifecycle-methods)                                             |

See [configuration](/docs/reference/configuration) for option defaults and the [quickstart](/docs/quickstart) for an application example.

## Transaction coordination is a separate API [#transaction-coordination-is-a-separate-api]

`lazy-layers-cache/transactions` coordinates attempts for a durable operation through a primary Redis record. It is not part of `LazyLayersCache`, `setupCache`, L1, L2, or the event bus. Do not use a cache loader or a cache lock to authorize a payment, order transition, or other business side effect.

The coordinator exposes `begin`, `renew`, `complete`, and `readStatus`. Its result unions distinguish acquired, in-progress, completed, and conflict. Its classified unavailable and unknown errors tell your application when to retry before dispatch or reconcile durable state instead of guessing. It does not execute your business action or return its business result.

[Transaction coordination](/docs/reference/transactions) documents the exact import, client requirements, result unions, recovery flow, and the database, provider, and outbox responsibilities that remain outside the library.

## Production setup [#production-setup]

```ts
function setupCache<K extends CacheKey = string, V = unknown>(
  options?: SetupCacheOptions<K, V>,
): Promise<ManagedLazyLayersCache<K, V>>
```

`setupCache` resolves infrastructure, checks health, waits for the event subscription, and returns a cache with idempotent cleanup. It reads `REDIS_URL` when no client or URL is passed.

For Cloudflare KV on Node.js, pass `kv: { namespace }` with a KV binding-compatible client such as `CloudflareKVRestNamespace`. An explicit KV selection suppresses implicit Redis discovery. Workers use the separate `lazy-layers-cache/cloudflare` entrypoint. See [Cloudflare KV setup](/docs/setups/cloudflare-kv).

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

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

<ParamField path="namespace" type="string">
  Redis key and channel namespace. Falls back to `LAZY_LAYERS_NAMESPACE`, then `npm_package_name`, then `app`.
</ParamField>

<ParamField path="redis" type="SetupRedisOptions | false">
  Creates Redis L2 and Redis Pub/Sub from an existing `client`, an explicit `url`, or `REDIS_URL`. Pass `false` for L1 only. `required: true` rejects startup when Redis configuration is missing.
</ParamField>

<ParamField path="l2" type="CacheStore<K, V> | false">
  Explicit store override. It wins over the generated Redis store.
</ParamField>

<ParamField path="eventBus" type="EventBus | false">
  Explicit bus override. It wins over generated Redis Pub/Sub. Pass `false` to disable peer fan-out.
</ParamField>

<ParamField path="invalidationPublisher" type="CloudflareInvalidationPublisher">
  Publishes `invalidate` and `invalidateByPattern` operations to a dedicated Cloudflare Queue after local deletion. The separate consumer retries KV deletion. Queue delivery does not fan out to every L1. See [Cloudflare KV setup](/docs/setups/cloudflare-kv#application-invalidation-queue).
</ParamField>

<ParamField path="startup.requireHealthy" type="boolean" default="true">
  Requires configured shared infrastructure and the inbound subscription to be ready before setup returns.
</ParamField>

<ParamField path="startup.timeoutMs" type="number" default="10000">
  Bounds each startup health, connection, and subscription readiness check.
</ParamField>

All `LazyLayersCacheOptions` are accepted alongside these setup fields. See [production setup](/docs/setups/production) for the resolved defaults.

## Low-level construction [#low-level-construction]

```ts
class LazyLayersCache<K extends CacheKey = string, V = unknown> extends HybridCache<K, V> {
  constructor(options?: LazyLayersCacheOptions<K, V>)
}
```

`K` is the key type and must extend `CacheKey`, which is `string | number`. `V` is the value type. Both default to `string` and `unknown`, so an unparameterised cache hands you `unknown` back and you cast at every call site. Name the types once at construction and every method is typed from there.

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

  export const cache = new LazyLayersCache({ ttlMs: 5 * 60 * 1000 })

  // Identical object, built by the factory helper.
  export const same = createCache({ ttlMs: 5 * 60 * 1000 })
  ```

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

  export const cache = new LazyLayersCache<string, User>({ ttlMs: 5 * 60 * 1000 })

  // Identical object, built by the factory helper.
  export const same = createCache<string, User>({ ttlMs: 5 * 60 * 1000 })
  ```
</CodeGroup>

### createCache [#createcache]

```ts
function createCache<K extends CacheKey = string, V = unknown>(
  options?: LazyLayersCacheOptions<K, V>,
): LazyLayersCache<K, V>
```

`createCache(options)` is a one-line helper that returns `new LazyLayersCache(options)`. Same class, same options, same defaults, no extra behaviour. Use it when you prefer a function call to a `new` expression. Everything documented below applies to both.

`HybridCache` is the base class and holds all the logic. `LazyLayersCache` extends it and only forwards the constructor, so the two are interchangeable. `LazyLayersCacheOptions<K, V>` is an alias of `HybridCacheOptions<K, V>`. Every option lives in the [configuration reference](/docs/reference/configuration).

## Methods [#methods]

### getOrSet [#getorset]

```ts
getOrSet(key: K, loader: CacheLoader<V>, options?: CacheOptions): Promise<V | undefined>
```

The read-through path, and the method to reach for in almost all code. It checks L1, then L2, then runs your loader, then writes the result everywhere it belongs and broadcasts it to your other servers.

<ParamField path="key" type="K">
  The cache key. A `string` or `number`.
</ParamField>

<ParamField path="loader" type="(context?: { signal: AbortSignal }) => Promise<V | undefined>">
  Runs only on a miss. Receives an `AbortSignal` that fires on loader timeout or detected distributed lock loss, so pass it into your I/O. Returning `undefined` records a negative entry instead of caching a value.
</ParamField>

<ParamField path="options" type="CacheOptions">
  Per-call overrides for `ttlMs`, `levels`, `inflight`, `originLoad`, `negativeCache`, `failSafe`, `timeouts`, `distributedLock`, `ttlJitter`, `staleWhileRevalidate` and `earlyRefresh`, plus `tags`, the tags to store the value under for [`invalidateTags`](#invalidatetags). Falls back to the constructor options for anything you leave out.
</ParamField>

Returns the cached or freshly loaded value. It returns `undefined` when the loader resolves `undefined` and no stale copy is available, and short-circuits to `undefined` without calling the loader at all while a negative entry for that key is live.

<CodeGroup>
  ```js title="src/users/repository.js"
  import { cache } from '../cache/index.js'
  import { db } from '../db.js'

  export async function getUser(id) {
    return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
      const row = await db.users.findById(id, { signal })
      return row ?? undefined
    })
  }
  ```

  ```ts title="src/users/repository.ts"
  import { cache } from '../cache/index.js'
  import type { User } from '../types/user.js'
  import { db } from '../db.js'

  export async function getUser(id: string): Promise<User | undefined> {
    return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
      const row = await db.users.findById(id, { signal })
      return row ?? undefined
    })
  }
  ```
</CodeGroup>

What happens on a miss, in order:

<Steps>
  <Step title="Dedupe">
    A built-in L1 hit returns without awaiting. On a miss, concurrent callers for the same key join the in-flight promise, which is registered before the L2 read, so the L2 read and the loader body run once per process. If `inflight.maxEntries` is already full the call runs unregistered and emits `inflight:bypass`.
  </Step>

  <Step title="Coordinate across instances">
    Redis L2 automatically locks cold and expired keys and renews active leases. With RedisStore's v2 key layout, the L2 read takes the lease in the same script when the key is empty, so a miss costs two Redis round trips: that read, and one that publishes the value and releases the lease. Waiters are woken by the event bus when the load finishes, or poll without one, and return the shared value or take over a released lease.
  </Step>

  <Step title="Load">
    The loader runs under your `timeouts` with an `AbortSignal`. A failure serves the stale copy when fail-safe is on and one exists, and rethrows otherwise.
  </Step>

  <Step title="Store">
    The value is written to L1 and L2, and any negative entry for the key is cleared. The built-in L1 keeps a fail-safe snapshot when the value later expires or is evicted by the entry limit.
  </Step>

  <Step title="Broadcast">
    With an event bus configured, an untagged value is published as a `set` event. Every peer writes it into its own L1, so their first read of that key is already a local hit. One server pays for the query. Tagged values are not broadcast; peers read them from L2.
  </Step>
</Steps>

<Note>
  The broadcast is the reason `getOrSet` earns its place over a manual read-then-write. Only a `getOrSet` loader result is published. See [the difference between getOrSet, get and set](#choosing-between-getorset-get-and-set).
</Note>

<Warning>
  `setupCache` sets `broadcastSetMaxBytes` to 32 KB. The low-level constructor has no ceiling. Values over the ceiling are still stored locally and in L2, and the skip emits `set:broadcast-skipped` with `reason: 'max-bytes'`.
</Warning>

With Redis L2, a contention deadline returns eligible stale data or throws the exported `DistributedLockTimeoutError` (`code: 'DISTRIBUTED_LOCK_TIMEOUT'`, `key`, `waitTimeoutMs`). Detected lease loss aborts the loader signal and throws `DistributedLockLostError` (`code: 'DISTRIBUTED_LOCK_LOST'`, `key`) unless eligible stale data can be served. No lock settings are required. See [stampede protection](/docs/guides/stampede-protection) for the automatic wait budget and failure limits.

### prewarm [#prewarm]

```ts
prewarm(key: K, loader: CacheLoader<V>, options?: CacheOptions): Promise<V | undefined>
```

The explicit warm-up name for the full `getOrSet` path. It checks existing layers first, runs one protected loader on a miss, stores the result, and primes peer L1 caches. Use it from deploy hooks, schedulers, or background jobs.

```js title="src/jobs/prewarm.js"
await cache.prewarm('plans:active', ({ signal }) =>
  db.plans.findActive({ signal }),
)
```

### get [#get]

```ts
get(key: K): Promise<V | undefined>
```

Reads what is already cached. Nothing more.

<ParamField path="key" type="K">
  The cache key.
</ParamField>

Checks the negative cache, then L1, then L2. A value found in L2 is written into L1 before it is returned, so the next read is local. Returns `undefined` for a negative-cached key, for a genuine miss, and when L2 fails or its circuit breaker is open, because L2 failures degrade rather than throw.

`get` never runs a loader, never dedupes, and never publishes anything.

<CodeGroup>
  ```js title="src/users/warm-path.js"
  import { cache } from '../cache/index.js'

  const cached = await cache.get(`user:${id}`)

  if (cached === undefined) {
    // Nothing was loaded. You now own the miss.
  }
  ```

  ```ts title="src/users/warm-path.ts"
  import { cache } from '../cache/index.js'

  const cached: User | undefined = await cache.get(`user:${id}`)

  if (cached === undefined) {
    // Nothing was loaded. You now own the miss.
  }
  ```
</CodeGroup>

### set [#set]

```ts
set(key: K, value: V, options?: CacheOptions): Promise<void>
```

Writes a value you already have.

<ParamField path="key" type="K">
  The cache key.
</ParamField>

<ParamField path="value" type="V">
  The value to store. It is serialized on the way into L2.
</ParamField>

<ParamField path="options" type="CacheOptions">
  Per-call overrides, same shape as `getOrSet`.
</ParamField>

Writes to L1 and to L2, remembers the value as the stale copy when fail-safe is on, clears any negative entry for the key, and emits a local `set` cache event for your `on` handlers.

<Warning>
  `set` writes to L1 and L2 but does **not** publish to the event bus. Only a `getOrSet` loader result is broadcast. Every peer keeps whatever its own L1 already holds until that entry expires or you `delete` the key, so a plain `set` will not prime peers and can leave them serving the old value for a full L1 TTL.
</Warning>

<CodeGroup>
  ```js title="src/users/import.js"
  import { cache } from '../cache/index.js'

  // Seeding a value you computed elsewhere. Local layers only.
  await cache.set(`user:${user.id}`, user, { ttlMs: 30 * 1000 })
  ```

  ```ts title="src/users/import.ts"
  import { cache } from '../cache/index.js'
  import type { User } from '../types/user.js'

  // Seeding a value you computed elsewhere. Local layers only.
  await cache.set(`user:${user.id}`, user, { ttlMs: 30 * 1000 })
  ```
</CodeGroup>

### Choosing between getOrSet, get and set [#choosing-between-getorset-get-and-set]

|            | Runs a loader | Dedupes concurrent callers | Writes L1 and L2           | Primes peers |
| ---------- | ------------- | -------------------------- | -------------------------- | ------------ |
| `getOrSet` | yes           | yes                        | yes                        | yes          |
| `get`      | no            | no                         | promotes an L2 hit into L1 | no           |
| `set`      | no            | no                         | yes                        | no           |

Reach for `getOrSet` unless you have a specific reason not to. `get` is for the rare case where a miss is not yours to fill, such as a health probe or a debug endpoint. `set` is for a value that arrived from somewhere other than a loader, and it costs you the broadcast.

<Note>
  This is the only page in these docs that uses `get` and `set` in an example. Everywhere else, a read is `getOrSet`, a warm-up is `prewarm`, and an invalidation is `invalidate` or `invalidateByPattern`.
</Note>

### peekLocal [#peeklocal]

```ts
peekLocal(key: K): V | undefined
```

Reads the built-in L1 synchronously: no promise, no L2, no network. Returns `undefined` on a miss, while invalidation is not trusted, for a remembered miss, and when L1 is a custom store (only the built-in one can be read synchronously). A hit is counted and reported like a `get()` hit.

```js
const flags = cache.peekLocal('feature-flags') ?? (await cache.getOrSet('feature-flags', loadFlags))
```

### getMany, setMany, deleteMany [#getmany-setmany-deletemany]

```ts
getMany(keys: readonly K[]): Promise<(V | undefined)[]>
setMany(entries: Iterable<readonly [K, V]>, options?: CacheOptions): Promise<void>
deleteMany(keys: readonly K[]): Promise<void>
```

Batch versions of `get`, `set` and `delete`, with the same guarantees per key. Results follow the order of `keys`. At most 64 operations run at once, so a large batch cannot flood L2. With `RedisStore`, those 64 go to Redis as one Lua script ([batch scripts](/docs/guides/redis-lua-scripts)), and `setMany` and `deleteMany` tell peers in one event per 256 keys.

### runScript [#runscript]

```ts
runScript(name: string, keys: readonly K[], args?: readonly (string | number | Buffer)[]): Promise<unknown>
```

Runs a Lua script registered in the L2 store's `scripts` option on the Redis keys of `keys` (`KEYS[1..n]`) and their lease keys (`KEYS[n+1..2n]`), and returns its reply. A script declared `writes: true` is fenced against loads in flight, and its keys are dropped from memory here and on peers afterwards, even when it fails. Throws a `TypeError` for an unknown name or an L2 that cannot run scripts; script errors reach the caller. See the [Redis Lua scripts guide](/docs/guides/redis-lua-scripts).

### getOrSetMany [#getorsetmany]

```ts
getOrSetMany(
  keys: readonly K[],
  loader: (missing: K[], context: { signal: AbortSignal }) => Promise<Map<K, V | undefined> | (V | undefined)[]>,
  options?: CacheOptions,
): Promise<(V | undefined)[]>
```

Reads every key and loads all misses with one `loader` call. The loader returns a Map, or an array in the order of `missing`. Keys it leaves out are misses and are remembered by the negative cache. Keys already loading in this process are joined; concurrent `getOrSet` calls for keys in the batch join it. A batch never overwrites a write or delete that happened while it loaded. It takes one origin slot and no cross-process lease. See [batches](/docs/guides/batches-and-freshness#batch-reads-and-loads).

### namespace [#namespace]

```ts
namespace(name: string): CacheNamespace<V>
```

A view in which every key is prefixed with `name:`, sharing this cache's layers, budget and connections. It has `get`, `peekLocal`, `set`, `getOrSet`, `prewarm`, `has`, `delete`, `invalidate`, the batch methods, `deleteByPattern`, `clear()` (invalidates only this namespace, here and on peers) and `namespace()` for nesting. The name cannot contain `*`.

### has [#has]

```ts
has(key: K): Promise<boolean>
```

<ParamField path="key" type="K">
  The cache key.
</ParamField>

Returns `false` immediately for a negative-cached key, without consulting either layer. Otherwise it asks L1, then L2. An L2 failure returns `false` rather than throwing.

`has` does not decode the value, which makes it cheap on L2 but leaves you open to the usual race: the key can expire between your `has` and your read. Prefer `getOrSet` and check the result for `undefined`.

```js title="src/cache/probe.js"
const warm = await cache.has(`user:${id}`)
```

### delete [#delete]

```ts
delete(key: K): Promise<void>
```

<ParamField path="key" type="K">
  The key to invalidate everywhere.
</ParamField>

Drops the key from L1, L2, the negative cache, the stale copy and any in-flight promise, advances that key's generation counter, then publishes a `del` event so every peer does the same. Call it after your write commits, not before.

<CodeGroup>
  ```js title="src/users/repository.js"
  export async function updateUser(id, patch) {
    const updated = await db.users.update(id, patch)
    await cache.delete(`user:${id}`)
    return updated
  }
  ```

  ```ts title="src/users/repository.ts"
  export async function updateUser(id: string, patch: Partial<User>): Promise<User> {
    const updated = await db.users.update(id, patch)
    await cache.delete(`user:${id}`)
    return updated
  }
  ```
</CodeGroup>

### invalidate [#invalidate]

```ts
invalidate(key: K): Promise<void>
```

The application-facing name for `delete`. It has identical behaviour and is the preferred name after a source-of-truth write.

```js title="src/users/repository.js"
const user = await db.users.update(id, patch)
await cache.invalidate(`user:${id}`)
```

### deleteByPattern [#deletebypattern]

```ts
deleteByPattern(pattern: string): Promise<void>
```

<ParamField path="pattern" type="string">
  A glob pattern such as `user:42:sessions:*`.
</ParamField>

Removes every matching entry from L1, L2, and the in-flight, negative and stale maps, then publishes a `pattern` event so every peer repeats the scan locally.

<Warning>
  This walks the keyspace. L1 iterates every key it holds, and L2 scans Redis. `deleteByPattern('*')` does that on every server at once. Keep patterns tightly prefixed, and never build one from user input.
</Warning>

Unlike `delete`, a `pattern` event carries no generation counter, so the ordering guard that protects single keys does not apply to pattern invalidations.

<CodeGroup>
  ```js title="src/users/repository.js"
  await cache.deleteByPattern(`user:${id}:sessions:*`)
  ```

  ```ts title="src/users/repository.ts"
  await cache.deleteByPattern(`user:${id}:sessions:*`)
  ```
</CodeGroup>

### invalidateByPattern [#invalidatebypattern]

```ts
invalidateByPattern(pattern: string): Promise<void>
```

The application-facing name for `deleteByPattern`. It performs the same namespace scan and publishes the same pattern event.

### invalidateTags [#invalidatetags]

```ts
invalidateTags(tags: readonly string[]): Promise<void>
```

Invalidates every value stored with any of `tags`, in every layer and on every instance, without scanning keys. Store values with tags through the `tags` option of `set`, `getOrSet`, `setMany` or `getOrSetMany`.

```js title="src/products/repository.js"
await cache.getOrSet(`product:${id}`, () => db.products.find(id), {
  tags: ['products', `store:${storeId}`],
})

await cache.invalidateTags([`store:${storeId}`])
```

Each tag has a token; invalidating gives it a new one, and an entry loaded under an older token reads as a miss. A load that started before the call cannot bring its value back. Without an event bus, other instances notice within `tagCheckMs` (1 second by default). Emits a `delete-tags` event and is counted in `lazycache_deletes_total{kind="tags"}`. See [invalidating by tag](/docs/concepts/invalidation#invalidating-by-tag) for limits and rolling-upgrade behaviour.

### clear [#clear]

```ts
clear(): Promise<void>
```

Exactly `deleteByPattern('*')`. It empties this server's layers and publishes a pattern event that empties every peer's too, including the shared L2 you all read from.

<Warning>
  `clear` is a production incident waiting for a caller. It is a test and local-development tool. To drop a bounded set of keys, use `deleteByPattern` with a real prefix.
</Warning>

### size [#size]

```ts
size(): Promise<number>
```

Returns the L1 entry count when L1 exists. It only reports L2 when L1 is disabled, so with both layers configured this is the number of entries in **this process's memory**, not the total across the cache.

L2 sizing is approximate. `RedisStore` returns the cardinality of its index when `useIndex` is on, and otherwise counts keys with a full scan, which is expensive on a large keyspace.

```js title="src/cache/metrics.js"
const l1Entries = await cache.size()
```

### on [#on]

```ts
on(handler: CacheEventHandler): () => void
```

<ParamField path="handler" type="(event: CacheEvent) => void">
  Called synchronously for every cache event. A handler that throws is caught and logged, so it cannot break a read.
</ParamField>

Returns an unsubscribe function. Passing handlers to the `events` constructor option is equivalent to calling `on` for each of them at startup.

<CodeGroup>
  ```js title="src/cache/metrics.js"
  import { cache } from './index.js'

  const off = cache.on((event) => {
    if (event.type === 'set:broadcast-skipped') {
      console.warn('value too large to broadcast', event.bytes, event.maxBytes)
    }
  })

  // Later, during shutdown.
  off()
  ```

  ```ts title="src/cache/metrics.ts"
  import type { CacheEvent } from 'lazy-layers-cache'
  import { cache } from './index.js'

  const off = cache.on((event: CacheEvent) => {
    if (event.type === 'set:broadcast-skipped') {
      console.warn('value too large to broadcast', event.bytes, event.maxBytes)
    }
  })

  // Later, during shutdown.
  off()
  ```
</CodeGroup>

The full event union is in the [cache events reference](/docs/reference/cache-events).

<Warning>
  Never use a cache key as a metric label. Keys are unbounded, and one high-cardinality label will take down your metrics backend before it takes down your cache.
</Warning>

### Observability methods [#observability-methods]

```ts
getObservabilityHandler(): ObservabilityRequestHandler | undefined
getObservabilityServer(): ObservabilityServerHandle | undefined
closeObservability(): Promise<void>
```

`getObservabilityHandler` returns a request handler you can mount on your own HTTP server. It answers the request and returns `true`, or returns `false` to pass through. Both getters return `undefined` when observability is off. `closeObservability` stops the standalone server and is safe to call when none was started.

### Lifecycle methods [#lifecycle-methods]

```ts
ready(): Promise<void>
close(): Promise<void>
```

`ready` resolves when the inbound event subscription is active and rejects when subscription failed. `setupCache` calls it before returning.

`close` stops observability and disconnects the event bus. On a `ManagedLazyLayersCache`, it also closes the Redis client when setup created that client. Caller-provided clients remain caller-owned. Managed close is idempotent.

## Redis capability discovery [#redis-capability-discovery]

```ts
discoverRedisCapabilities(
  client: RedisCapabilityClient,
  options?: RedisCapabilityDiscoveryOptions,
): Promise<RedisCapabilityManifest>
hasRedisCapability(manifest: RedisCapabilityManifest, name: RedisCapabilityName): boolean
```

Discovery sends bounded, read-only `INFO server` and `COMMAND INFO` requests for an allow-list. It never runs `CONFIG`, creates an index, or enables Redis modules. Each command has a `supported`, `unavailable`, or `unknown` state with a sanitized reason. `supported` means the server advertises the command, not that every application operation has passed an ACL or runtime check.

| Option                 | Default                  | Maximum                |
| ---------------------- | ------------------------ | ---------------------- |
| `timeoutMs`            | 250 ms per request       | Validated by discovery |
| `maxCommandNames`      | 18 allow-listed commands | 64                     |
| `maxInfoBytes`         | 16 KiB                   | 64 KiB                 |
| `maxCommandReplyBytes` | 64 KiB                   | 256 KiB                |

`commandNames` narrows the allow-list. `minimumRedisMajorVersion` defaults to 6. Discovery failures can produce `unknown`, so do not treat a failed probe as proof that Redis lacks a capability.

`new RedisCapabilityRegistry(client, options)` caches and deduplicates discovery via `get()`. `invalidate()` discards its manifest. A client `ready` event invalidates it after reconnect. Call `close()` to detach listeners. The registry does not own or close the client.

## Exported classes and values [#exported-classes-and-values]

Everything below is a runtime export of `lazy-layers-cache`.

<AccordionGroup>
  <Accordion title="Cache and stores">
    `ManagedLazyLayersCache`, `LazyLayersCache`, `HybridCache`, `MemoryStore`, `RedisStore`, `CloudflareKVStore`, `CloudflareKVRestNamespace`, `CircuitBreaker`, `setupCache`, `createCache`, and `CacheSetupError`.

    `MemoryStore` is the L1 implementation and is created for you when you do not pass `l1`. `RedisStore` is generic over the value type only, as `RedisStore<V>`, because its key type is fixed to `CacheKey`.
  </Accordion>

  <Accordion title="Event buses">
    `RedisEventBus`, `RabbitMQEventBus`, `NatsEventBus`. Each satisfies the `EventBus` interface and each needs `await bus.connect()` before use. Constructor options are in the [event bus reference](/docs/reference/event-buses).
  </Accordion>

  <Accordion title="Defaults">
    ```ts
    DEFAULT_CACHE_TTL_MS      // 3_600_000
    DEFAULT_L1_MAX_ENTRIES    // 1_000
    DEFAULT_INFLIGHT_TTL_MS   // 5_000 minimum for the derived in-flight lifetime
    PRODUCTION_L1_TTL_MS      // 10_000
    PRODUCTION_INFLIGHT_MAX_ENTRIES // 10_000
    PRODUCTION_BROADCAST_SET_MAX_BYTES // 32_768
    PRODUCTION_STARTUP_TIMEOUT_MS // 10_000
    GZIP_MIN_BYTES            // 65_536
    GZIP_SAVINGS_THRESHOLD    // 0.15
    NULL_SENTINEL             // '__hybridcache_null__'
    ```
  </Accordion>

  <Accordion title="Serializer">
    `serialize`, `serializeWithStats`, `deserialize`, `inspectBuffer`, `estimateValueBytes`, `getCompressionSavings`, `sizeSavings`, `shouldGzip`, `hasPrefix`, `stripPrefix`.

    `serialize` returns a `Buffer`. `serializeWithStats` returns that buffer plus `encoding`, `originalBytes`, `storedBytes`, `compressionRatio` and `compressed`. `deserialize` accepts a `Buffer` or `Uint8Array` and returns `null` on corrupt input rather than throwing, so one poisoned key cannot take down a read path.

    Shared cache records, including Cloudflare KV, use `serializeCacheValue` and `deserializeCacheValue`. Import them from `lazy-layers-cache` on Node or `lazy-layers-cache/cloudflare` in a Worker. That facade writes `HC1M`, `HC1G`, or `HC1J` with the shared 1 KiB gzip floor and 15% savings rule. The Node `serialize` function remains the full codec set for Redis and L1, including LZ4, Zstd, and Snappy.
  </Accordion>

  <Accordion title="Observability and telemetry">
    `ObservabilityCollector`, `ObservabilityInspector`, `createObservabilityHandler`, `startObservabilityServer`, `renderDashboard`, `renderPrometheus`, `resolveObservabilityOptions`, `normalizeRoute`, `isInspectableStore`.

    Telemetry rides Node's `diagnostics_channel`: `subscribeTelemetry`, `publishTelemetry`, `hasTelemetrySubscribers`, and `TELEMETRY_CHANNEL_NAME`, which is `lazycache:cache:event`.

    Constants: `DEFAULT_OBSERVABILITY_PORT` (`7077`), `DEFAULT_OBSERVABILITY_ROUTE` (`/__lazylayers`), `DEFAULT_OBSERVABILITY_MAX_EVENTS` (`1000`), `DEFAULT_OBSERVABILITY_MAX_VALUE_BYTES` (`262_144`), `OBSERVABILITY_SESSION_COOKIE` (`lazylayers_obs`, the cookie set after `?token=`). There are no default credentials.
  </Accordion>
</AccordionGroup>

## Exported types [#exported-types]

<AccordionGroup>
  <Accordion title="Cache and options">
    `SetupCacheOptions<K, V>`, `SetupRedisOptions`, `SetupCloudflareKVOptions`, `CacheStartupOptions`, `LazyLayersCacheOptions<K, V>`, `HybridCacheOptions<K, V>`, `HybridCacheResilienceOptions`, `CacheOptions`, `CacheLevelOptions`, `CacheLevel`, `CacheKey`, `CacheLayer<K, V>`, `CacheEntry<V>`, `CacheStore<K, V>`, `CacheLoader<V>`, `InflightEntry<K, V>`, `InflightOptions`, `InflightStore<K, V>`, `DistributedLock`, `DistributedLockOptions`, `CircuitBreakerOptions`, `CircuitBreakerState`, `RedisStoreOptions`, `CloudflareKVStoreOptions`, `CloudflareKVRestOptions`, `CloudflareKVNamespace`, `CacheLoggerOptions`, `CacheRuntimeEnv`.

    `CacheStore<K, V>` is the interface any custom layer must satisfy: `set`, `get`, `getOrSet`, `has`, `delete`, `deleteByPattern`, `clear` and `size`. `CacheLayer<K, V>` is `CacheStore<K, V> | false`, which is why `l1: false` and `l2: false` typecheck.
  </Accordion>

  <Accordion title="Events">
    `CacheEvent` and `CacheEventHandler` are the local event stream that `on` gives you.

    `InvalidationEvent` is what travels over the bus. It is a union of three variants keyed on `InvalidationType`, which is `'del' | 'pattern' | 'set'`. All three extend `BaseInvalidationEvent` with `id`, `type`, `source`, `ts` and `generation`.

    | Variant        | Type        | Extra fields                                         |
    | -------------- | ----------- | ---------------------------------------------------- |
    | `DeleteEvent`  | `'del'`     | `keys: string[]`                                     |
    | `PatternEvent` | `'pattern'` | `pattern: string`                                    |
    | `SetEvent`     | `'set'`     | `keys: string[]`, `value: unknown`, `ttlMs?: number` |

    `SetEvent` is the one that carries a payload, which is what primes a peer's L1 and what `broadcastSetMaxBytes` measures.
  </Accordion>

  <Accordion title="Inspection">
    `InspectableStore`, `StoreInspectOptions`, `StoreInspection`, `KeyInspection`, `BufferInspection`, `CacheEncoding`, `SerializedCacheValue`.

    A store is inspectable when it exposes `inspect()`. Both `MemoryStore` and `RedisStore` do, and `isInspectableStore` is the type guard the dashboard uses. Inspection is read-only and cursor-paginated, and L1 inspection uses `peek` so browsing keys never changes eviction order.
  </Accordion>

  <Accordion title="Observability and buses">
    `ObservabilityOptions`, `ResolvedObservabilityOptions`, `ObservabilityAuthOptions`, `ObservabilityServerOptions`, `ObservabilityPrometheusOptions`, `ObservabilityCounters`, `ObservabilityHandlerDeps`, `ObservabilityRequestHandler`, `ObservabilityServerHandle`, `StartObservabilityServerOptions`, `InspectorDeps`, `ConfigSnapshot`, `OverviewSnapshot`, `PrometheusGauges`, `RecordedEvent`.

    `EventBus`, `EventBusHealth`, `EventBusRetryQueueOptions`, `RedisEventBusOptions`, `RedisEventBusHealth`, `RabbitMQEventBusOptions`, `RabbitMQEventBusHealth`, `NatsEventBusOptions`, `NatsEventBusMode`, `NatsEventBusHealth`, `NatsJetStreamOptions`.
  </Accordion>
</AccordionGroup>

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

<CardGroup cols="2">
  <Card title="Configuration reference" icon="sliders" href="/docs/reference/configuration">
    Every option these methods read, its default, and what it costs you when it is wrong.
  </Card>

  <Card title="Cache events" icon="signal" href="/docs/reference/cache-events">
    The full union `on` delivers, so you can turn these methods into metrics.
  </Card>

  <Card title="Stores" icon="database" href="/docs/reference/stores">
    What `MemoryStore` and `RedisStore` do behind `get`, `set` and `deleteByPattern`.
  </Card>
</CardGroup>
