# Invalidation (https://lazy-layers-cache.vercel.app/docs/concepts/invalidation)

> Why keeping copies honest is hard, invalidating by key, pattern or tag, the three events that travel between servers, and what stops a late event undoing a delete.



To invalidate a cache across several Node.js instances, commit the database write, then call `invalidate(key)`. lazy-layers-cache removes the key from L1, L2 and in-flight state, and publishes a delete on the event bus so every peer drops its own L1 copy. `invalidateByPattern('tenant:42:*')` covers a key family, and `invalidateTags(['store:7'])` a group with no common prefix. TTLs remain the safety net for an event that does not arrive.

A cache is a copy, and a copy has no way of knowing when the original changed. Nobody tells it. Correctness depends entirely on something else remembering to say so, at the right moment, to every server holding a copy, and none of those three is guaranteed by anything in the system.

That is the whole of why invalidation has a reputation. It is not one hard problem. It is three, and they fail independently.

## Living on TTLs alone [#living-on-ttls-alone]

The simplest answer is to admit you will be wrong and put a clock on it. Cache for 60 seconds, accept that a write can be invisible for up to 60 seconds, move on.

This works right up until you write down what you are actually choosing.

| TTL        | Worst case staleness | Loads per key per hour, per server |
| ---------- | -------------------- | ---------------------------------- |
| 1 hour     | 1 hour               | 1                                  |
| 60 seconds | 60 seconds           | 60                                 |
| 5 seconds  | 5 seconds            | 720                                |
| 1 second   | 1 second             | 3,600                              |

Staleness and origin load are the same dial turned in opposite directions, and the dial is badly shaped. Almost every expiry is wasted work, because most keys did not change during their TTL. You reload a value 3,600 times an hour to catch the one write that happened at minute 34, and you are still stale for up to a second when it does.

Worse, TTL gives you no way to say "this one is wrong now". A price changed, a permission was revoked, a user deleted their account, and the cache keeps serving the old answer until a timer that knows nothing about any of it happens to fire.

## Saying it out loud instead [#saying-it-out-loud-instead]

An event bus lets the server that made the change tell everyone else. Peers that receive the event can discard their copy before its TTL expires. Delivery can be delayed or missed, so the bus does not provide a fixed staleness guarantee.

TTL does not go away. It changes job, from being the mechanism that keeps the cache honest to being the safety net for the case where a message did not arrive.

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

  export async function updateUser(id, patch) {
    // Invalidate after the write commits. Until it does, the cached value is
    // still the truth, and a delete now would only reload the old row.
    const updated = await db.users.update(id, patch)

    // Drops the key from L1, L2, the negative cache, the stale copy and any
    // in-flight promise, here and on every peer.
    await cache.delete(`user:${id}`)

    // A whole prefix at once. This scans L2, so keep the prefix narrow.
    await cache.deleteByPattern(`user:${id}:sessions:*`)

    return updated
  }
  ```

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

  export async function updateUser(id: string, patch: Partial<User>): Promise<User> {
    // Invalidate after the write commits. Until it does, the cached value is
    // still the truth, and a delete now would only reload the old row.
    const updated = await db.users.update(id, patch)

    // Drops the key from L1, L2, the negative cache, the stale copy and any
    // in-flight promise, here and on every peer.
    await cache.delete(`user:${id}`)

    // A whole prefix at once. This scans L2, so keep the prefix narrow.
    await cache.deleteByPattern(`user:${id}:sessions:*`)

    return updated
  }
  ```
</CodeGroup>

<Warning>
  `deleteByPattern('*')` scans the entire keyspace on every server that receives it. Prefix patterns tightly, and never build one out of user input.
</Warning>

## Invalidating by tag [#invalidating-by-tag]

A key names one value. A tag names a group that has no common prefix: every product in a store, every page that shows one user, everything a price change touches. Tag values when you write or load them, and invalidate the group in one call.

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

// Every value tagged store:7, in every layer, on every server.
await cache.invalidateTags(['store:7'])
```

Nothing is scanned or deleted one by one, so the cost does not grow with the number of tagged entries:

* **Tokens.** Every tag has a token, a random id, and a tagged entry records the token of each of its tags as they were when its value was loaded. `invalidateTags` gives each tag a new token, and an entry whose recorded token no longer matches reads as a miss.
* **No clocks.** Tokens are compared, never ordered, so clocks on different servers do not matter.
* **No races.** Two invalidations at once need no coordination: each replaces the token.
* **Loads in flight.** A load that started before the invalidation stores its value under the old token. The caller that waited gets it, but it is never served afterwards.
* **Shared tokens.** With an L2, tokens are kept there, under reserved keys beginning `__lazy-layers:tag:`, so every server agrees. A token record that is missing, for example because Redis evicted it, is replaced by a new one, which turns its tag's entries into misses rather than reviving them.
* **Peers.** They learn of an invalidation through the bus, as a `del` of each tag's reserved key. Releases without tags delete that key, which they never hold, and carry on.
* **Without a bus.** Another server notices within `tagCheckMs`: 1 second by default, or the L1 TTL when that is shorter. A server trusts a token it read for that long, and reads tokens in steady use again in the background before the time runs out, so reads never wait for it. `tagCheckMs: 0` reads the tokens before every read of a tagged value.
* **While L2 is down.** Tokens cannot be read, so a server uses the last token it knew for each tag: tagged values are still served and cached, and nothing newer could be learned anyway. An invalidation made on this server during the outage still takes effect here.
* **Reading for tags.** `getOrSet` with `tags` serves a value only if it was stored with every one of them. A value stored without them, by a plain `set` or by a release before 8.0, is loaded again and stored with its tags, so invalidating any of them reaches it.

Limits and trade-offs:

* An entry carries at most 32 tags, each up to 256 characters. Tags belong to the whole cache, not to a namespace.
* Tagged values are kept by the built-in L1 and by an encoded L2 such as Redis. A custom L1 or a value-only L2 does not store them, so they are always loaded.
* A tagged value is never kept as a fail-safe snapshot, never remembered as a miss, and not broadcast to peers' L1. Peers read it from L2 instead.
* A tagged record in L2 starts with `HC1T`, which releases before 8.0 read as a miss. During a rolling upgrade they load and store their own untagged copy; an 8.0 server reading the key for its tags treats that copy as a miss and stores a tagged one. Only the L1 of a server still running 0.7 keeps its copy, until its L1 TTL, so finish the upgrade before relying on `invalidateTags`.
* Reading a tagged value checks its tokens, which costs nothing while they are known. A server learns a new token by reading it from L2 the first time it needs it, one read per tag. It remembers up to 50,000 tokens and reads a forgotten one again when next needed.

## Three event types, one of which carries a value [#three-event-types-one-of-which-carries-a-value]

| Type      | Published by                                   | What a peer does with it                                                                                                      |
| --------- | ---------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `del`     | `cache.delete(key)`                            | Publisher deletes L2; peers remove local L1, negative, stale and in-flight state                                              |
| `pattern` | `cache.deleteByPattern(p)` and `cache.clear()` | Drops every local entry whose key matches the pattern                                                                         |
| `set`     | a `getOrSet` loader resolving                  | L2-backed peers read their own authoritative snapshot and promote its current value/TTL; L1-only peers use the scoped payload |

`del` and `pattern` say only what to forget. `set` is the one that carries the loaded value itself, which is what turns a fleet of caches from a group that all reload independently into one where a single server's query warms everybody. That path is the [lazy fan-out](/docs/concepts/lazy-loading#the-lazy-fan-out), and it has two caveats worth knowing before you rely on it.

Events carry `source`, `ts`, an `id`, optional `namespace`/`keyTypes`, and, for tracked `del` and `set`, a per-key `generation`. Managed setup scopes events to its normalized namespace. Scoped receivers reject old untagged publishers; stage publisher upgrades or use separate channels during rollout.

A delayed set payload cannot replace newer protected Redis state through peer priming: the receiver reads its own L2 and subtracts the elapsed snapshot/decode time from its TTL before promotion. Observable transport gaps, invalid deliveries and bounded-queue overflow make local data untrusted; subscription recovery conservatively flushes L1. Ordinary Pub/Sub publisher loss still requires authoritative reconciliation for a strict freshness contract.

## Buses lose, duplicate, and reorder [#buses-lose-duplicate-and-reorder]

A message bus is not a promise of correctness. It is a promise of best effort, and everything it does badly can undo an invalidation:

* it can deliver the same event twice
* it can deliver events out of order
* it can deliver your own event back to you
* it can fail to deliver at all, to a server that was disconnected

Three mechanisms handle the first three. The fourth is a property of the transport you chose, not something a cache can fix, which is why [choosing an event bus](/docs/guides/event-buses) is a real decision.

### Dedupe by event ID [#dedupe-by-event-id]

Every published event gets an `id`. Each server keeps the IDs it has already applied and drops repeats, emitting `invalidation:duplicate` instead of applying the work a second time.

The set of remembered IDs is bounded on both axes: `eventDedupeMaxEntries` defaults to 10,000 and `eventDedupeTtlMs` defaults to five minutes. Redelivery outside that window is applied again, which is safe for a delete and merely wasteful for a `set`.

An event that arrives without an `id`, from an older peer, gets a synthetic one built from its source, timestamp, type and keys, so it still deduplicates.

### Filter your own events [#filter-your-own-events]

A server that publishes an event also receives it back on a fanout bus. Applying it would mean undoing its own work, so `event.source === this.source` returns early and nothing happens.

This is why `source` has to be unique per server. Leave it unset and a random identifier is generated per process, which works but tells you nothing when you are reading logs. Set it to something stable and recognisable, such as the pod name or instance ID.

<Warning>
  Two servers sharing one `source` value will each ignore the other's events, believing them to be their own. This is a silent correctness bug, not an error.
</Warning>

### Late events cannot resurrect a deleted value [#late-events-cannot-resurrect-a-deleted-value]

This is the one that matters most, because it is the failure that produces a wrong answer rather than a redundant one.

Every server keeps a per-key generation counter. Deleting a key advances it, and the published `del` event carries the new number. A `set` event carries the generation the value was loaded at.

A lower-generation `set` hint is dropped and emits `invalidation:stale`. A lower-generation `del` still invalidates local copies because the publisher may have restarted and reset its counter. Versioned caches also stop versioned caching on this ambiguity until recreated, rather than returning an older version namespace.

```mermaid
sequenceDiagram
    participant A as Server A
    participant Bus as Event bus
    participant B as Server B
    A->>A: loader resolves user:42 at generation 0
    A->>Bus: set user:42, generation 0
    B->>B: delete user:42, local generation becomes 1
    B->>Bus: del user:42, generation 1
    Bus-->>B: set user:42, generation 0 arrives late
    B->>B: 0 is lower than 1, drop it
```

Without the counter, that late `set` would write a deleted user back into B's L1 and it would stay there until its TTL expired. With it, the delete wins no matter which order the messages land in.

Three honest limits on this:

* Equal generations do not impose a total order. L2-backed set hints read the current authoritative snapshot; L1-only peers retain payload-based ordering.
* The counters live in memory, per server. A restart resets them to zero. Accepted deletes always remove local copies; a lower delete counter makes versioned state ambiguous and triggers conservative bypass.
* `pattern` events carry no generation at all, so they apply whenever they arrive. One more reason to keep patterns narrow.

Turning on `versioning` goes further and folds the generation into the storage key itself, so an old value is not merely ignored, it is not addressable. [Event ordering](/docs/architecture/event-ordering) has the full picture.

## What invalidation still does not give you [#what-invalidation-still-does-not-give-you]

It is worth being clear about the boundary. This machinery keeps copies from disagreeing under normal bus behaviour. It is not a consensus protocol.

On an observed disconnect or invalid delivery, local state becomes untrusted and is conservatively flushed on subscription recovery. A publisher failure that the receiver cannot observe still needs authoritative reconciliation for strict freshness; ordinary Pub/Sub does not preserve lost events.

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

<CardGroup cols="2">
  <Card title="Event ordering" icon="arrow-down-1-9" href="/docs/architecture/event-ordering">
    The three ordering mechanisms in detail, and exactly what is not guaranteed.
  </Card>

  <Card title="Choosing an event bus" icon="tower-broadcast" href="/docs/guides/event-buses">
    What each transport promises a server that was offline when the event went out.
  </Card>

  <Card title="Lazy loading" icon="bolt" href="/docs/concepts/lazy-loading">
    The `set` event from the other side, where one server's query warms the fleet.
  </Card>
</CardGroup>


## Questions

### Should I invalidate before or after the database write?

After it commits. Invalidating first lets a concurrent loader read the old row and cache it again. Invalidation is separate from the database transaction, so an application that must retry a failed invalidation needs durable delivery of its own.

### What is the difference between pattern and tag invalidation?

A pattern such as `tenant:42:*` matches key names, so it scans L1 and L2 for them. A tag names a group whose keys share no prefix; `invalidateTags` gives the tag a new token instead of scanning, so its cost does not grow with the number of tagged entries.

### Can a late event bring back a deleted value?

Not for single keys: `del` and `set` events carry a per-key generation, and a peer drops a `set` older than its last delete. Pattern events carry no generation, so they have no ordering protection.