# Asking once per request

> cache() — one lookup, however many places need it, and with a key and a lifetime, however many requests.

Middleware checks who you are, the layout shows their name, and the page reads
their permissions. Wrap the lookup in `cache()`, and those three calls make one:

```ts
import { cache } from '@rsc-kit/core/cache'

export const currentUser = cache(async () => db.user(await sessionId()))
```

## Calling it more than once

Call it wherever you need it. The first call runs, and the rest get the same
answer:

```tsx
export async function middleware() {
  if (!(await currentUser())) redirect('/login')
}

export default async function Page() {
  const user = await currentUser()   // already resolved

  return <h1>Hello {user.name}</h1>
}
```

Without options, an answer lasts one request. Two requests in flight never see
each other's answers, and nothing survives into the next one, so one visitor
never sees another's data.

React's `cache()` is the same idea, but it isn't open yet when middleware runs,
which is where the duplicate lookups start.

## Arguments

Arguments are compared the way React compares them: primitives by value,
objects by identity.

```ts
const post = cache(async (id: string) => db.post(id))

post('a')   // runs
post('a')   // reuses the first
post('b')   // runs
```

Two objects that look the same are two different calls, so pass an id rather
than an object.

## Across requests

For an answer that is the same for every visitor, such as a page built in the
panel, a menu or a price list, give `cache()` a key and a lifetime:

```ts
import { cache } from '@rsc-kit/core/cache'

export const findPage = cache(
  async (slug: string) => db.pages.findBySlug(slug),
  { key: 'pages.find', revalidate: 3600, tags: ['pages'] },
)
```

Each request still asks once. Across requests, the answer for each list of
arguments is kept for `revalidate` seconds.

- **`key`** names the function in the store. Use the same key on every
  instance, and a different key for every function.
- **Arguments and answers are JSON.** A `Date` comes back as a string, on the
  first call as well as later ones.
- **It runs as nobody.** `cookies()` and `headers()` throw inside it, and a call
  to Laravel or Go carries no session. A kept answer is handed to every visitor,
  so it must not be about one of them.
- **A deploy starts empty.** Keys include the build, so a new deploy never reads
  what an old one kept.

### Saying the data changed

When the data changes, call `changed()` with its tag,
and the next ask misses at once:

```ts
'use server'
import { changed } from '@rsc-kit/core/changed'

export async function savePage(values: PageValues) {
  await db.pages.save(values)
  await changed('pages')
}
```

`tags` can also be a function of the arguments, for a tag per record:

```ts
cache(findBySlug, { key: 'pages.find', revalidate: 3600, tags: (slug) => [`page:${slug}`] })
```

`changed()` is the same call that refreshes open tabs for
[live data](/guides/live-data), and a page kept with [ISR](/guides/isr) that
read the answer renders again too.

Nothing is purged. Each kept answer's key includes its tags' versions, so a
change makes a new key, and the old entry is never read again.

`changed()` reaches every instance only when the versions are shared, as set up
for [live data](/guides/live-data-in-production#where-the-versions-live). With
the default in-memory versions, another instance sees a change once its kept
answer expires, after at most `revalidate` seconds.

### Where answers are kept

By default answers are kept in memory: the 1,000 most recently used, up to
64 MB of them, one copy per instance. To share them across instances, install a store. It needs only a
`get` and a `set`:

```ts title="src/instrumentation.ts"
import { installCacheStore } from '@rsc-kit/core/cache'

// Redis
installCacheStore(() => ({
  get: (key) => redis.get(key),
  set: (key, value, ttl) => redis.set(key, value, 'EX', ttl),
}))

// Workers KV (60 seconds is KV's shortest expiry)
installCacheStore(() => ({
  get: (key) => env.CACHE.get(key),
  set: (key, value, ttl) => env.CACHE.put(key, value, { expirationTtl: Math.max(60, ttl) }),
}))
```

A store that fails makes pages slower, not broken: the engine warns once and
does the lookup itself.
