---
title: 'Cache Helpers'
description: 'Cache oRPC procedure output with tag-based revalidation, stale-while-revalidate, storage adapters, and a handler plugin that reflects cache tags in HTTP headers.'
sidebar:
  label: 'Cache'
---

## Installation

```package-install
npm install @orpc/experimental-cache@beta
```

## Basic Usage

The `CacheStore` interface has three methods: `getOrSet` returns the entry under a key, filling it on a miss, `revalidate` invalidates entries by tag, and `encodeKey` turns any value into a key. Use an adapter or write your own:

| Name                                               | Adapter for                                                                                |
| -------------------------------------------------- | ------------------------------------------------------------------------------------------ |
| [`MemoryCacheStore`](#memory)                      | In-memory storage                                                                          |
| [`RedisCacheStore`](#redis)                        | [Redis](https://github.com/redis/redis)                                                    |
| [`UpstashCacheStore`](#upstash)                    | [Upstash Redis](https://github.com/upstash/redis-js)                                       |
| [`BunRedisCacheStore`](#bun-redis)                 | [Bun's Redis](https://bun.com/docs/runtime/redis)                                          |
| [`VercelCacheStore`](#vercel)                      | [Vercel Runtime Cache](https://vercel.com/docs/caching/runtime-cache)                      |
| [`CacheableCacheStore`](#cacheable)                | [Cacheable](https://cacheable.org)                                                         |
| [`WorkersCacheStore`](#cloudflare-workers-caching) | [Cloudflare Workers Caching](https://developers.cloudflare.com/workers/cache/), purge only |

```ts twoslash
import { MemoryCacheStore } from '@orpc/experimental-cache/memory'
// ---cut---
const store = new MemoryCacheStore()

const entry = await store.getOrSet('planet:1', async () => ({ id: 1, name: 'Earth' }), {
  tags: ['planets', 'planet:1'],
  ttl: 60_000,
})

await store.revalidate({ tags: ['planets'] }) // the next `getOrSet` fills again
```

An entry is fresh for `ttl`, then stale for `swr`: the next read refreshes it, in the background when `waitUntil` is given. Durations are in milliseconds.

## Cache Middleware

The `cache` helper creates middleware that caches the output of [procedures](/docs/procedure). A hit skips the handler. Every option accepts a value or a function of the middleware options and input.

`key` defaults to the procedure path and input. Set it when:

- The procedure is called outside a router, such as with `call` or `.callable()`.
- `cache` comes before `.input()`.
- The input holds a Blob, File, event iterator, or stream.

Keep `tags` the same for a key, and list the tags of any cached procedure the handler calls.

```ts
import type { CacheContext } from '@orpc/experimental-cache'
import { cache } from '@orpc/experimental-cache'
import { MemoryCacheStore } from '@orpc/experimental-cache/memory'

const findPlanet = os
  .$context<CacheContext>()
  .input(z.object({ id: z.number() }))
  .use(
    cache({
      key: (_, input) => `planet:${input.id}`,
      tags: (_, input) => ['planets', `planet:${input.id}`],
      ttl: 60_000, // default is never stale
      swr: 300_000, // default is 0
    }),
  )
  .handler(({ input }) => {
    return { id: input.id, name: `Planet ${input.id}` }
  })

const store = new MemoryCacheStore() // one store for the whole app

const handler = new RPCHandler({ planet: { find: findPlanet } })
const { response } = await handler.handle(request, {
  context: { 'cache/store': store },
})
```

:::warning
Everyone using a key shares its entry. When the output depends on the requester, put the requester in the `key` or resolve `enabled` to `false`. A hit skips every middleware after `cache`, so check permissions before it.
:::

:::warning
Blob, File, [AsyncIteratorObject](/docs/async-iterator-object), and stream outputs cannot be cached. Declare `.output()` after `cache`, so only validated output is stored.
:::

### Stale While Revalidate

Past `ttl` but within `swr`, an entry is stale. Pass `cache/waitUntil` to return the stale output at once and refresh in the background:

```ts
export default {
  async fetch(request, env, ctx) {
    const { response } = await handler.handle(request, {
      context: {
        'cache/store': store,
        'cache/waitUntil': ctx.waitUntil.bind(ctx),
      },
    })

    return response ?? new Response('Not Found', { status: 404 })
  },
}
```

On long-running servers, `(promise) => promise.catch(console.error)` is enough. Without `cache/waitUntil`, the call waits for the refresh, and returns the stale output when it fails.

## Revalidate Middleware

The `revalidate` helper creates middleware that revalidates tags after the procedure succeeds, typically on mutations. `tags` is a list or a function of the middleware options, input, and output.

```ts
import { revalidate } from '@orpc/experimental-cache'

const updatePlanet = os
  .$context<CacheContext>()
  .input(z.object({ id: z.number(), name: z.string() }))
  .use(revalidate({ tags: (_, input) => [`planet:${input.id}`] }))
  .handler(({ input }) => {
    return input
  })
```

## Handler Plugin

The `CacheHandlerPlugin` reports cache activity in response headers. Only the headers you list are set:

- `orpc-cache-tag`: the tags the response depends on.
- `orpc-cache-tag-invalidation`: the tags the request revalidated.
- `cache-tag`: the same tags, for caches in front such as CDNs.
- `cache-control`: `public` with `max-age` and `stale-while-revalidate` from what is left of `ttl` and `swr`, unless the procedure set its own.

```ts
import { CacheHandlerPlugin } from '@orpc/experimental-cache'

const handler = new RPCHandler(router, {
  plugins: [
    new CacheHandlerPlugin({
      headers: ['orpc-cache-tag', 'orpc-cache-tag-invalidation'],
    }),
  ],
})
```

:::warning
`cache-control` is sent as `public`. List it only when no cached procedure depends on the requester.
:::

:::info[Response Caches in Front]
With `cache-control` and `cache-tag` listed, a cache in front serves GET responses without reaching your server. Pair it with a store that purges it, such as [`WorkersCacheStore`](#cloudflare-workers-caching). Browsers cache them too, and no purge reaches a browser.
:::

:::tip[Cross-Origin Clients]
For cross-origin browser clients, expose the headers with [CORSPlugin](/docs/plugins/cors):

```ts
new CORSPlugin({
  exposeHeaders: ['orpc-cache-tag', 'orpc-cache-tag-invalidation'],
})
```

:::

:::info
The `handler` can be any supported oRPC handler, such as [RPCHandler](/docs/rpc/handler), [OpenAPIHandler](/docs/openapi/handler), or a custom one.
:::

## Link Plugin

The `CacheLinkPlugin` reads `orpc-cache-tag` and `orpc-cache-tag-invalidation` from responses, for client cache integrations such as the [TanStack Query](#tanstack-query) plugin.

```ts
import { CacheLinkPlugin } from '@orpc/experimental-cache'

const link = new RPCLink({
  url: '/rpc',
  plugins: [new CacheLinkPlugin()],
})
```

:::info
The `link` can be any supported oRPC link, such as [RPCLink](/docs/rpc/link), [OpenAPILink](/docs/openapi/link), or a custom one.
:::

## TanStack Query

`CacheRevalidationUtilsPlugin` is a [TanStack Query](/docs/integrations/tanstack-query#plugins) plugin that refetches the queries a mutation revalidated by cache tag. It requires the [Handler Plugin](#handler-plugin) with both tag headers and the [Link Plugin](#link-plugin):

```ts
import { CacheLinkPlugin } from '@orpc/experimental-cache'
import { CacheRevalidationUtilsPlugin } from '@orpc/experimental-cache/tanstack-query'

const link = new RPCLink({
  url: '/rpc',
  plugins: [new CacheLinkPlugin()],
})

const orpc = createTanstackQueryUtils(createORPCClient(link), {
  plugins: [new CacheRevalidationUtilsPlugin()],
})
```

:::info
Streamed and live queries are not covered. Data set with `setQueryData` is refetched by the first mutation that revalidates tags.
:::

:::tip[Server-Side Rendering]
Queries rendered through a [server-side client](/docs/client/server-side) carry no tags, so the first mutation that revalidates refetches them. To keep their tags, render through a link whose `fetch` calls the handler directly.
:::

When several utils share a query client, give each its own [`prefix`](/docs/integrations/tanstack-query#setup).

## Tiered Store

`TieredCacheStore` layers stores front to back, such as memory in front of Redis. A miss in one tier fills from the next, and a revalidation reaches every tier. Every tier but the last needs a `ttl` cap, since an in-process tier is only revalidated on its own instance.

```ts
import { TieredCacheStore } from '@orpc/experimental-cache'
import { MemoryCacheStore } from '@orpc/experimental-cache/memory'
import { RedisCacheStore } from '@orpc/experimental-cache/redis'
import { createClient } from 'redis'

const store = new TieredCacheStore([
  { store: new MemoryCacheStore(), ttl: 5_000 },
  { store: new RedisCacheStore(createClient({ url: process.env.REDIS_URL })) },
])
```

## Adapters

Entries without a `ttl` are dropped after `defaultRetention`. When a cached output changes shape between deploys, change the store's `prefix`.

### Memory

Stores entries in the process, for development, testing, and single-instance deployments. It has no size limit, so set a `ttl` on procedures with client-supplied input. Tag counters are never dropped, so do not revalidate an unbounded set of tags.

```ts
import { MemoryCacheStore } from '@orpc/experimental-cache/memory'

const store = new MemoryCacheStore({
  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: undefined,

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
```

### Redis

Stores entries in Redis, and works with Redis Cluster. Pass a [`RedisLocker`](/docs/helpers/lock) to coalesce fills across processes.

:::warning
Run Redis with `noeviction` or a `volatile-*` policy. Tag counters never expire, so do not revalidate an unbounded set of tags.
:::

```ts
import { RedisCacheStore } from '@orpc/experimental-cache/redis'
import { RedisLocker } from '@orpc/experimental-lock/redis'
import { createClient } from 'redis'

const client = createClient({ url: 'redis://localhost:6379' })

const store = new RedisCacheStore(client, {
  /**
   * The prefix to use for Redis keys.
   *
   * @default ''
   */
  prefix: '',

  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: new RedisLocker(client, { prefix: 'cache-lock:', ttl: 10_000 }),

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
const tenantStore = store.prefix('tenant:123:')
```

`store.prefix()` returns a store under a longer prefix that shares the client and options.

For another Redis client, extend `BaseRedisCacheStore` from `@orpc/experimental-cache/base-redis`. For another key-value backend, extend `BaseKeyValueCacheStore` from `@orpc/experimental-cache/base-key-value`.

### Upstash

The [Redis](#redis) adapter for Upstash's REST client. Pass an [`UpstashLocker`](/docs/helpers/lock) to coalesce fills across instances.

```ts
import { UpstashCacheStore } from '@orpc/experimental-cache/upstash'
import { UpstashLocker } from '@orpc/experimental-lock/upstash'
import { Redis } from '@upstash/redis'

const redis = Redis.fromEnv()

const store = new UpstashCacheStore(redis, {
  /**
   * The prefix to use for Redis keys.
   *
   * @default ''
   */
  prefix: '',

  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: new UpstashLocker(redis, { prefix: 'cache-lock:', ttl: 10_000 }),

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
const tenantStore = store.prefix('tenant:123:')
```

### Bun Redis

The [Redis](#redis) adapter for Bun's built-in Redis client, from `@orpc/bun`. Pass a [`BunRedisLocker`](/docs/helpers/lock#bun-redis) to coalesce fills across processes.

```ts
import {
  experimental_BunRedisCacheStore as BunRedisCacheStore,
  experimental_BunRedisLocker as BunRedisLocker,
} from '@orpc/bun'
import { redis } from 'bun'

const store = new BunRedisCacheStore(redis, {
  /**
   * The prefix to use for Redis keys.
   *
   * @default ''
   */
  prefix: '',

  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: new BunRedisLocker(redis, { prefix: 'cache-lock:', ttl: 10_000 }),

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
const tenantStore = store.prefix('tenant:123:')
```

### Vercel

Stores entries in the [Vercel Runtime Cache](https://vercel.com/docs/caching/runtime-cache). A revalidation that lands during a fill is not detected, so set a `ttl`.

```ts
import { VercelCacheStore } from '@orpc/experimental-cache/vercel'
import { getCache } from '@vercel/functions'

const store = new VercelCacheStore({
  /**
   * The Vercel Runtime Cache to use.
   *
   * @default getCache()
   */
  cache: getCache(),

  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: undefined,

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
```

### Cacheable

Stores entries through a [Cacheable](https://cacheable.org) instance. A revalidation that lands during a fill is not detected, so set a `ttl`.

:::warning
Tag counters live in the secondary store, or the primary without one. Give that store no default `ttl` and no eviction.
:::

```ts
import { CacheableCacheStore } from '@orpc/experimental-cache/cacheable'
import KeyvRedis from '@keyv/redis'
import { Cacheable } from 'cacheable'

const cacheable = new Cacheable({
  secondary: new KeyvRedis('redis://localhost:6379'),
})

const store = new CacheableCacheStore(cacheable, {
  /**
   * Serializer for keys and cached outputs.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,

  /**
   * Coalesces concurrent fills of one key.
   *
   * @default new MemoryLocker({ ttl: 60_000 })
   */
  locker: undefined,

  /**
   * How long entries without a `ttl` are kept, in milliseconds.
   *
   * @default 30 days
   */
  defaultRetention: undefined,
})
```

### Cloudflare Workers Caching

A purge-only store from `@orpc/cloudflare`. [Workers Caching](https://developers.cloudflare.com/workers/cache/) caches responses in front of the Worker through the `cache-control` and `cache-tag` headers of the [Handler Plugin](#handler-plugin), and `revalidate` purges the tags. It requires `"cache": { "enabled": true }` in your wrangler configuration.

```ts
import { experimental_WorkersCacheStore as WorkersCacheStore } from '@orpc/cloudflare'

const store = new WorkersCacheStore({
  /**
   * The Workers Caching purge surface, such as `ctx.cache`.
   *
   * @default cache from `cloudflare:workers`
   */
  cache: undefined,

  /**
   * Serializer for keys. Nothing is stored under them; they only identify a lookup.
   *
   * @default RPCJsonSerializer
   */
  serializer: undefined,
})
```
