# Handle failure (https://lazy-layers-cache.vercel.app/docs/guides/failure-handling)

> Fail open, trip breakers, serve stale, cache known misses, and bound how long a loader may run.



When Redis or the event bus fails, lazy-layers-cache fails open: an L2 error becomes a miss and the loader runs, circuit breakers stop repeated calls to a failing dependency, and fail-safe serves a recent value when the loader itself fails or times out. Fail-safe is on by default with a 30 second window.

A cache sits between your users and everything slow. That position is also what makes it dangerous: a cache that throws when its store is sick has turned an optimisation into an outage. This page is about what your users see when something underneath stops answering.

## Fail open is the stance [#fail-open-is-the-stance]

L2 read failures become cache misses, allowing `getOrSet` to reach the loader. An event-bus publish failure is reported without rejecting a successful cache load. Circuit breakers and bounded queues limit repeated work against unavailable dependencies.

Fail-open does not guarantee a successful request. Loader failures, origin overload, contention deadlines, and detected lease loss can still reach the caller when no eligible stale value exists. [Stampede protection](/docs/guides/stampede-protection) explains the distinction between a Redis transport failure and a contended or lost lease.

<Warning>
  With managed Redis Pub/Sub, a subscription gap makes local invalidation state untrusted. The cache flushes and bypasses L1, negative entries, and stale fallbacks until recovery restores trust. With a bus that cannot report such gaps, missed events can leave local copies unchanged until expiry. Choose TTLs and stale windows for the freshness your reads tolerate.
</Warning>

## Circuit breakers [#circuit-breakers]

Failing open still means trying, and trying costs a connection, a socket timeout, and a slot in your request path. A circuit breaker stops you queueing work against a dependency that is already struggling.

Two independent breakers exist, one for L2 and one for the event bus. Both take the same `CircuitBreakerOptions`, and both are constructed for every cache you build, so their defaults are already live: three consecutive failures to open, then a thirty second cooldown. Configuring them is how you replace those numbers with numbers that fit your dependency.

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

  export const cache = new LazyLayersCache({
    l2: new RedisStore(redis, { prefix: 'app:cache:' }),
    eventBus: bus,
    source: process.env.INSTANCE_ID ?? `srv-${process.pid}`,

    resilience: {
      l2CircuitBreaker: {
        // Consecutive failures before the breaker opens. Default 3.
        failureThreshold: 5,
        // How long calls are skipped before one probe is allowed through.
        cooldownMs: 10_000,
      },
      eventBusCircuitBreaker: {
        failureThreshold: 3,
        cooldownMs: 5_000,
      },
    },
  })
  ```

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

  const options: LazyLayersCacheOptions<string, User> = {
    l2: new RedisStore<User>(redis, { prefix: 'app:cache:' }),
    eventBus: bus,
    source: process.env.INSTANCE_ID ?? `srv-${process.pid}`,

    resilience: {
      l2CircuitBreaker: {
        // Consecutive failures before the breaker opens. Default 3.
        failureThreshold: 5,
        // How long calls are skipped before one probe is allowed through.
        cooldownMs: 10_000,
      },
      eventBusCircuitBreaker: {
        failureThreshold: 3,
        cooldownMs: 5_000,
      },
    },
  }

  export const cache = new LazyLayersCache<string, User>(options)
  ```
</CodeGroup>

The breaker has three states, which is the standard shape.

| State       | What it means                     | What happens next                                                                                                 |
| ----------- | --------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
| `closed`    | Normal. Calls go through.         | `failureThreshold` consecutive failures open it                                                                   |
| `open`      | Calls are skipped, not attempted. | After the current wait, one probe is allowed and the state becomes `half-open`. The first wait is `minCooldownMs` |
| `half-open` | One call is being trusted.        | Success closes it; a failure reopens it with the wait doubled, up to `cooldownMs`                                 |

A skipped call emits `l2:skipped` or `event-bus:publish-skipped` carrying the state, so the breaker opening is something you can alert on rather than infer from a latency graph.

Tune with numbers. `failureThreshold` defaults to 3, `minCooldownMs` to 1,000 and `cooldownMs` to 30,000. A low threshold trips on a single blip. The backoff keeps a short outage short: a Sentinel or Cluster failover of a few seconds is probed again after one second, while a long outage is probed at most every thirty seconds. Raise `minCooldownMs` if each failed probe is expensive.

A store that can tell when its client has reconnected does not wait for the backoff at all: `RedisStore` reports the ioredis `ready` event, and the breaker lets the next call through as a probe at once. The same goes for the event bus: when it reports `ready` or `subscribed`, invalidations it missed are resent immediately. A custom store opts in with `onReady(listener)` returning a function that stops listening (`ReadyNotifyingStore`; `defineStore` accepts it too).

A probe only succeeds once the Redis client has reconnected. After a Sentinel or Cluster failover, the client's first reconnect often goes to the address of the server that just stopped, which never answers, and ioredis waits `connectTimeout` (10 s by default) before trying the new primary. `setupCache` sets it to 2 s on the clients it creates. Set it yourself on a client you pass in:

```ts
new Redis({
  sentinels,
  name: 'mymaster',
  connectTimeout: 2_000,
  commandTimeout: 2_000,
  failoverDetector: true, // reconnect as soon as Sentinel switches primaries
})
```

In the fleet harness, with the 10 s default, servers skipped Redis for about 15 s after a Sentinel promotion that took 3 s.

<Note>
  **Invalidations the bus misses are sent again.** When a publish fails, or the event-bus breaker skips it, the cache remembers which keys it invalidated and retries every 250 ms (while the breaker allows) until the bus takes them. Peers then drop their copies and read the current value. A `set` is resent as a delete of the key, because its value may be out of date by then. The cache remembers up to 10,000 keys and 64 patterns; past that it sends one delete of every key, which costs peers their memory tier but never leaves them stale. `event-bus:publish-skipped` and `event-bus:publish-error` still tell you the bus is failing.
</Note>

## Writes Redis missed are repaired [#writes-redis-missed-are-repaired]

If a `set` or `delete` cannot reach Redis, or the L2 breaker skips it, Redis may still hold the value that change was meant to replace. Reading that key from Redis would serve it, so the cache remembers the key and skips Redis for it until the change is repaired. Repair deletes the key from Redis, so the next read loads the current value from your loader, and peers are told to drop their copies too.

Repairs are retried every 5 s, up to 128 keys a pass, and at once when the Redis client reports it is ready again. A failed pattern delete blocks every key it matches until whatever it should have removed has expired. Past 10,000 remembered keys or 64 patterns, the cache stops reading Redis altogether for as long as any value there can live, rather than risk serving an old one. Every one of these limits is fixed, so an outage cannot grow memory without bound.

## Stale fallback [#stale-fallback]

When a loader fails, you often have a perfectly serviceable slightly older answer sitting in memory. Stale fallback returns it instead of propagating the error.

It is on by default with a 30,000 ms window. Set `staleTtlMs` when you need a different recovery window.

<CodeGroup>
  ```js title="src/cache/index.js"
  export const cache = new LazyLayersCache({
    ttlMs: 5 * 60 * 1000,

    failSafe: {
      // How long past normal expiry a value stays usable as a fallback.
      staleTtlMs: 60_000,
    },
  })
  ```

  ```ts title="src/cache/index.ts"
  const options: LazyLayersCacheOptions<string, User> = {
    ttlMs: 5 * 60 * 1000,

    failSafe: {
      // How long past normal expiry a value stays usable as a fallback.
      staleTtlMs: 60_000,
    },
  }

  export const cache = new LazyLayersCache<string, User>(options)
  ```
</CodeGroup>

With the built-in L1, a value becomes a fail-safe snapshot when it expires from L1 or is evicted by the entry limit, and stays servable for `staleTtlMs` past its expiry. Values removed to free memory are not kept, because keeping them would free nothing. With another L1 store, values are remembered when they are written. If the loader then throws, the stale value is returned and `stale:hit` is emitted with a reason of `loader-error`, `soft-timeout`, or `hard-timeout`.

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

  cache.on((event) => {
    if (event.type === 'stale:hit') {
      logger.warn({ key: event.key, reason: event.reason }, 'served stale')
    }
  })
  ```

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

  cache.on((event: CacheEvent) => {
    if (event.type === 'stale:hit') {
      logger.warn({ key: event.key, reason: event.reason }, 'served stale')
    }
  })
  ```
</CodeGroup>

<Warning>
  Stale data is still stale. This is the right trade for a product page and the wrong trade for a permission check, payment state, or order transition. Scope it per call rather than globally when only some reads can tolerate an old answer.
</Warning>

Stale fallback is also what makes a soft timeout meaningful, which is the next section. To serve a snapshot at once and refresh in the background even when the loader is healthy, turn on [`staleWhileRevalidate`](/docs/guides/batches-and-freshness#stale-while-revalidate).

## L1 pressure does not turn an L2 hit into a miss [#l1-pressure-does-not-turn-an-l2-hit-into-a-miss]

The built-in L1 shares a byte budget with its stale snapshots. During memory pressure it evicts stale snapshots first, then entries chosen by the eviction policy, and can reject a new L1 promotion. An L2 hit still returns to the caller. It simply does not consume more local heap, and emits `promotion:bypassed` with `pressure` or `budget`.

Peer priming follows the same rule. Under pressure, a received value removes an obsolete L1 entry before the replacement promotion is bypassed. The server then reads the shared value from L2 on demand instead of knowingly serving the old L1 copy.

Treat sustained `promotion:bypassed` events as a capacity signal. Check the instance memory limit, payload sizes, `admission.maxEntryBytes`, and L2 latency before increasing `maxMemory`. The budget is not a process RSS guarantee, so an oversized L1 ceiling can still leave too little heap for the application.

## Loader timeouts [#loader-timeouts]

A loader with no ceiling can hold a request open for as long as the origin is willing to keep the socket alive, which on a struggling database can be minutes. Two timeouts bound that, and they exist for different reasons.

<CodeGroup>
  ```js title="src/cache/index.js"
  export const cache = new LazyLayersCache({
    ttlMs: 5 * 60 * 1000,

    failSafe: { staleTtlMs: 60_000 },

    timeouts: {
      // Latency budget. Needs fail-safe on and a stale value present.
      softMs: 200,
      // Absolute ceiling. Always applies.
      hardMs: 2_000,
    },
  })
  ```

  ```ts title="src/cache/index.ts"
  const options: LazyLayersCacheOptions<string, User> = {
    ttlMs: 5 * 60 * 1000,

    failSafe: { staleTtlMs: 60_000 },

    timeouts: {
      // Latency budget. Needs fail-safe on and a stale value present.
      softMs: 200,
      // Absolute ceiling. Always applies.
      hardMs: 2_000,
    },
  }

  export const cache = new LazyLayersCache<string, User>(options)
  ```
</CodeGroup>

| Timeout  | Requires                                     | Effect                              |
| -------- | -------------------------------------------- | ----------------------------------- |
| `softMs` | Fail-safe on **and** a stale value available | Stop waiting, serve the stale value |
| `hardMs` | Nothing                                      | Give up on the loader entirely      |

The soft timeout is a latency budget. You already hold an answer that is slightly old, so you return it rather than making the user wait for a fresher one. The hard timeout is for a loader that is not coming back. When the soft path applies it takes precedence, so a request never waits `hardMs` when a stale answer was available at `softMs`.

### Pass the signal to your I/O [#pass-the-signal-to-your-io]

Both timeouts abort the loader's `AbortSignal`. That is the only lever the cache has, because it cannot reach inside your database client and cancel a query it never issued.

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

  export async function getUser(id) {
    return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
      // Passing the signal is what makes the timeout cancel work rather than
      // just stop waiting for it.
      const res = await fetch(`${process.env.USER_API}/users/${id}`, { signal })
      return res.ok ? res.json() : undefined
    })
  }
  ```

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

  export async function getUser(id: string): Promise<User | undefined> {
    return cache.getOrSet(`user:${id}`, async ({ signal } = {}) => {
      // Passing the signal is what makes the timeout cancel work rather than
      // just stop waiting for it.
      const res = await fetch(`${process.env.USER_API}/users/${id}`, { signal })
      return res.ok ? (res.json() as Promise<User>) : undefined
    })
  }
  ```
</CodeGroup>

<Warning>
  A loader that ignores its signal keeps running after the timeout fires. Under sustained pressure you accumulate abandoned queries that still hold connections, which is the failure mode the timeout was supposed to prevent.
</Warning>

## Negative caching [#negative-caching]

Asking repeatedly for something that does not exist means running the loader repeatedly. A crawler walking deleted IDs, or a client retrying a 404, will happily push full origin load through a cache that only remembers hits.

Negative caching records the absence. A loader that resolves to `undefined` writes a short lived negative entry, and later reads for that key return `undefined` without calling the loader, emitting `miss` with level `negative`.

<CodeGroup>
  ```js title="src/cache/index.js"
  export const cache = new LazyLayersCache({
    ttlMs: 5 * 60 * 1000,

    negativeCache: {
      // Keep it short. This is the window in which a newly created record
      // still looks absent.
      ttlMs: 10_000,
      maxEntries: 5_000,
    },
  })
  ```

  ```ts title="src/cache/index.ts"
  const options: LazyLayersCacheOptions<string, User> = {
    ttlMs: 5 * 60 * 1000,

    negativeCache: {
      // Keep it short. This is the window in which a newly created record
      // still looks absent.
      ttlMs: 10_000,
      maxEntries: 5_000,
    },
  }

  export const cache = new LazyLayersCache<string, User>(options)
  ```
</CodeGroup>

A positive `ttlMs` is required. Without one, nothing is recorded. `maxEntries` bounds the map, and the oldest entry is evicted when the cap is reached.

Ten seconds is usually enough to absorb a retry storm while staying short enough that a just created record becomes visible quickly. A `delete` on the key clears the negative entry immediately, so writing through your own API stays consistent regardless of the TTL.

## Watching failures [#watching-failures]

Every failure path emits an event. A reasonable production subscription:

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

  cache.on((event) => {
    switch (event.type) {
      case 'l2:error':
        // Carries the breaker state, so you can alert on the transition to open.
        metrics.increment('cache.l2.error', { operation: event.operation, state: event.state })
        break
      case 'l2:skipped':
        metrics.increment('cache.l2.skipped', { state: event.state })
        break
      case 'stale:hit':
        metrics.increment('cache.stale', { reason: event.reason })
        break
      case 'loader:timeout':
        metrics.increment('cache.loader.timeout')
        break
      case 'event-bus:publish-error':
        metrics.increment('cache.bus.error')
        break
      case 'event-bus:publish-skipped':
        // Remember: these events are dropped, not queued for retry.
        metrics.increment('cache.bus.skipped')
        break
    }
  })
  ```

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

  cache.on((event: CacheEvent) => {
    switch (event.type) {
      case 'l2:error':
        // Carries the breaker state, so you can alert on the transition to open.
        metrics.increment('cache.l2.error', { operation: event.operation, state: event.state })
        break
      case 'l2:skipped':
        metrics.increment('cache.l2.skipped', { state: event.state })
        break
      case 'stale:hit':
        metrics.increment('cache.stale', { reason: event.reason })
        break
      case 'loader:timeout':
        metrics.increment('cache.loader.timeout')
        break
      case 'event-bus:publish-error':
        metrics.increment('cache.bus.error')
        break
      case 'event-bus:publish-skipped':
        // Remember: these events are dropped, not queued for retry.
        metrics.increment('cache.bus.skipped')
        break
    }
  })
  ```
</CodeGroup>

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

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

<CardGroup cols="2">
  <Card title="Resilience" icon="shield-check" href="/docs/concepts/resilience">
    The same behaviours as a concept, plus the full table of what is on by default.
  </Card>

  <Card title="Cache events" icon="list" href="/docs/reference/cache-events">
    Every event these features emit, with its exact payload fields.
  </Card>

  <Card title="Event buses" icon="tower-broadcast" href="/docs/guides/event-buses#the-retry-queue">
    How the retry queue buffers a failed publish, and why the breaker bypasses it.
  </Card>
</CardGroup>


## Questions

### What happens when Redis is down?

Reads skip L2 and reach your loader, and the L2 circuit breaker stops calling Redis until its cooldown passes. A request can still fail when the loader fails with no eligible stale value, the origin gate is full, or a lock deadline passes.

### How long is a stale value served after the loader fails?

For `failSafe.staleTtlMs` past the value's expiry: 30 seconds by default. A deleted or invalidated key is never served this way.