What is your developer-dependent CMS actually costing you? Calculate your costs and get a full report
What is your developer-dependent CMS actually costing you? Calculate your costs and get a full report
Tutorials
Why reading the whole flat sitemap on every render runs out of memory on large Agility sites, and how to resolve pages from a compact sitemap index with single-node cached lookups.
Most Agility Next.js sites resolve a URL by reading the flat sitemap and looking up the path. That's fine for a few hundred pages. On a large site it becomes the most expensive thing your app does, and it can run your functions out of memory. This guide shows how to tell whether you're affected and how to fix it without changing what your site renders.
Download your flat sitemap and count it:
curl -s -H "APIKey: $AGILITY_API_FETCH_KEY" \
"https://api.aglty.io/$AGILITY_GUID/fetch/en-us/sitemap/flat/website" \
| node -e 'let s="";process.stdin.on("data",d=>s+=d).on("end",()=>{const j=JSON.parse(s),n=Object.values(j);console.log("bytes",s.length,"nodes",n.length,"dynamic",n.filter(x=>x.contentID>0).length)})'
(Use your instance's API host if it isn't api.aglty.io; see Content Fetch API.)
Look at the node count, not the number of pages your editors made. Every dynamic page adds one node per item in its list, so a list shown under several dynamic pages is counted several times. For example, 2,036 articles each listed under 15 section pages makes 30,540 nodes. If you have more than a few thousand nodes, or the JSON is over about 1 MB, read on.
Symptoms: function out-of-memory errors or timeouts under load (crawlers, a full-site link check), slow uncached renders (several seconds) and high CPU while rendering.
Next.js caches don't hand you the stored object. They hand you a copy:
"use cache" hit decodes the stored stream into a new object..json() parses it again.So code like this builds the entire sitemap on every call, even when the cache is warm:
const sitemap = await getSitemapFlat({ locale, preview }) // cached, but a new 13 MB object every time
const node = sitemap[path]
A typical page calls it several times: in generateMetadata, in the page, for breadcrumbs or JSON-LD, and to resolve listing URLs. Under concurrency, those copies add up to gigabytes. The sitemap entry also fills Next's 50 MB in-memory cache, pushing out everything else.
sitemap.xml) in its own cached function. A cached node is a few hundred bytes, so a cache hit costs almost nothing.agility-sitemap-flat-{locale}, so the publish webhook still clears them.The Advanced Next.js Demo Site ships this as src/lib/cms/sitemapIndex.ts (the index) and src/lib/cms/getSitemapNode.ts (the lookups). The Next.js starter ships the same index for its fetch-cache model, as lib/cms/sitemapIndex.ts and lib/cms/getSitemapIndex.ts. A sketch of the lookup side, simplified from the demo site:
// lib/cms/getSitemapNode.ts (sketch)
import { cacheLife, cacheTag } from "next/cache"
import { getPublishedSitemapIndex } from "./sitemapIndex"
// A tiny cached token under the sitemap tag. When the publish webhook
// revalidates the tag, the next read gets a new token.
const sitemapVersion = async (locale: string) => {
"use cache"
cacheTag(`agility-sitemap-flat-${locale}`)
cacheLife("days")
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`
}
const cachedNode = async (locale: string, path: string, version: string) => {
"use cache"
cacheTag(`agility-sitemap-flat-${locale}`)
cacheLife("days")
const index = await getPublishedSitemapIndex(locale, version) // one download per process per version, not per call
return index.get(path) ?? null
}
export const getSitemapNode = async ({ locale, path }: { locale: string; path: string }) =>
cachedNode(locale, path, await sitemapVersion(locale))
getPublishedSitemapIndex keeps the index in module scope and downloads the sitemap again only when the version token changes, which happens when the publish webhook clears the sitemap tag. Concurrent requests share one in-flight download. The webhook also drops the index on the instance it reaches, so that instance refreshes straight away. The starter refreshes on a timer instead, every AGILITY_FETCH_CACHE_DURATION seconds (default 60), and serves the previous index while a refresh runs. In both, preview reads skip all of this and download fresh, once per request, so editors see new pages straight away.
Then replace every whole-sitemap read in your render path:
| Before | After |
|---|---|
sitemap[path] in getAgilityPage | getSitemapNode({ locale, path }) |
findHomeNode(sitemap) | getHomePath(locale) |
hreflang / language switcher: scan for pageID + contentID | findSitemapPath({ locale, pageID, contentID }) |
sitemap.xml, llms.txt, generateStaticParams | one cached list of paths, filtered inside the cached function |
| listing cards: scan the sitemap for each item's URL | look up only the listed items |
Also check the proxy or middleware. If it validates paths against the sitemap, point it at the same in-process index rather than keeping its own copy. The demo's proxy can't use the Next.js cache, so it reloads the index every 60 seconds and keeps the previous one if a reload fails.
Build the previous commit and the new one, run both with next start, and compare the HTML of a few hundred URLs: pages, dynamic items, listings with paging and filters, 404s, and paths in a different case. Ignore Next's build-specific chunk names. When we moved large sites to this pattern, every URL matched. The only difference was the order of URLs in one site's sitemap.xml, which search engines ignore.
To check the index itself, the demo site's scripts/test-sitemap-index.ts asserts that it rebuilds every sitemap node exactly, in order. Run npx tsx scripts/test-sitemap-index.ts, or add live to also check each configured locale's live sitemap.
@agility/content-fetch returns undefined for a 5xx, a timeout or a network error, the same as for a real 404. Under load, one failed request can be cached as a 404 page. Make anything other than a 404 throw, so the failure isn't cached and the next request retries. See Fetch API Status Codes and Caching. Both the demo site and the starter include strictClient.ts.fields parameter. Read lists in pages of 50 or fewer and stop once you have enough.