In the previous lesson we classified AgendaViva's holes and decided which ones aren't needed. The tool for closing them is one line: 'use cache'. Writing it isn't hard. What takes care is understanding what it promises: that the result depends only on what goes in, that it can be stored and that anyone can receive it.
You'll see where the directive goes, what makes up the key of each entry, what can be passed in and returned, why it can't read cookies, where entries are stored in each kind of deployment and when its remote and private variants are needed. Then we'll apply it to AgendaViva's queries, and face the consequence announced in 04-02: building will need a database.
- The first cached function
Cache Components has been enabled since 01-02 with cacheComponents: true and partialPrefetching: true. Without the first option, the directive doesn't exist. Let's start with the query that pays off most, the districts:
// lib/data/venues.ts
export async function listDistricts(): Promise<string[]> {
'use cache'
const db = await getDb()
const rows = await db
.selectDistinct({ district: venues.district })
.from(venues)
.orderBy(asc(venues.district))
return rows.map(({ district }) => district)
}Nothing else changes: not the signature, not the callers. With that line:
- The first call runs the query and stores the result.
- The following ones, in the same render or on someone else's visit, return what was stored.
- When prerendering, the function is run and awaited. It stops being a hole and its result can go into the shell.
The third effect is the one that changes the page. An ordinary cache saves queries; this one also moves content from the request to the build.
An entry doesn't last forever. Unless told otherwise, the default profile applies: it's renewed every 15 minutes, in the background. Lifetimes are the topic of 05-03, where we'll make them explicit; until then the default will do.
- Where it's written
| Level | What's stored | When |
|---|---|---|
| Data function | The returned value | Almost always: several pages benefit from it |
| Component | The returned JSX, already rendered | If building the result is costly, or if the data isn't used anywhere else |
| File | All its exported functions | Modules entirely dedicated to it |
In all three cases, the functions must be async. A cached component looks like what you already know:
// Example only: AgendaViva caches the data
async function VenueTable() {
'use cache'
const venues = await listVenues()
return (
<table>
<tbody>
{venues.map((venue) => (
<tr key={venue.id}>
<td>{venue.name}</td>
<td>{venue.capacity}</td>
</tr>
))}
</tbody>
</table>
)
}Storing the JSX saves the render as well, but it ties the cache to a presentation. In AgendaViva we put it in lib/data/, next to the query, for three reasons: the event page, the quick view and, later on, the metadata share the same entry; the invalidation rules stay in one place; and whoever reads the function sees how long it may take to update.
2.1. Why not at file level
Putting 'use cache' on the first line of lib/data/events.ts looks convenient. We don't do it:
- It would cache everything, including
getAvailabilityandsuggestEvents, which mustn't be. - The exported functions could be imported from a Client Component and called as if they were Server Functions. It's a documented feature, but it opens up to the browser a layer we decided to close in 03-05.
- Constants don't survive.
EVENTS_PER_PAGEwould disappear for the client; shared values have to live in another file.
Inside each function, the decision is visible where it's made. A couple more limits: the directive can't go on a Route Handler's GET itself, only on a helper function that it calls; and in proxy.ts it has no effect (07-02).
- The key
Each combination of inputs gets its own cache entry. The key is made up of:
| Part | Consequence |
|---|---|
Build ID, or deploymentId if configured |
Every deployment starts with an empty cache |
| Function ID, based on its location and signature | Two identical functions in different files don't share |
| Serialized arguments (props, for a component) | Each combination, one entry |
| Variables captured from the enclosing function | They count too, even though they aren't visible in the signature |
| In development, a reload marker | Editing the code invalidates |
The fourth one deserves an example:
async function Overview({ venueId }: { venueId: string }) {
async function count(category: Category) {
'use cache'
// Key: venueId (captured) and category (argument)
return countEvents(venueId, category)
}
return <p>{await count('concert')} concerts</p>
}It works, and it's easy to capture too much without noticing: a large object, a filter that's always changing. Prefer functions at the top level of the module, with explicit arguments. The signature then becomes a contract: whatever isn't in it can't influence the result.
Arguments are compared by their serialized content. That's an important difference from React.cache, which compared by identity (04-03):
React.cache |
'use cache' |
|
|---|---|---|
| Lasts | One request | As long as its lifetime says, across visitors |
| Compares | Identity | Content: { district: 'Northside' } is a hit even if it's another object |
| Stores | The promise, in memory | The serialized result |
| Goes into the shell | No | Yes |
| Accepts request data | Yes | No |
| Returns | The same reference | A copy |
Since 'use cache' also avoids repeated calls within the same render, functions that use it don't need React.cache, and the preloading from 04-03 keeps working with them. React.cache stays where there's request data, as in getPreferredDistrict.
3.1. How many entries
A cache only pays off if the keys repeat. With the district there are four or five values: nearly everything is a hit. With the search text, every visitor types something different: thousands of entries nobody will ask for again are stored, and they evict the useful ones.
What's more, many keys come from the URL. If a cached function accepts any district, anyone requesting ?district=a1, ?district=a2… can fill the memory at will. Two measures, which we'll apply in section 7:
- Validate against a known set before entering the cache.
- Leave out arguments with unbounded values. Cache by the dimension with few values and query the rest, or filter it in memory.
- What goes in and what comes out
Inputs and the result travel serialized, with rules similar to those in 03-03, but not identical in both directions:
| Type | As an argument | As a result |
|---|---|---|
Primitives, null, undefined |
Yes | Yes |
| Plain objects, arrays | Yes | Yes |
Date, Map, Set, ArrayBuffer and typed arrays |
Yes | Yes |
| JSX | Pass-through only | Yes |
| Functions and Server Actions | Pass-through only | No |
Class instances, URL, symbols, WeakMap |
No | No |
Drizzle's events are plain objects with Dates, so they pass through as they are. What doesn't pass is db: it's an instance with connections. That's why each function calls getDb() inside, instead of receiving it.
4.1. Pass-through: children and slots
"Pass-through only" means the cached component can place it in its result, but not look at it, modify it or call it. It allows a cached frame with dynamic content, the composition from 03-03:
// Example only
async function VenueFrame({ slug, children }: { slug: string; children: ReactNode }) {
'use cache'
const venue = await getVenueBySlug(slug)
return (
<section>
<h2>{venue?.name}</h2>
{children}
</section>
)
}
// The child isn't stored: it's rendered on every request, inside its boundary
<VenueFrame slug="mill-theater">
<Suspense fallback={<p>Checking…</p>}>
<TodaysSpots />
</Suspense>
</VenueFrame>children isn't part of the entry. For the same reason, a cached layout doesn't cache the pages it contains. Server Actions (module 6) can pass through a cached component in the same way, down to the form that uses them.
4.2. Promises as arguments
A promise can be passed, but there's a catch. If it depends on the request, like unknown params or cookies(), the cached function will wait for it while prerendering and it will never arrive. The build hangs and, after 50 seconds, fails:
Error: Filling a cache during prerender timed out, likely because request-specific arguments such as params, searchParams, cookies() or uncached data were used inside "use cache".
The same happens if you fetch someone else's promise from a global Map. Our globalThis.agendaVivaDb doesn't carry that risk: it stores the pool, not results. The rule: resolve outside, pass values.
// Wrong: the cached function waits for request data
<Details params={params} /> // with 'use cache' inside Details
// Right: the dynamic component waits; the cached function receives a string
async function EventContent({ params }: Pick<Props, 'params'>) {
const { slug } = await params
const details = await getEventDetails(slug)
// …
}
- What it can't do
A cached function runs in an isolated environment. Inside it:
| Operation | Result |
|---|---|
cookies(), headers(), searchParams |
Error |
connection() |
Error: it requires a real request |
draftMode() |
You can read isEnabled, but not enable or disable it |
io() |
Resolves instantly |
Date.now(), Math.random() |
Allowed: the value is stored with the entry |
Reading what something else stored with React.cache |
It doesn't see it: it has its own scope |
| Writing to the database, sending emails | Possible, and a mistake: it won't run on every call |
The ban in the first row follows the call stack. If listUpcomingEvents called getPreferredDistrict, and that called cookies(), it would fail all the same, with the next-request-in-use-cache error. On a route rendered at request time, the failure may not show up at build time and only appear with next start: don't rely on the build alone.
It makes sense with the question from 04-05: if Ana's result is stored, who receives it? The correct pattern is already in YourDistrictEvents: the personal part is read outside, and what goes into the cache is a district, shared by all its residents.
The io() row is what makes everything we wrote in module 4 fit together. getDb() starts with await io(): outside a cache, it stops prerendering and leaves the hole; inside one, it does nothing and the query runs. The same function works for both cases, without parameters or duplicates. With connection() that wouldn't have been possible.
And the one about unpredictable values: reading the clock stops being an error because now it's been stated what it means, "the moment this entry was prepared". We'll use it in 05-03 to filter by date.
- Where it's stored
The result is serialized in RSC format and ends up in several places:
| Store | What it contains | Scope |
|---|---|---|
| Prerendered output | The shell's HTML and RSC Payload | On disk, or in the platform's durable storage |
| Server memory | The entries, in an LRU cache | One process |
| Browser | The RSC Payload of what was visited and prefetched | One tab |
The shell is the most profitable: there's no need to even look up the entry. The second store handles whatever is outside it, such as the results of /events, which depend on searchParams. And there, the environment matters a lot:
| Deployment | Runtime entries |
|---|---|
| Your own server, one process | They persist between requests until they expire, are evicted or the server restarts |
| Several processes or containers | Each has its own; invalidating in one doesn't affect the others |
| Serverless | They usually don't persist: each request may land on a different instance |
The memory size is limited with cacheMaxMemorySize. On a serverless platform, what was computed at build time is always reused; what's computed at runtime, rarely. Check your provider's documentation, because it may replace the store with another one.
And in every case, a new deployment starts from scratch, because the key includes the build ID. It's deliberate: between two versions, the function or the shape of its result may have changed. Expect a spike in queries after deploying.
6.1. use cache: remote
'use cache: remote' stores the entry in a store shared by all instances, which is configured with cacheHandlers or provided by the platform. It trades an expensive query for a network round trip, so it pays off when two conditions hold at once: the content is outside the shell and its keys repeat a lot.
| Pays off | Doesn't pay off |
|---|---|
| API with a request limit | Query that already takes under 50 ms |
| Database that can't handle spikes | Nearly unique keys (searches, per-user data) |
| Costly computation after reading the request | Data that changes every few seconds |
| Unreliable external service | Content that's already in the shell |
If you don't configure anything, it uses the same memory as the ordinary directive. AgendaViva doesn't need it on a single server; we'll come back to it when deploying (11-04 and 11-05).
6.2. use cache: private
'use cache: private' is the exception to the cookie rule: it can read cookies(), headers() and searchParams, because in production the result isn't stored on any server between requests. It's only reused within the request and, afterwards, in the browser's memory, for the stale time.
'use cache' |
remote |
private |
|
|---|---|---|---|
| Stores on the server | Memory | Shared store | No |
| Shared between visitors | Yes | Yes | No |
| Reads cookies and headers | No | No | Yes |
| Goes into the static shell | Yes | Yes | No |
connection() |
No | No | No |
It's designed for two cases: compliance requirements that prevent storing certain data on the server, and code that can't be restructured to pass the value as an argument. If you can extract the value, extract it. You also can't nest remote and private inside each other.
- AgendaViva's queries
7.1. Venues
Add 'use cache' as the first line of listVenues, listVenueSummaries and getVenueBySlug, as well as listDistricts. The third no longer needs cache:
// lib/data/venues.ts
export async function getVenueBySlug(slug: string): Promise<Venue | null> {
'use cache'
const db = await getDb()
const [venue] = await db.select().from(venues).where(eq(venues.slug, slug)).limit(1)
return venue ?? null
}VenuesPage doesn't change: it still hands VenueSearch the promise from listVenueSummaries(). Since it now resolves during prerendering, the list goes into the shell and the skeleton is no longer seen.
A detail that gets forgotten: the null is stored too. If someone visits a venue that doesn't exist yet and it's created afterwards, its absence will keep being shown until the entry expires or is invalidated. We'll take that into account in 05-04.
7.2. Events
In lib/data/events.ts, put the directive in listUpcomingEvents, getEventBySlug, getEventDetails, listVenueEvents and listRelatedEvents. The ones that were wrapped in cache become ordinary functions:
// lib/data/events.ts
export async function getEventDetails(slug: string): Promise<EventDetailsData | null> {
'use cache'
const db = await getDb()
// … the same query
}preloadVenueEvents doesn't change. getAvailability and suggestEvents stay uncached, the first because it's volatile and the second because of the variety of search texts. And listEvents is split up: the current function is renamed queryEvents and is no longer exported, and a new one decides whether it's worth storing:
// lib/data/events.ts (imports listDistricts and the Category type)
const CACHED_PAGES = 5
export async function listEvents(
filters: EventFilters = {},
): Promise<EventPage> {
const { category, district, q } = filters
const page = filters.page ?? 1
if (district && !(await listDistricts()).includes(district)) {
return { events: [], total: 0, page: 1, totalPages: 1 }
}
// What hardly ever repeats isn't stored
if (q || page > CACHED_PAGES) return queryEvents(filters)
return queryCachedEvents(category, district, page)
}
async function queryCachedEvents(
category: Category | undefined,
district: string | undefined,
page: number,
): Promise<EventPage> {
'use cache'
return queryEvents({ category, district, page })
}
async function queryEvents(filters: EventFilters): Promise<EventPage> {
// … the body that listEvents had
}- The number of entries is bounded: five categories (four plus none) times the districts plus "none", times five pages. With three districts that's a hundred at most.
- The district is validated first, and doing so is free because
listDistrictsis already cached. As a bonus, a made-up district no longer reaches the query. - Separate arguments instead of the object. The function accepts objects, but this way you can see what the entry depends on, and
qcan't sneak in. - The pages are still none the wiser.
listEventskeeps its signature.
Even though the response is cached, /events is still ◐: the list depends on searchParams. What you gain is that the hole is resolved without querying.
7.3. Isolating the spots
The cached event page contains spotsLeft, which goes stale. We move that piece of data into its own component:
// app/(public)/events/_components/event-availability.tsx
import { getAvailability } from '@/lib/data/events'
import { LiveAvailability } from './live-availability'
export async function EventAvailability({ slug }: { slug: string }) {
const availability = await getAvailability(slug) // Uncached: queried on every visit
if (!availability) return null
return <LiveAvailability slug={slug} initial={availability} />
}// EventDetails: replaces <LiveAvailability … />
<ErrorBoundary title="We can't check the spots">
<Suspense fallback={<p className="mt-4 h-6">Checking spots…</p>}>
<EventAvailability slug={event.slug} />
</Suspense>
</ErrorBoundary>Since getAvailability requires the event to be published, the block disappears on canceled events, which is correct.
The cards also show "37 spots left". A hole per card would be overkill there, so the way out is to promise less: an exact figure that may be fifteen minutes old is false information; "spots available" ages much better.
// components/event-card.tsx
<p className="mt-2 text-sm">{event.spotsLeft > 0 ? 'Spots available' : 'Fully booked'}</p>It's a general consequence of caching: it forces you to review what the interface claims. In 05-04 we'll decide when that notice is updated.
7.4. The home page without a skeleton
// app/(public)/page.tsx
export default function HomePage() {
return (
<>
<h1 className="text-3xl font-bold">What's on in Vallenar del Río</h1>
<h2 className="mt-8 mb-4 text-xl font-semibold">Upcoming events</h2>
<UpcomingEvents />
<Suspense fallback={null}>
<YourDistrictEvents />
</Suspense>
</>
)
}UpcomingEvents no longer needs a boundary: it only waits for cached data. It could stay without any harm, but removing it has an advantage. If someone later introduces a wait in that component, or shortens the cache lifetime too much, the build will fail and make it visible; with the boundary, the content would silently turn into a hole.
Don't remove the ones around EventContent, VenueContent or those on /events: below a request read, the boundary also covers the case where the entry isn't in memory yet.
- Building with a database
Run npm run build with PostgreSQL stopped: it fails. When prerendering /, listUpcomingEvents actually queries. With the database running, the build finishes, and the home page contains the events.
It's no longer possible to build without data, and that affects several things:
| Aspect | What you need to plan for |
|---|---|
| Configuration | DATABASE_URL must exist at build time, not just at startup |
| CI | A PostgreSQL service with migrations and data, or read access to a stable environment (11-06) |
| Deployment order | Migrations first, then the build that uses them |
| Shell content | It's whatever was in the database used for the build, until the first renewal |
| Connections | Prerendering is split across processes, and each one creates its own pool |
| Time | QUERY_DELAY_MS also applies; set it to zero in real builds |
| Bots that don't receive the shell | They repeat the work at request time (04-04): the data must be available then too |
The fourth row is the most treacherous. If you build against test data and deploy against the real data, the first visitors will see events that don't exist. Either build with the same data, or revalidate right after deploying.
If building with a database were unworkable, the alternative is to leave those areas as holes with connection() before calling the cached function: they'd be stored at runtime, without being in the shell.
8.1. Checking and debugging
Turn on logger: true in Drizzle (04-03), build, start with npm run start and reload the home page several times: there are no event queries at all. Open an event page: the first visit queries the event, the following ones only the spots. Two other aids:
- In development,
console.logcalls made inside a cached function appear with theCacheprefix. NEXT_PRIVATE_DEBUG_CACHE=1in front ofnpm run startshows hits, misses and writes.
Common Mistakes and Tips
- Caching a function that reads the request, directly or through another one. The error may only show up at runtime.
- Passing request promises to a cached function: the build hangs for 50 seconds.
- Capturing variables without noticing in nested functions.
- Using free text or user IDs as keys. The cache fills up with single-use entries.
- Receiving
dbor an instance as an argument. It isn't serializable. - Putting the directive on the file of a data layer with functions that mustn't be stored.
- Counting on memory on a serverless platform, or across deployments.
- Forgetting that
nulland empty lists are stored too. - Showing a cached figure as if it were exact.
Exercises
Exercise 1: find the bugs
This function has three problems. Describe them and rewrite it.
export async function listSuggested(db: Database, user: { id: string; district: string }) {
'use cache'
const theme = (await cookies()).get('theme')?.value
const rows = await db.select().from(venues).where(eq(venues.district, user.district))
return rows.map((row) => ({ ...row, theme }))
}Solution
dbisn't serializable: it can't be an argument.- It reads a cookie inside the cache.
- The key includes
user.id, which has no influence on the result: there would be one entry per person instead of one per district.
export async function listVenuesInDistrict(district: string): Promise<Venue[]> {
'use cache'
const db = await getDb()
return db.select().from(venues).where(eq(venues.district, district))
}The theme is read outside, if it's needed on the server at all, and combined at render time. The function receives only what it depends on.
Exercise 2: counting entries
queryCachedEvents receives category, district and page. Someone proposes adding a fourth argument, sort, with two values, and a fifth, day, to filter by date within the next 365 days. Calculate how many entries there can be in each case, with three districts, and say what you would do.
Solution
Today: 5 × 4 × 5 = 100. With sort, 200: manageable. With day, 200 × 366 = 73,200: most of them would never repeat.
Options: don't cache requests with day, as is already done with q; or cache the month with a separate function and filter the day in memory, which means looking for the dimension with fewer values. The second pays off if people query by day a lot. In both cases you have to validate day first: a made-up date is another key.
Exercise 3: choosing the variant
Choose between 'use cache', 'use cache: remote', 'use cache: private' and none for: (a) the legal notice read from the database; (b) the exchange rate from an API limited to 100 requests a day, used in a component that reads a currency cookie, on a serverless platform; (c) the bookings of the signed-in person; (d) a function from an internal library that reads the language cookie, can't be modified and is called in three components; (e) an event's spots.
Solution
- (a)
'use cache'. It's in the shell; a long lifetime is enough. - (b)
'use cache: remote'. It's outside the shell, there are few keys (one per currency) and the API limit is strict. In memory, each instance would use up its own quota. - (c) None. It's personal and must be up to date. To avoid repeating the query within the request,
React.cache. - (d)
'use cache: private'in a function that wraps it, orReact.cacheif you only want to avoid repeating it in the same request. It's the "can't be restructured" case. - (e) None: its value lies in being current.
Conclusion
'use cache' stores the result of an async function under a key made up of the build, the function and its arguments, and lets it go into the shell. In return it demands serializable inputs and outputs and forbids reading the request: the personal part is read outside and passed as an argument. Entries live in the shell, in a process's memory and in the browser, never beyond a deployment. Bounding the keys and isolating what's volatile are the two decisions that make it work.
AgendaViva's queries are now stored, all with the same default lifetime and with no name to refer to them by. In Lifetimes and Tags: cacheLife and cacheTag we'll decide how long each one lasts, give them tags and keep a promise from 01-04: to stop showing past events.
