Durable cache on Netlify
By Flavio
Published · Updated
Tagged: Services
Cache Netlify Function responses across regions with the durable CDN directive, max-age, and stale-while-revalidate, then vary, tag, purge and debug the cache.
I need to remember this interesting technique so let me write a blog post.
I read this on Jason Lengstorf’s blog. The astro.party site is gone now, but there’s an archived copy of the post.
Netlify’s durable cache adds a shared backing layer to its edge cache. When one region generates a cached response, other regions can reuse it instead of invoking the function again.
Set the durable directive in the Netlify-specific CDN header:
export default async () => {
return new Response('Hello world', {
headers: {
'Netlify-CDN-Cache-Control':
'public, durable, max-age=60, stale-while-revalidate=120'
}
})
}
This example keeps a response fresh for 60 seconds. For the next 120 seconds, the cache may serve the stale response while it revalidates in the background.
Use Netlify-CDN-Cache-Control when the rule is meant for Netlify’s CDN but not the visitor’s browser cache. Choose durations based on how stale the content is allowed to become, and never cache personalized or authenticated responses under a shared key.
The durable directive applies to Netlify Function responses, not Netlify Edge Function responses. Netlify also notes that the cache is eventually consistent, so it does not guarantee exactly one function invocation across every region.
Why the edge cache alone is not enough
Without durable, each Netlify edge node keeps its own copy. A visitor in Europe and a visitor in the US hit different nodes, so both requests run your function, even if the response is identical.
With durable, the first function response also goes into a shared cache. When another edge node misses, it checks the durable cache before invoking the function.
This matters most when the function is slow, like a server-rendered page that calls a database or an API. The first visitor waits. Most of the others don’t.
If you use Netlify Functions through a framework, check its adapter first. Netlify says cacheable responses on sites using the Next.js Runtime 5.5.0 or later already use the durable cache.
Nothing is cached by default
Function responses are not cached unless you add cache headers. Without them, Netlify sends:
Cache-Control: public, max-age=0, must-revalidate
So if you deploy a function and never set a header, every request runs it.
Which header wins
Netlify reads three headers:
Netlify-CDN-Cache-Controlapplies only to Netlify’s CDNCDN-Cache-Controlapplies to any CDN that supports itCache-Controlapplies to CDNs and the browser
When you set more than one, Netlify uses the most specific. It always passes CDN-Cache-Control and Cache-Control downstream, so other caches and the browser can read them.
This lets you cache on the CDN for a long time while telling the browser to always check back:
export default async () => {
return new Response(await renderPage(), {
headers: {
'Content-Type': 'text/html',
'Cache-Control': 'public, max-age=0, must-revalidate',
'Netlify-CDN-Cache-Control':
'public, durable, max-age=3600, stale-while-revalidate=86400'
}
})
}
The browser revalidates every time, but the request stops at Netlify’s CDN and doesn’t reach your function for an hour. After that, for up to a day, visitors still get the cached copy while Netlify fetches a new one in the background.
renderPage() is a placeholder for whatever builds your HTML.
New deploys clear the cache
You don’t need to purge after a deploy. Netlify invalidates the cache for that deploy context on every new deploy by default.
This is why long max-age values are less scary than they look. The cache can’t outlive a deploy.
Cache different versions with Netlify-Vary
The cache key is the URL. If your function returns different content based on a query parameter, a cookie, or the visitor’s country, add Netlify-Vary, or visitors will get each other’s version:
headers: {
'Netlify-CDN-Cache-Control': 'public, durable, max-age=300',
'Netlify-Vary': 'query=page|per_page,country=us|es+pt'
}
The syntax:
query=page|per_pagekeys on those query parameters. Usequeryalone to key on all of themheader=App-Versionkeys on a request headercookie=ab_testkeys on one cookie value, not the wholeCookieheadercountry=us|es+ptandlanguage=en|dekey on location and language. The+groups values, so Spain and Portugal share one copy
Requests that match none of the listed values share one cache entry. Send the same Netlify-Vary on every response from a URL.
Don’t try to vary on the whole Cookie header. It can contain session tokens, which gives every user a separate entry, and Netlify doesn’t accept header=Cookie anyway. Pick the one cookie that changes the content.
Purge on demand with cache tags
Sometimes content changes without a deploy, like when someone edits a post in a CMS. Tag the response:
headers: {
'Netlify-CDN-Cache-Control': 'public, durable, max-age=31536000',
'Netlify-Cache-Tag': 'posts,post-42'
}
Then purge by tag from another function, for example a webhook that your CMS calls:
import { purgeCache } from '@netlify/cache'
export default async () => {
await purgeCache({ tags: ['post-42'] })
return new Response('Purged', { status: 202 })
}
Call purgeCache() with no tags to purge everything for the site. The same function is also exported by @netlify/functions.
A few limits to know:
- tags are case-insensitive, up to 1024 characters each, and at most 500 per response
- each tag or site can be purged twice every 5 seconds. Go faster and you get a
429
Check if it worked
Netlify adds a Cache-Status header to every response. Look at it with curl:
curl -sI https://your-site.netlify.app/some-page | grep -i cache-status
You can get more than one line, one per cache layer:
Cache-Status: "Netlify Edge"; fwd=miss
Cache-Status: "Netlify Durable"; hit; ttl=1234
How to read it:
"Netlify Edge"; hitmeans the edge node had it"Netlify Durable"; hitmeans the edge missed but the durable cache had it, so the function didn’t runfwd=uri-missorfwd=vary-missmeans a miss that went to the function, andstored=truemeans the new response is now cachedfwd=stalemeans you got the stale copy while it revalidates
If you never see "Netlify Durable", check that the response comes from a regular function, not an Edge Function, and that the header includes public and durable.
Things that break caching
- Basic auth on any page of the site disables caching for the entire site
- Edge Function responses ignore
durable - Responses that depend on the logged-in user. Don’t cache them with
public, or make sureNetlify-Varyseparates them properly
See Netlify’s caching documentation for the full list of options.
Want me to talk about your product? You can sponsor this site.
Related posts about services: