Cache Helpers
Cache oRPC procedure output with tag-based revalidation, stale-while-revalidate, storage adapters, and a handler plugin that reflects cache tags in HTTP headers.
Installation
npm install @orpc/experimental-cache@betapnpm add @orpc/experimental-cache@betayarn add @orpc/experimental-cache@betabun add @orpc/experimental-cache@betanub add @orpc/experimental-cache@betaaube add @orpc/experimental-cache@betaBasic 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 |
In-memory storage |
RedisCacheStore |
Redis |
UpstashCacheStore |
Upstash Redis |
BunRedisCacheStore |
Bun’s Redis |
VercelCacheStore |
Vercel Runtime Cache |
CacheableCacheStore |
Cacheable |
WorkersCacheStore |
Cloudflare Workers Caching, purge only |
const const store: MemoryCacheStorestore = new new MemoryCacheStore(options?: BaseKeyValueCacheStoreOptions): MemoryCacheStoreIn-memory cache store with tag-based invalidation, intended for
development, testing, and single-instance deployments. Expired and
revalidated entries are replaced when their key is filled again, and
otherwise swept on a later write.MemoryCacheStore()
const const entry: CacheEntryentry = await const store: MemoryCacheStorestore.BaseKeyValueCacheStore.getOrSet(key: string, compute: () => Promisable<unknown>, options?: CacheGetOrSetOptions): Promise<CacheEntry>Resolves the entry under `key`, filling it with the output of `compute` on
a miss. Implementations may coalesce concurrent callers of one key into
one fill. A stale entry within `swr` is refreshed, in the background when
`waitUntil` is given. An entry stored under other tags than the lookup's,
or the same in another order, counts as a miss. A lifetime of zero stores
nothing.getOrSet('planet:1', async () => ({ id: numberid: 1, name: stringname: 'Earth' }), {
CacheGetOrSetOptions.tags?: readonly string[] | undefinedTags associated with the entry. Revalidating any of them invalidates the entry.tags: ['planets', 'planet:1'],
CacheGetOrSetOptions.ttl?: number | undefinedFresh lifetime in milliseconds. `undefined` or `Infinity` means the entry never becomes stale.ttl: 60_000,
})
await const store: MemoryCacheStorestore.MemoryCacheStore.revalidate({ tags }: CacheRevalidateOptions): Promise<void>Invalidates every entry associated with any of the given tags.revalidate({ CacheRevalidateOptions.tags: readonly [string, ...string[]]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. 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
callor.callable(). cachecomes 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.
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 },
})
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:
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.
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:publicwithmax-ageandstale-while-revalidatefrom what is left ofttlandswr, unless the procedure set its own.
import { CacheHandlerPlugin } from '@orpc/experimental-cache'
const handler = new RPCHandler(router, {
plugins: [
new CacheHandlerPlugin({
headers: ['orpc-cache-tag', 'orpc-cache-tag-invalidation'],
}),
],
})
Link Plugin
The CacheLinkPlugin reads orpc-cache-tag and orpc-cache-tag-invalidation from responses, for client cache integrations such as the TanStack Query plugin.
import { CacheLinkPlugin } from '@orpc/experimental-cache'
const link = new RPCLink({
url: '/rpc',
plugins: [new CacheLinkPlugin()],
})
TanStack Query
CacheRevalidationUtilsPlugin is a TanStack Query plugin that refetches the queries a mutation revalidated by cache tag. It requires the Handler Plugin with both tag headers and the Link Plugin:
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()],
})
When several utils share a query client, give each its own prefix.
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.
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.
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 to coalesce fills across processes.
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 adapter for Upstash’s REST client. Pass an UpstashLocker to coalesce fills across instances.
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 adapter for Bun’s built-in Redis client, from @orpc/bun. Pass a BunRedisLocker to coalesce fills across processes.
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. A revalidation that lands during a fill is not detected, so set a ttl.
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 instance. A revalidation that lands during a fill is not detected, so set a ttl.
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 caches responses in front of the Worker through the cache-control and cache-tag headers of the Handler Plugin, and revalidate purges the tags. It requires "cache": { "enabled": true } in your wrangler configuration.
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,
})