# Execution paths (https://lazy-layers-cache.vercel.app/docs/architecture/execution-paths)

> The exact order of operations for a read, a write and an invalidation, traced against src/cache/hybridCache.ts.



Three paths do all the work. This page traces each one step by step, in the order the code actually runs them, because the ordering is where the surprises live.

If you read only three things here, read [where the in-flight promise is registered](#where-the-in-flight-promise-is-registered), [where the bus publish happens](#the-broadcast-happens-after-the-local-write), and [when the generation counter moves](#invalidation). Each of those is an ordering people assume incorrectly, and each one changes what your system does under load.

## The read path [#the-read-path]

`getOrSet` is the whole read. It resolves a value from the cheapest place that has it, and only reaches your loader when nothing does.

```mermaid
flowchart TB
    A["getOrSet key"] --> SL1{"built-in L1 hit, no negative entry?"}
    SL1 -->|yes| R["return the value"]
    SL1 -->|no| IF{"load in flight for this key?"}
    IF -->|yes| J["join it: same promise"]
    IF -->|no| LEAD["register as the key's leader, before any await"]
    LEAD --> NEG{"negative entry?"}
    NEG -->|yes| U["return undefined"]
    NEG -->|no| L2G["l2 read through the circuit breaker, taking the lease when empty"]
    L2G --> H2{"found?"}
    H2 -->|yes| P["write into L1"] --> E2["emit hit L2"] --> R
    H2 -->|no| RECHECK{"negative entry now?"}
    RECHECK -->|yes| U
    RECHECK -->|no| SWR{"stale-while-revalidate and a snapshot?"}
    SWR -->|yes| ST["return the snapshot, refresh in the background"]
    SWR -->|no| LOAD["load with the distributed lock"]
```

Step by step:

<Steps>
  <Step title="Resolve the storage key">
    Normally this is your key unchanged. With `versioning.enabled` set to `true`, the key's current generation counter is appended, so `user:42` becomes `user:42::v3`.
  </Step>

  <Step title="Read the built-in L1 without awaiting">
    When local invalidation state is trusted and no negative entry is recorded for the key, `getOrSet` reads the built-in L1 synchronously. A hit emits `hit` with level `L1` and returns at once: nothing leaves the process, and no promise is waited on. With `earlyRefresh`, a hit past the refresh point also starts one background reload; the caller still gets the current value. A custom L1 store is read asynchronously in the L2 step instead.
  </Step>

  <Step title="Join a load in flight">
    A live in-flight entry for the key means `inflight:reuse` is emitted and the caller receives the leader's own promise. It does not read L2 and does not call the loader.
  </Step>

  <Step title="Become the key's leader">
    Otherwise the caller registers an in-flight entry for the key and only then starts reading. There is no `await` between the L1 check and this registration, so two callers cannot both become leader, and every caller that arrives later shares the L2 read as well as the load.
  </Step>

  <Step title="Check the negative cache, then read L2 through the circuit breaker">
    A key recorded as a known miss emits `miss` with level `negative` and returns `undefined`, with no L2 round trip. Otherwise L2 is read. Every L2 call goes through the same wrapper: if the breaker is open the call is skipped and `l2:skipped` is emitted; if the call rejects, `l2:error` is emitted and the read becomes a miss rather than an exception. With RedisStore's v2 key layout and the lock on, the read takes the key's lease in the same script when the key is empty. With no L2, a key the built-in L1 just missed has nowhere else to be, so nothing more is read.
  </Step>

  <Step title="Promote an L2 hit into L1">
    On a healthy hit the encoded value is written into L1 **before** being returned, then `hit` with level `L2` is emitted. Under memory pressure or without enough room in the local byte target, `promotion:bypassed` is emitted and the L2 value is returned without growing L1.
  </Step>

  <Step title="Re-check the negative cache">
    The L2 round trip is a window, and a concurrent loader on this server can record a negative entry inside it. So the check runs again after the read returns nothing, and a negative entry found here returns `undefined`.
  </Step>

  <Step title="Serve stale while revalidating">
    With `staleWhileRevalidate` on and a fail-safe snapshot held for the key, the snapshot is returned at once and the key is reloaded in the background. Otherwise the load starts.
  </Step>
</Steps>

### Where the in-flight promise is registered [#where-the-in-flight-promise-is-registered]

Before the first `await`. A caller that misses the built-in L1 and finds no live leader registers itself as the key's leader, then reads L2 and loads. Callers that arrive while it is unsettled share its promise, so a cold-key burst on one process costs one L2 read and one loader call. Followers are counted in bulk rather than each allocating an entry.

Accepted followers are bounded by `inflight.maxWaiters` (10,000 across one cache by default) and the shared memory budget. Overflow throws `InflightOverloadError` without starting another loader.

<Note>
  `benchmarks/herd.mjs` fires 10,000 concurrent `getOrSet` calls at a single cold key and counts loader calls. With dedupe on, the default, that is 1 loader call and 9,999 in-flight reuses. With dedupe off it is 10,000 loader calls. Both runs assert every caller received the correct value, so the collapse cannot come from dropping requests.
</Note>

Registration itself runs in this order:

<Steps>
  <Step title="Honour an explicit opt out">
    If `inflight.enabled` is `false`, either on the call or on the cache, the read and load run immediately and no entry is registered.
  </Step>

  <Step title="Prune an expired entry">
    Only the queried key is checked for expiry on this path; maintenance work is bounded. Unless explicitly set, `inflight.ttlMs` covers the loader hard timeout, the distributed wait budget when locking is active, and a 50 ms margin, with a 5,000 ms minimum. Default lifetimes are 10,050 ms without locking and 20,100 ms with Redis locking.
  </Step>

  <Step title="Join a live entry if there is one">
    A live promise for the key means `inflight:reuse` is emitted and that same promise is returned. The loader is not called. This is where 9,999 of the 10,000 callers end up.
  </Step>

  <Step title="Check the tracking cap">
    `inflight.maxEntries` bounds tracked keys (1,024 by default in the raw constructor). When tracking is full, a new key bypasses dedupe and emits `inflight:bypass` with reason `maxEntries`, but finite leader and origin admission still apply; bypass does not grant unlimited origin work.
  </Step>

  <Step title="Register, then read">
    The entry is stored under the key with an `expiresAt`, and the read and load start on the next microtask, so a store or loader that calls back into the cache finds the key already in flight. The leader removes the entry when it settles, on both settlement paths.
  </Step>
</Steps>

A load that throws therefore leaves no poisoned entry behind for later callers to join.

## Load and store [#load-and-store]

Everything below happens inside the promise that was just registered.

<Steps>
  <Step title="Start the clock and the AbortController">
    A fresh `AbortController` is created per load, and `loader:start` is emitted.
  </Step>

  <Step title="Call the loader">
    Your loader is invoked with `{ signal }` **once**, immediately, before any timeout race is set up. Which race it is then entered into depends on configuration, but the call itself has already happened and does not vary.
  </Step>

  <Step title="Race it, if a timeout applies">
    `softMs` applies only when all three of fail-safe enabled, a `softMs` value, and a stale value for this key are true together. Otherwise `hardMs` applies if it is set. Otherwise the loader is awaited with no ceiling. On a timeout the signal is aborted, `loader:timeout` is emitted, and a timeout error is thrown into the next step. No timer is armed for a loader that settles before the event loop turns: loads are noted in an array, and one shared `setImmediate` arms timers only for those still running.
  </Step>

  <Step title="Handle a failure">
    Any throw, from your loader or from a timeout, emits `loader:error` with the elapsed duration. If a stale value exists **and** fail-safe is enabled, `stale:hit` is emitted with a reason of `loader-error`, `soft-timeout` or `hard-timeout`, and the stale value is returned. Otherwise the error is rethrown and reaches your caller.
  </Step>

  <Step title="Handle undefined">
    `loader:success` is emitted first. Then, if the value is `undefined`, a negative entry is recorded, and a stale value is returned in its place when fail-safe is enabled. &#x2A;*Nothing is written to either layer and nothing is published.** An absent value is not a cache write.
  </Step>

  <Step title="Write the layers">
    Without the lock, L1 first, then L2 through the circuit breaker. The built-in L1 commits synchronously; another store is awaited. With RedisStore and the lock, the value is published to L2 and the lease released in one script (`publishAndRelease`), and L1 is written after that succeeds. Then any negative entry for the key is cleared and `set` is emitted with the levels that are active. Both layer writes finish before the next step begins.

    A separate fail-safe snapshot is kept only when L1 does not hold the value. The built-in L1 hands one over when the value expires or is evicted by the entry limit.
  </Step>

  <Step title="Broadcast">
    Only now, and only when a bus is configured, `broadcastSet` is not `false`, and the value has no tags. Tagged values are not broadcast; peers read them from L2.
  </Step>
</Steps>

### The broadcast happens after the local write [#the-broadcast-happens-after-the-local-write]

The local write is fully awaited before the broadcast block is entered, and the publish itself is awaited too. Your `getOrSet` caller is still waiting while the event goes out.

```mermaid title="Write and Broadcast Pipeline"
sequenceDiagram
    participant C as Caller
    participant Cache as getOrSet
    participant DB as Loader
    participant L1
    participant L2
    participant Bus as Event bus
    C->>Cache: getOrSet user:42
    Cache->>L1: miss
    Cache->>L2: miss
    Cache->>DB: loader runs once
    DB-->>Cache: value
    Cache->>L1: set
    Cache->>L2: set through the breaker
    Cache->>Cache: emit set
    Cache->>Cache: encode the event, measure bytes
    Cache->>Bus: publish set event, awaited
    Cache-->>C: value
```

The broadcast itself is three steps:

<Steps>
  <Step title="Build the event">
    A `set` event carrying a fresh ID, the key, the loaded value itself, the effective `ttlMs`, this server's `source`, a timestamp, and the key's current generation counter. A `set` does not advance that counter.
  </Step>

  <Step title="Measure it">
    The entire event is encoded with the normal serializer and its byte length is measured. If `broadcastSetMaxBytes` is set and the encoded event exceeds it, `set:broadcast-skipped` is emitted with `reason: 'max-bytes'`, `bytes` and `maxBytes`, and nothing is published. The local write stands and peers read the value from L2 when they need it.
  </Step>

  <Step title="Publish it">
    Otherwise `set:broadcast` is emitted and the event is published. If the bus circuit breaker is open, the publish is skipped with `event-bus:publish-skipped`. If the publish rejects, `event-bus:publish-error` is emitted and the rejection is swallowed. Either way the cache remembers the key and resends it, as a delete, once the bus takes events again. Neither outcome fails the read.
  </Step>
</Steps>

<Warning>
  `broadcastSetMaxBytes` has no default. Without it, a 5 MB value is encoded and sent in full to every server on the bus. Pick the ceiling from what your bus and your servers can absorb, not from what your largest value happens to be, because a broadcast is sent once and received by everyone.
</Warning>

## Load with the distributed lock [#load-with-the-distributed-lock]

This runs between in-flight registration and the loader whenever the L2 supports locking, unless locking is explicitly disabled. Cold starts and cache expiry use this same path.

<Steps>
  <Step title="Try to acquire">
    A random token identifies the owner. With RedisStore's v2 key layout the lease was already requested by the L2 read above, in the same script, so this step adopts it. An initial Redis failure falls through to the existing fail-open loader path. A lock held by another instance starts a bounded wait instead.
  </Step>

  <Step title="Recheck and load while renewing">
    A lease taken by the read needs no recheck: nothing could have filled the key in between. A store that acquires separately reads the cache again after acquisition, so a value published since the original miss avoids another load. RedisStore renews the token's lease at roughly one third of its lifetime. A separate local expiry deadline bounds a hung renewal. Detected ownership loss aborts the loader signal and discards a late loader result. Cleanup stops renewal and releases only this token's lock.
  </Step>

  <Step title="Wait for a result or retry acquisition">
    Waiters sleep until they are woken, or until the next poll: `reconcileMs` with an event bus, `pollMs` without. They are woken by the owner's `set` broadcast, by its lease announcement, or directly when the owner is on the same instance. They then read the key, taking the lease in the same operation where the store supports it, so a failed or crashed owner is replaced by one waiter at once. Once contention has been observed, later Redis errors do not trigger an automatic unlocked load.
  </Step>

  <Step title="Bound the wait without starting another load">
    The default budget is `max(lock ttlMs, loader hardMs) + pollMs`, initially 10,050 ms. At the deadline the cache emits `lock:timeout`, returns eligible stale data or throws `DistributedLockTimeoutError`. An explicit `onTimeout: 'load'` restores the unlocked fallback. Redis command latency is governed by your Redis client timeouts.
  </Step>
</Steps>

## Write [#write]

A write touches five things and, on its own, tells nobody.

<Steps>
  <Step title="Resolve the storage key">
    Appending the generation when versioning is on.
  </Step>

  <Step title="Encode and write L1">
    Synchronous for the built-in store, which owns the encoded record and enforces byte admission before retaining it; awaited for other stores.
  </Step>

  <Step title="Write L2 through the circuit breaker">
    Awaited. A matching-format Redis store reuses the encoded value. A failure emits 

    `l2:error`

     and is swallowed, so the L1 write stands alone.
  </Step>

  <Step title="Keep a fail-safe snapshot">
    Only when fail-safe is enabled, 

    `staleTtlMs`

     is positive, and the shared stale-byte budget permits it. With the built-in L1, no separate copy is taken while L1 holds the value; L1 hands over a snapshot when the value expires or is evicted by the entry limit.
  </Step>

  <Step title="Clear the negative entry and emit">
    Any recorded miss for this key is dropped, then 

    `set`

     is emitted with the active levels.
  </Step>
</Steps>

That is the whole write. It is what step six of the load above runs, and the broadcast that follows it there is a separate step performed by `getOrSet`, not by the write itself.

<Warning>
  A direct `cache.set()` runs exactly those five steps and stops. It never publishes to the bus, and it never advances a generation counter. Peers learn about the value only when they read L2 themselves, or when a later invalidation reaches them. If you want the fan-out, the write has to come from a `getOrSet` loader.
</Warning>

## Invalidation [#invalidation]

`delete` is local first, published second, and the order inside the local part is what makes the published event correct.

<Steps>
  <Step title="Drop the in-flight promise, the negative entry and the stale copy">
    All three, before any layer is touched. Dropping the in-flight promise is what stops a load that is already running from writing the value back after the delete.
  </Step>

  <Step title="Resolve the storage key, then advance the generation">
    In that order. The key is captured at its current version, and only then is the counter incremented by one. With versioning on, that is what makes the delete remove the pre-delete key rather than a version that was never written.
  </Step>

  <Step title="Delete from L1, then L2">
    Both awaited, with the L2 delete going through the circuit breaker like every other L2 call.
  </Step>

  <Step title="Emit delete, then publish">
    The published `del` event carries the generation read **after** the increment, so peers receive the new number and any older event still in flight loses the comparison against it.
  </Step>
</Steps>

`deleteByPattern` follows the same shape with two differences: the in-flight, negative and stale maps are swept for matching keys rather than one key being removed, and the published `pattern` event carries **no generation at all**. Pattern invalidations have no ordering protection. `clear()` is `deleteByPattern('*')`.

<Warning>
  `deleteByPattern('*')` scans your entire keyspace on every server. Prefix patterns tightly, and never build one from user input.
</Warning>

On the receiving side, after an event has passed the three [ordering checks](/docs/architecture/event-ordering):

| Inbound event | What the peer does                                                                                                                                                                                            |
| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `del`         | Raises the local counter to the maximum of local and incoming, then runs the same local delete across L1, L2, negative, stale and in-flight                                                                   |
| `set`         | Raises the counter to the maximum, then writes the value into **L1 only**, keeps a fail-safe snapshot when L1 does not hold it, clears the negative entry and the in-flight promise, and emits `set:received` |
| `pattern`     | Runs the local pattern delete immediately, with no generation check                                                                                                                                           |

A remote `set` never writes L2. The shared copy comes from the publishing server's own write.

## Watching the order [#watching-the-order]

The event stream is emitted in execution order, so subscribing to it is the cheapest way to confirm any of the above against your own configuration.

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

  // hit L1, or miss L1 then hit L2, or miss both then loader:start,
  // loader:success, set, set:broadcast, in that order.
  cache.on((event) => console.log(event.type, 'key' in event ? event.key : ''))

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

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

  // hit L1, or miss L1 then hit L2, or miss both then loader:start,
  // loader:success, set, set:broadcast, in that order.
  cache.on((event: CacheEvent) => console.log(event.type, 'key' in event ? event.key : ''))

  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   // undefined records a negative entry, writes nothing
    })
  }
  ```
</CodeGroup>

## Three orderings worth memorising [#three-orderings-worth-memorising]

1. **The in-flight leader is registered before the L2 read.** Concurrent callers on one process share one L2 read and one loader call.
2. **The bus publish happens after the local write, and is awaited.** L1 and L2 both hold the value before any peer hears about it, and the caller waits for the publish.
3. **The generation counter advances before the layer deletes, and the published number is the new one.** That is why a late `set` from before the delete loses the comparison on every peer.

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

<CardGroup cols="2">
  <Card title="Event ordering" icon="arrow-down-1-9" href="/docs/architecture/event-ordering">
    What a peer does with the event this page publishes, and the three checks it passes first.
  </Card>

  <Card title="Resilience" icon="shield-check" href="/docs/concepts/resilience#circuit-breakers">
    The breaker that wraps every L2 call above, and the numbers to size it with.
  </Card>

  <Card title="Walkthrough" icon="route" href="/docs/walkthrough">
    The same journey told as a story, following one key from a cold miss into a peer.
  </Card>
</CardGroup>
