AgendaViva's queries have been stored since the previous lesson, but with decisions nobody has made: fifteen minutes for everything, whether it's the list of districts or this afternoon's guide. A cache entry raises two questions. The first is how long it's acceptable for a piece of data to be out of date. The second, how to flag it once you know it's no longer true.
cacheLife answers the first, and cacheTag prepares the answer to the second. In this lesson you'll see what an entry's three times mean, how they decide whether content goes into the shell, what happens when caches are nested and how to design a tag vocabulary. We'll finish by paying off the debt from 01-04: stopping the guide from showing events that are already over.
- An entry's three times
An entry's lifetime is described with three numbers, in seconds:
| Property | Who applies it | What it means |
|---|---|---|
stale |
The browser | During this time, the router shows what it has without asking the server |
revalidate |
The server | Once this time has passed, the next request receives what's stored and triggers the renewal in the background |
expire |
The server | Once this time has passed without a renewal, the next request waits for the new content |
flowchart LR
A["The entry is created"] --> B["Fresh<br/>served as is"]
B -- "revalidate" --> C["Stale<br/>served and renewed behind the scenes"]
C -- "a request renews it" --> B
C -- "expire with no visits" --> D["Expired<br/>the next request waits"]
D -- "it's regenerated" --> B
The second phase is the stale-while-revalidate pattern: nobody waits, at the cost of someone receiving the previous version. That leads to something that's often misunderstood:
revalidateisn't the maximum age. It's the point from which renewing is worth it. Renewal is triggered by a visit, not by a clock: on a page with a 15-minuterevalidatethat nobody opens for 10 hours, the next visitor receives content that's 10 hours old.- The maximum age is
expire. It's the limit of what you're willing to show. With steady traffic it's almost never reached; with little traffic, it's what really protects you. staleis another clock, that of a specific tab. Content can be renewed on the server and still look old in a browser that fetched it recently.
When you choose a lifetime, say the three sentences out loud: "whoever already has it can see it like this for stale; from revalidate on we refresh it if there's traffic; we'll never show anything older than expire".
1.1. Two browser rules
The server tells the router the stale value in the x-nextjs-stale-time header. Whatever the configuration, a minimum of 30 seconds applies, so that a prefetch doesn't expire before there's time to click. And it isn't the same as Cache-Control: it doesn't affect the CDN or the browser's HTTP cache.
- Profiles
Writing three numbers every time would be tedious. Next.js comes with named profiles:
| Profile | stale |
revalidate |
expire |
For |
|---|---|---|---|---|
default |
5 min | 15 min | never | Whatever doesn't specify anything |
seconds |
30 s | 1 s | 1 min | Near real time |
minutes |
5 min | 1 min | 1 h | Frequent changes |
hours |
5 min | 1 h | 1 day | Several changes a day |
days |
5 min | 1 day | 1 week | Daily changes |
weeks |
5 min | 1 week | 30 days | Weekly changes |
max |
5 min | 30 days | 1 year | Almost never, or only when invalidated |
import { cacheLife } from 'next/cache'
export async function listDistricts(): Promise<string[]> {
'use cache'
cacheLife('days')
const db = await getDb()
// …
}Look at the expire column for default: never. A function without cacheLife can, after a period with no visits, serve something arbitrarily old. It's one of the reasons the documentation recommends always setting an explicit cacheLife. The others: the intent can be read in the code itself, and nesting behavior no longer depends on what's inside.
Three usage rules:
- It's called inside the cached function, in the function itself. Hiding it in a shared utility makes it impossible to see the lifetime at a glance. At the top level of the module it's an error.
- A single call per execution. There can be several in different branches, as long as only one runs.
- The name expresses how often the data changes, not how important the page is.
2.1. Custom profiles
When none fits, there are two ways. An object in the call itself, for a one-off case:
And a named profile in the configuration, if it's going to be reused. AgendaViva's listings have a particular need: they depend on the time, so they must be renewed often and, above all, they can't age without limit even if nobody visits the page in the small hours:
// next.config.ts (addition)
cacheLife: {
// Listings that depend on the current date
listings: {
stale: 300, // 5 minutes
revalidate: 900, // 15 minutes
expire: 3600, // 1 hour
},
},- Whatever is omitted is inherited from the
defaultprofile, both here and in inline objects. With a one-hourexpireand norevalidate, it would be renewed every 15 minutes. expiremust be greater thanrevalidate; otherwise it's an error.- The names are added to the types:
cacheLife('listings')autocompletes andcacheLife('listing')doesn't compile, as soon asnext dev,next buildornext typegenregenerate the types. - You can redefine a predefined one, including
default. With the ones named after a period, you'll surprise whoever readshoursexpecting hours; a name of your own is better.
With the times we've chosen we can make a concrete guarantee: no guide listing will ever be more than an hour old.
- The lifetime decides whether it goes into the shell
Storing something in the HTML that expires in seconds makes no sense. Next.js applies these thresholds:
| Lifetime | Static shell and link prefetching | App Shell |
|---|---|---|
revalidate equal to 0, or expire under 5 minutes |
Out: hole | Out |
stale under 30 seconds |
Out: hole | Out |
stale between 30 seconds and 5 minutes |
In | Out |
| Everything else | In | In |
Of the predefined profiles, only seconds is left out, because its expire is one minute. minutes gets in. The distinction in the last column matters when creating profiles: a 60-second stale seems prudent and leaves the content out of the App Shell, so it isn't prefetched by an ordinary Link. That's why listings uses 300.
A short-lived entry is, as far as prerendering is concerned, request data. If there's no <Suspense> above it, the build complains with blocking-prerender-runtime, and the ways out are adding one or lengthening the lifetime. It's still useful: during those seconds it shields the database from spikes.
In the next build table, each route now shows the shortest lifetime of all the caches it contains. If a page takes less time to renew than you expected, one of its pieces is in charge:
The home page inherits the times from listings, which we'll see applied in section 8. /venues contains venues and the footer's year, all lasting a day. On /events, the listings aren't in its shell, because they wait for searchParams: only the footer counts.
- Lifetimes that depend on the result
Not every result deserves the same lifetime. The case we have pending is the weather forecast, which can succeed, not exist or fail. Storing a failure for an hour would turn an incident lasting seconds into one lasting sixty minutes:
// lib/data/weather.ts (imports cacheLife; io and cache are no longer needed)
export async function getForecast(day: string): Promise<ForecastResult> {
'use cache'
const { weatherUrl, weatherKey } = readEnv()
if (!weatherUrl || !weatherKey) {
cacheLife('hours')
return { status: 'no-data' }
}
const url = new URL('/v1/forecast', weatherUrl)
url.searchParams.set('day', day)
try {
const result = await requestForecast(url, weatherKey)
cacheLife('hours')
return result
} catch (error) {
console.error('Could not get the forecast:', error)
cacheLife('seconds')
return { status: 'error' }
}
}cacheLifeis called once the result is known, in each branch.- If the API fails at build time, the entry is short-lived:
DayForecastturns into a hole, its<Suspense>covers it and the first visitor tries again. The build doesn't break and the error isn't baked in. - If it fails at runtime, it's stored for a very short time. During a provider outage, it isn't asked once per visitor, and as soon as it recovers, you notice.
- The API key isn't in the cache key. It's read inside, from the configuration; only
dayis an argument. io()disappears. The function is always cached, and inside one it does nothing.
The alternative would be to throw the exception instead of returning { status: 'error' }. In 04-01 we decided that a missing forecast isn't a page error, and that decision still holds.
This pattern works for other results: a null for a resource that may be published soon (minutes) versus the resource found (days), or a lifetime that comes with the data, cacheLife({ revalidate: data.seconds }).
- Caches inside caches
A cached function can call another. Each has its own entry, and the outer one stores the complete result, including what came from the inner one:
| The outer one… | Its lifetime |
|---|---|
Has an explicit cacheLife |
Its own, whether shorter or longer than the inner ones |
Doesn't have one, and the inner one lasts less than default |
It's shortened to the inner one's |
| Doesn't have one, and the inner one lasts longer | default's: it isn't lengthened |
| Doesn't have one, and the inner one is short-lived | Error when prerendering |
The first row has a consequence you need to see coming. If Home lasts a day and calls listUpcomingEvents, which lasts fifteen minutes, the list will be a day old: as long as the outer one is a hit, the inner one doesn't even run. A piece of data's effective lifetime is set by the outermost cache that contains it.
The last row is a safeguard. Without it, a component with seconds, hidden away in a dependency, would turn everything containing it into a hole. It's fixed by giving the outer one a cacheLife that expresses the intent.
In AgendaViva we try not to nest: the queries are cached, and the components that use them aren't. That way each piece of data has a single lifetime.
- Tags
Time covers the changes you don't control. The ones you make (an organizer edits an event) are known the instant they happen, and waiting fifteen minutes for them to show up isn't an option. To be able to say "this entry is no longer valid", you have to be able to name it, and that's what cacheTag does:
import { cacheLife, cacheTag } from 'next/cache'
export async function listDistricts(): Promise<string[]> {
'use cache'
cacheLife('days')
cacheTag('venues')
// …
}A tag is a string. Many entries can carry the same one and one entry can carry several; invalidating a tag invalidates all the entries that carry it. It isn't part of the key: it doesn't separate results, it only groups them.
The limits: 256 characters per tag and 128 tags per call; anything beyond that is discarded with a warning in the console. They're case-sensitive.
6.1. Designing the vocabulary
The question for tagging an entry is: what changes would make it obsolete? One tag for each answer. Two levels of detail cover almost everything:
| Tag | Means | Invalidated when… |
|---|---|---|
events |
"I contain some list of events" | Any event is published, canceled or changed |
event:jazz-night |
"I contain this event" | That event changes |
venues |
"I contain some list of venues, or data about them" | Any venue changes |
venue:the-factory |
"I contain this venue" | That venue changes |
A single global tag would work, but every edit would clear everything. One per query with its parameters would be precise, and nobody would know which ones to invalidate. Two levels, collection and item, are the usual sweet spot.
Since the strings are written in one place and invalidated in another, a typo doesn't raise any error: simply nothing gets invalidated. That's why they're centralized:
// lib/tags.ts
export const EVENTS_TAG = 'events'
export const VENUES_TAG = 'venues'
export function eventTag(slug: string): string {
return `event:${slug}`
}
export function venueTag(slug: string): string {
return `venue:${slug}`
}The module is neutral, with no server-only: it only builds strings. It identifies by slug because that's what the cached functions know before querying. The trade-off is that if changing a slug is ever allowed, both the old and the new one will have to be invalidated.
6.2. Before or after querying
cacheTag can be called anywhere in the function, and where matters:
// lib/data/events.ts
export async function getEventDetails(slug: string): Promise<EventDetailsData | null> {
'use cache'
cacheLife('hours')
cacheTag(eventTag(slug)) // Before: it also tags the null
const db = await getDb()
const [details] = await db
.select({ event: events, venue: venues })
.from(events)
.innerJoin(venues, eq(events.venueId, venues.id))
.where(and(eq(events.slug, slug), inArray(events.status, ['published', 'canceled'])))
.limit(1)
if (!details) return null
cacheTag(venueTag(details.venue.slug)) // After: only known now
return details
}If the event tag were placed after the return null, the absence would be stored without a tag, and when the event was published nobody could remove it. The venue tag, on the other hand, depends on the data.
- Events that are already over
Since 01-04, the listings haven't looked at the date. The sample data is in the future so it doesn't show, but the product rule is clear: a finished event mustn't appear on the home page, the guide, the venues or the suggestions. Its event page does stay accessible, because someone may have the link.
The comparison needs the current time, and you already know what happens when you read it while prerendering. These are the ways to do it:
| Option | What it implies |
|---|---|
Read the clock in the page, after io(), and pass it to the query |
The page is a hole, and the cache key changes every millisecond: nothing useful is stored |
Pass only the day ('2028-05-12') |
Reasonable keys, but the page still has a hole |
| Read the clock inside the cached function | The time is stored with the entry and renewed with it: the page stays in the shell |
now() in SQL |
Equivalent to the previous one, with the database's clock |
| Filter in the browser | The HTML would contain past events |
The third is the one that fits. Its price is precision: an event can stay in the list, after it ends, for as long as the entry lasts. With the listings profile, about fifteen minutes with traffic and an hour at most. For a cultural events guide that's more than enough; for an auction it wouldn't be.
The comparison is with endsAt, not startsAt: an exhibition that opened two weeks ago is still on.
// lib/data/events.ts (imports gt from 'drizzle-orm')
// Published and not yet over. Reads the clock: call it after getDb()
function isCurrent() {
return and(isPublished, gt(events.endsAt, new Date()))
}
export async function listUpcomingEvents(
limit = 6,
district?: string,
): Promise<EventWithVenue[]> {
'use cache'
cacheLife('listings')
cacheTag(EVENTS_TAG, VENUES_TAG)
const db = await getDb()
const rows = await db
.select(withVenueColumns)
.from(events)
.innerJoin(venues, eq(events.venueId, venues.id))
.where(and(isCurrent(), district ? eq(venues.district, district) : undefined))
.orderBy(...byDate)
.limit(limit)
return rows.map(attachVenue)
}Replace isPublished with isCurrent() in queryEvents, listVenueEvents, listRelatedEvents and suggestEvents. Two details make this work outside a cache as well:
- The order.
isCurrent()is called afterawait getDb(), which starts withio(). InsuggestEvents, or inqueryEventswhen there's search text, prerendering stops there and the clock never gets read. Inside a cache,io()resolves and the read is legitimate. If it were written before theawait, the uncached version would raise the error. - It's a function, not a constant like
isPublished. A module constant would read the clock once, when the server starts, and would never move forward.
In queryEvents, the condition is built once and used both for counting and for reading, so the two queries see the same time.
The event page of a finished event deserves to say so, but that's known by comparing with the time of the visit: a small Client Component, or a hole. We leave it as an exercise.
7.1. Trying it out
With npm run db:studio, give riverside-quartet a startsAt and an endsAt from yesterday. Build, start and open the home page: it's not there. Put it back on its date and reload: it's still not there, and that's correct. The list was stored at build time and nobody has reported the change. Reporting it is the next lesson.
- AgendaViva's lifetimes and tags
This is the final state of the cached functions. Apply it, with the directive, cacheLife and cacheTag together at the start of each one:
| Function | cacheLife |
Tags |
|---|---|---|
listUpcomingEvents |
listings |
events, venues |
queryCachedEvents |
listings |
events, venues |
listVenueEvents(slug) |
listings |
events, venue:slug |
listRelatedEvents |
listings |
events |
getEventDetails(slug) |
hours |
event:slug and, if it exists, venue:… |
getEventBySlug(slug) |
hours |
event:slug |
listVenues, listVenueSummaries, listDistricts |
days |
venues |
getVenueBySlug(slug) |
days |
venue:slug |
getForecast |
hours or seconds |
None: we're not the ones who change it |
The listings carry venues because they show the venue's name and district. listRelatedEvents doesn't render them.
Venues have a one-day lifetime rather than max. With tags that were always invalidated, max would be enough, and it's what's recommended for content that reports its changes. But AgendaViva doesn't yet have any screen to edit them: they're changed by hand in the database, without notice. The lifetime is the safety net for whatever the tags don't cover.
flowchart TD
A["How does the data change?"] --> B["Over time, without notice"]
A --> C["Only from my application"]
A --> D["Both ways"]
B --> B1["cacheLife tuned to the acceptable delay"]
C --> C1["cacheTag and a long lifetime"]
D --> D1["cacheTag and a medium lifetime"]
Common Mistakes and Tips
- Confusing
revalidatewith the maximum age. With little traffic, whatever's there is served untilexpire. - Leaving the profile implicit, which never expires.
- Setting a one-minute
stale"just in case". It takes the content out of the App Shell. - Using
secondswithout<Suspense>. It doesn't go into the shell and raises an error. - Storing a failure for as long as a success.
- Caching a component with a long lifetime that contains short-lived data: the outer one wins.
- Writing tags by hand in every place. Typos don't warn you.
- Tagging after an early
return: the absence is left untagged. - Reading the clock in a module constant, or before
getDb(). - Passing the current time as an argument to a cached function.
Exercises
Exercise 1: reasoning about the times
An entry is created at 10:00 with the listings profile (300, 900, 3600). Say what each visit receives, on a full load, and what happens behind the scenes: 10:10, 10:20, 10:20:30, 11:40. Then say what someone sees who opened the home page at 10:19 and goes back to it via a link at 10:22.
Solution
| Visit | Receives | Behind the scenes |
|---|---|---|
| 10:10 | The 10:00 version | Nothing: it's fresh |
| 10:20 | The 10:00 version | It's renewed |
| 10:20:30 | The 10:20 version | Nothing, if the renewal has already finished |
| 11:40 | Waits, and receives the 11:40 version | 80 minutes have passed since 10:20: expired |
Whoever opened it at 10:19 received the 10:00 version, and at 10:22 the 5 minutes of stale haven't passed: the router can show what it has without asking, even if the server already has a new version.
Exercise 2: tagging a query
We add listOrganizerEvents(organizerId), a public function returning an organizer's current events and the names of their venues. Write it cached, with a lifetime and tags, and say what whoever changes an event would have to invalidate so that only what's needed gets updated.
Solution
// lib/tags.ts
export function organizerTag(id: string): string {
return `organizer:${id}`
}
// lib/data/events.ts
export async function listOrganizerEvents(
organizerId: string,
): Promise<EventWithVenue[]> {
'use cache'
cacheLife('listings')
cacheTag(organizerTag(organizerId), VENUES_TAG)
const db = await getDb()
const rows = await db
.select(withVenueColumns)
.from(events)
.innerJoin(venues, eq(events.venueId, venues.id))
.where(and(isCurrent(), eq(events.organizerId, organizerId)))
.orderBy(...byDate)
return rows.map(attachVenue)
}It doesn't carry events, but a finer-grained tag: when an event from another organizer changes, this list isn't touched. Whoever edits will have to invalidate event:slug, events and organizer:id. Each new tag adds precision and adds something to remember when writing; it pays off if there are many organizers with a lot of traffic. This function isn't kept in the project.
Exercise 3: saying it's over
On the event page, show "This event has ended." when that's the case at the time of the visit. The event page must stay in the shell. Write a server version and explain what would be different about doing it on the client.
Solution
// app/(public)/events/_components/ended-notice.tsx
import { io } from 'next/cache'
export async function EndedNotice({ endsAt }: { endsAt: Date }) {
await io()
// eslint-disable-next-line react-hooks/purity -- runs at request time, after io()
if (endsAt.getTime() > Date.now()) return null
return <p className="mt-2 font-medium">This event has ended.</p>
}
// In EventDetails, below the date
<Suspense fallback={null}>
<EndedNotice endsAt={event.endsAt} />
</Suspense>The read is in a component of its own, so the rest of the event page is prerendered. ESLint's purity rule doesn't know that io() makes it legitimate, and the documentation says to disable it on that line.
On the client, the comparison would use the visitor's clock, which may be wrong; in exchange it wouldn't need the server. It would pass endsAt as a prop (a Date is serializable) and read the time after mounting. In this case the difference is small; if the page had no other hole, the client version would leave it fully static.
Conclusion
An entry has three clocks: stale in the browser, revalidate to renew without waits and expire as the maximum age. They also decide whether the content fits in the shell and in the App Shell. An explicit lifetime in every function, shorter for failures than for successes, and no nesting, keeps behavior predictable. Tags, at two levels and centralized, say which changes make each entry obsolete. And reading the clock inside the cache has let us drop past events without taking the listings out of the shell.
The tags are in place, but nobody uses them yet. In Revalidation: updateTag, revalidateTag and revalidatePath you'll see how a change is reported, from where and with what guarantees for whoever made it and for everyone else.
