Skip to content

fix(core): cache global and single CMS content across page generations - #3539

Merged
eduardoformiga merged 4 commits into
devfrom
cursor/cms-global-content-cache
Oct 27, 2026
Merged

eduardoformiga merged 4 commits into
devfrom
cursor/cms-global-content-cache

Conversation

@eduardoformiga

@eduardoformiga eduardoformiga commented Oct 22, 2026 •

Copy link
Copy Markdown
Member

What's the purpose of this pull request?

#3526 cached the Content Platform (CP) template list for PLP/PDP, so concurrent page generations share one listEntries + getEntry scan. The other CMS calls made by every getStaticProps are still repeated per page:

  • Global sections on CP. getGlobalSectionsData always runs three lookups (globalSections, globalHeaderSections, globalFooterSections). Each one is a listEntries followed by a getEntry of the single entry, which comes to 3–6 CP calls per page with identical results. 20 pages generated together make ~120 calls that fit in 6.
  • Headless CMS (hCMS), the v3 default. Without CMS_DATA, every PLP/PDP and every global lookup re-lists the whole content type (10 per page). In the Black Friday load test (faststore-bf-loadtest), one cold Americanas PLP made 47 plp listings of ~700 ms each.

How it works?

  • createPromiseCache (new src/server/content/promiseCache.ts) extracts the memoization from fix(core): cache Content Platform template list across page generations #3526: in-flight dedupe, 5 minute TTL, failures not cached, and a late failure cannot evict a newer load. Two additions:

    • an optional shouldCache predicate, so a caller can drop a resolved value from the cache;
    • expired entries are removed whenever a new entry is stored, so keys that are never requested again (for example a superseded document version) do not accumulate for the life of the process.

    The PLP/PDP template list cache now uses it with unchanged behavior.

  • CP single content. getEntry caches the "first entry of the content type" lookup, used when there is no slug and no entryId. The key is (accountName, storeId, contentType, locale). This covers the global sections plus singleton content such as home, login, search and My Account pages. Preview, including branch preview, neither reads nor writes the cache, and lookups by slug (landing pages, the PLP/PDP direct match) stay uncached.

  • Empty results. An empty result for a required type (e.g. globalSections) is not kept, so content published right after an empty lookup shows up on the next request instead of after the TTL. Optional types (globalHeaderSections, globalFooterSections) are empty by design and stay cached.

  • hCMS listing. getCMSPage caches unfiltered listings by content type. This is the path that matters for stores without CMS_DATA. Previews always resolve to a locator, so they never reach this branch. Filtered listings, such as a landing page by slug, stay uncached because they depend on the page.

  • hCMS locator (opt-in). Fetches by documentId/versionId/releaseId are only cached when the caller passes { cache: true }: the PLP/PDP template chosen from CMS_DATA, and getSingleContent outside preview. This only applies to stores that receive CMS_DATA at build time. The locator comes from the build-time data, never from a preview, which is documented at the call sites.

The cache lives per process, like #3526. A CMS publish already triggers a new build, and the TTL only bounds staleness for long-lived processes. Downstream code (injectGlobalSections, withDefaultMyAccountSections, page props) only reads the shared objects. No public signatures, exports or config change.

Dev note. Under next dev each page is compiled with its own ContentService, so the cache is not shared across pages there. It is shared under next start (verified by the reviewer: a PDP did not refetch the globals already loaded by the PLP).

How to test it?

  • cd packages/core && pnpm vitest run --project node test/server
    • promiseCache.test.ts: dedupe, per-key entries, TTL, failures, late failure, shouldCache, expired-entry cleanup, clear.
    • service.test.ts: 20 concurrent global lookups share one listEntries + getEntry; separate keys per content type and locale; an empty optional type is cached while an empty required type is not, and is picked up once published; slug lookups, branch preview and MultipleContentError bypass the cache; TTL expiry; hCMS locator reuse outside preview and refetch in preview. The content source is switched through a mocked discovery.config, so the real isBranchPreview runs.
    • cms/index.test.ts: shared unfiltered listing, filtered listing not cached, locator cached only on opt-in and keyed by version, failures not cached.
  • Full node suite passing.

Starters Deploy Preview

N/A (server-side content fetching only)

References

Checklist

  • PR title and commit messages follow the Conventional Commits specification
  • PR description
  • Label: bug / performance
Open in Web Open in Cursor 

@eduardoformiga
eduardoformiga requested a review from a team as a code owner October 22, 2026 21:52
@eduardoformiga
eduardoformiga requested review from hellofanny and lemagnetic and removed request for a team October 22, 2026 21:52
*/
export function createPromiseCache<T>(ttlMs = CONTENT_CACHE_TTL_MS) {
const entries = new Map<string, PromiseCacheEntry<T>>()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Resource] 🟡 RESTRICT

createPromiseCache's internal Map never proactively evicts expired entries — a stale entry is only replaced if the exact same key is requested again after its TTL. For the new CMS locator cache (keyed by contentType+documentId+versionId+releaseId), every CMS republish of a PDP/PLP template mints a new versionId and thus a new key, so the old key's entry is orphaned in the Map for the remaining lifetime of the server process. In a long-lived Next.js ISR process this is an unbounded, slow memory leak.

Action: Add a periodic sweep (or size/LRU bound) that drops entries once expired regardless of whether their key is requested again, or document that the key space is expected to stay bounded for the process lifetime.

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8cec85f. createPromiseCache now drops every expired entry whenever a new entry is stored, so superseded keys (for example an old versionId) are reclaimed on the next miss without a timer. Two tests cover it: expired entries are removed on insert, and entries that have not expired are kept.

For context, in practice the locator key space was already bounded: those versions come from the build-time CMS_DATA, which is fixed per build, and a publish produces a new build and a new process. The cleanup makes that guarantee independent of how the process is deployed.

isContentPlatformSource: vi.fn(actual.isContentPlatformSource),
isContentPlatformSource,
isBranchPreview: (
previewData: Parameters<typeof ContentUtils.isBranchPreview>[0]

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Evolvability.Organizational] 🟡 RESTRICT

The mocked module reimplements isBranchPreview's branch-preview detection logic inline (checking previewData?.versionId || previewData?.releaseId) instead of invoking the actual implementation with the substituted isContentPlatformSource dependency. If the real isBranchPreview logic changes (e.g. additional conditions), this test suite will silently diverge from production behavior and keep passing even though the cache-bypass-for-previews guarantee it verifies (see 'bypasses the cache for branch previews', lines 421-440) no longer holds.

Action: Call through to actual.isBranchPreview inside the mock factory, injecting the mocked isContentPlatformSource as a parameter or via dependency override, rather than duplicating its condition logic.

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 8cec85f. The test no longer mocks src/server/content/utils. It mocks discovery.config with a mutable contentSource, so the real isContentPlatformSource and isBranchPreview run. I also checked it by mutation: forcing the real isBranchPreview to return false makes bypasses the cache for branch previews fail, whereas the previous stub would have kept passing.

@dk-pr-review

dk-pr-review Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

DK Review — Audit Summary

Verdict: ⚠️ RESTRICTED

Severity Count
BLOCK 0
RESTRICT 2
SUGGEST 1

Only BLOCK and RESTRICT findings anchored to a changed line are commented inline on the diff. The other finding below opens no review thread.

Scenarios evaluated: feature-flags, general-review, quality-ratchet
Scenarios skipped: dependency-governance (no matching files), pipeline-config (no matching files), agent-skills-review (no matching files)

⚠️ Governance warnings: Large PR detected (8 files) — review coverage may be incomplete


📋 Findings (3)

RESTRICT

  1. [Functional.Check] packages/core/src/server/cms/index.ts:132 — The new 'list' cache key for shareable content-type listings is built from only ['list', options.contentType], dropping every other field of Options (e.g. locale, if the CMS client supports per-locale listings). Elsewhere in this same PR (service.ts's getContentTypeKey), the team was careful to enumerate exactly which request fields affect the result and include them all in the key, with an explicit comment justifying the omission of slug. Here there's no equivalent justification that contentType alone fully determines the listing. If Options can vary by locale or any other caller-supplied dimension for non-filtered listings, concurrent requests for different locales/variants of the same content type would incorrectly share one cached result, serving the wrong content to some callers for up to the 5-minute TTL.
    → Confirm whether the non-locator branch of Options can carry locale or other result-affecting fields. If so, include them in the cache key (mirroring getContentTypeKey in service.ts); if not, add a short comment next to the key construction stating why contentType alone is sufficient, as was done for the locator cache and for getContentTypeKey.
  2. [Functional.Resource] packages/core/src/server/content/service.ts:199 — The new firstEntryCache deliberately never caches an empty result for a non-optional content type (shouldCache returns false via !isEmptyEntry(entry) || isOptionalContentType(params)), on the assumption the emptiness is transient ('about to be published'). But if a required content type is simply misconfigured and never published, this isn't transient: every single incoming request for that content type will bypass the cache entirely and hit clientCP.listEntries live, plus emit a console.warn each time (service.ts's fetchFirstEntryFromList). Under production traffic this turns a config mistake into sustained, unbounded load against the Content Platform API and continuous log spam, with no backoff.
    → Consider caching empty results for a much shorter TTL (instead of not caching them at all) so a sustained misconfiguration doesn't bypass caching on every request, and/or rate-limit the 'No entries found' warning.

SUGGEST

  1. [Evolvability.SupportedByLanguage] packages/core/test/server/content/service.test.ts:20 — The discovery.config mock falls back to the whole module namespace (actual.default ?? actual) and then force-casts base.contentSource with as ContentSourceConfig instead of narrowing it. If the real module ever lacks a default export, the mock still synthesizes one (default: { ...base, contentSource: mutableContentSource }), so the mocked shape can diverge from the real module's shape without TypeScript or the test catching it.
    → Assert the module shape explicitly (e.g. check actual.default exists before spreading it into a synthetic default) instead of relying on an unchecked as cast, so a real shape change in discovery.config fails loudly in this test file.

DK Review v1.0.0 | To dismiss a finding: reply /dk-review dismiss [reason] under its comment

@lemagnetic lemagnetic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Revisei e testei na brandless.

No next dev o cache não atravessa de uma página para a outra: cada uma sobe com o seu próprio ContentService. No yarn start elas compartilham o mesmo chunk, e a PDP não buscou de novo os globais que a PLP já tinha carregado. A busca por slug continua sendo uma chamada por página.

Um ponto para um eventual follow-up: se um content type obrigatório voltar vazio, esse vazio fica no cache por 5 minutos. Não vi isso na brandless.

@pkg-pr-new

pkg-pr-new Bot commented Oct 27, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@8cec85f

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@8cec85f

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@8cec85f

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@8cec85f

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@8cec85f

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@8cec85f

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@8cec85f

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@8cec85f

commit: 8cec85f

versionId: template.versionId,
},
{ cache: true }
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Check] 🟡 RESTRICT

getPDPFromCmsEnvData always passes { cache: true } to getPage, unconditionally sharing the fetched document across all callers by (contentType, documentId, versionId). The cache's own doc comment in cms/index.ts warns this is 'only safe when the locator does not come from a preview, since preview versions change between requests', and the sibling call site in content/service.ts correctly computes cache: !options.isPreview. This call site has no equivalent guard, so if this template-resolution path can ever run for a preview request, preview content (or a stale version) could leak into the shared cache and be served to subsequent non-preview visitors.

Action: Thread an isPreview flag (or equivalent) into getPDPFromCmsEnvData and pass { cache: !isPreview }, mirroring the pattern already used in ContentService.getSingleContent, or document explicitly why this path can never observe preview data.

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this applies, because the template locator in this path never comes from a preview. getPDP passes the preview data only as options, and getPDPFromCmsEnvData uses options just to build the MissingContentError. The locator that goes to getPage is { contentType: 'pdp', documentId, versionId } taken from findBestPDPTemplate(pages, product), where pages is the build-time CMS_DATA. Preview and non-preview requests therefore fetch the same published (documentId, versionId) document, and a given versionId is immutable, so nothing preview-specific can reach the shared cache.

That is different from ContentService.getSingleContent, where the locator can come from previewData, which is why that call site uses cache: !options.isPreview.

I made the invariant explicit with a comment at the call site in 8cec85f. Happy to thread an isPreview flag through as well if you would still prefer the extra guard.

versionId: template.versionId,
},
{ cache: true }
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Check] 🟡 RESTRICT

Same issue as in pdp.ts: getPLPFromCmsEnvData unconditionally passes { cache: true } to getPage without checking whether the resolved template/locator originates from a preview request, contradicting the documented safety invariant for locator caching in cms/index.ts.

Action: Pass cache based on the actual preview state of the request, consistent with the ContentService.getSingleContent call site (cache: !options.isPreview).

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same as the pdp.ts thread: getPLPFromCmsEnvData only uses options (which carries any preview data) for the MissingContentError. The locator passed to getPage is { contentType: 'plp', documentId, versionId } from findBestPLPTemplate(pages, slug, rewrites) over the build-time CMS_DATA, so a preview request resolves to the same published, immutable document as any other request. The comment added at the call site in 8cec85f documents this.

* entry is evicted too, so only the callers already waiting share that value.
*/
export function createPromiseCache<T>(ttlMs = CONTENT_CACHE_TTL_MS) {
const entries = new Map<string, PromiseCacheEntry<T>>()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Resource] 🟡 RESTRICT

createPromiseCache's internal Map only evicts an entry when a request for that exact key happens to land after expiry (or on rejection/shouldCache-false); entries for keys that are never requested again after expiring just sit in memory indefinitely. cmsPageCache now keys locator entries by (contentType, documentId, versionId, releaseId), so every CMS republish mints a brand-new permanent key in a long-lived ISR/Next.js server process, giving this cache effectively unbounded growth over the process lifetime instead of a bounded, TTL-reclaimed size.

Action: Add a periodic sweep of expired entries (e.g. on a timer or opportunistically on every get()) or cap the map with an LRU/max-size eviction policy, especially since this cache is now reused for the higher-cardinality locator key space.

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in 8cec85f (this review ran against 21a2dd3, before that commit). Expired entries are now removed whenever a new entry is stored, so a republished template that mints a new versionId no longer leaves a permanent key behind. See drops expired entries when a new key is stored in promiseCache.test.ts.

const actual = await importOriginal<typeof ContentUtils>()
const isContentPlatformSource = vi.fn(actual.isContentPlatformSource)
return {
...actual,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Evolvability.SolutionApproach] 🟡 RESTRICT

The vi.mock for '../../../src/server/content/utils' replaces the real isBranchPreview with a hand-rolled reimplementation (isContentPlatformSource() && !!(previewData?.versionId || previewData?.releaseId)) instead of exercising the actual function. The new 'bypasses the cache for branch previews' test therefore validates this inline stub's logic, not the production isBranchPreview implementation — a future change or bug in the real function's branch-preview detection would go undetected by this suite.

Action: Keep isBranchPreview as vi.fn(actual.isBranchPreview) (like isContentPlatformSource) and only stub its return value per test, so the cache-bypass test actually exercises (or at least tracks calls to) the real implementation instead of a parallel reimplementation.

To dismiss: reply /dk-review dismiss [reason] under this comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Same fix as the earlier thread, in 8cec85f (this review ran against 21a2dd3). isBranchPreview is no longer stubbed. The source is switched through a mocked discovery.config, so the cache-bypass test exercises the production function. The as unknown as cast on clientCMS.getCMSPage is also gone: the test uses vi.spyOn(...).mockResolvedValue(...) with a typed object.

# Conflicts:
#	packages/core/src/server/content/service.ts
Drop expired cache entries on insert, test the real isBranchPreview by mocking discovery.config, and document the non-preview invariant at the template call sites.
@cursor

cursor Bot commented Oct 27, 2026

Copy link
Copy Markdown

Thanks for the review and for testing on brandless, @lemagnetic.

  • next dev vs next start: agreed, and I added it to the PR description. Each page gets its own ContentService under next dev, so the cache only shows up under next start.
  • Empty required content type: done in 21a2dd3. An empty result for a required type (for example globalSections) is no longer cached, so content published right after an empty lookup appears on the next request. Optional types (globalHeaderSections, globalFooterSections) are empty by design and stay cached. createPromiseCache got an optional shouldCache predicate for this.

I also addressed the DK review findings in 8cec85f: expired cache entries are removed on insert, and the tests now run the real isBranchPreview. The 3.x backport (#3540) has the same changes.

@sonar-workflows

Copy link
Copy Markdown

@eduardoformiga
eduardoformiga merged commit 72b68b4 into dev Oct 27, 2026
14 of 16 checks passed
@eduardoformiga
eduardoformiga deleted the cursor/cms-global-content-cache branch October 27, 2026 20:05
}

return cmsPageCache.get(JSON.stringify(['list', options.contentType]), () =>
listCMSPages(options, cmsClient)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Check] 🟡 RESTRICT

The new 'list' cache key for shareable content-type listings is built from only ['list', options.contentType], dropping every other field of Options (e.g. locale, if the CMS client supports per-locale listings). Elsewhere in this same PR (service.ts's getContentTypeKey), the team was careful to enumerate exactly which request fields affect the result and include them all in the key, with an explicit comment justifying the omission of slug. Here there's no equivalent justification that contentType alone fully determines the listing. If Options can vary by locale or any other caller-supplied dimension for non-filtered listings, concurrent requests for different locales/variants of the same content type would incorrectly share one cached result, serving the wrong content to some callers for up to the 5-minute TTL.

Action: Confirm whether the non-locator branch of Options can carry locale or other result-affecting fields. If so, include them in the cache key (mirroring getContentTypeKey in service.ts); if not, add a short comment next to the key construction stating why contentType alone is sufficient, as was done for the locator cache and for getContentTypeKey.

To dismiss: reply /dk-review dismiss [reason] under this comment

getContentTypeKey(params),
() => this.fetchFirstEntryFromList(params, false),
(entry) => !isEmptyEntry(entry) || isOptionalContentType(params)
)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Functional.Resource] 🟡 RESTRICT

The new firstEntryCache deliberately never caches an empty result for a non-optional content type (shouldCache returns false via !isEmptyEntry(entry) || isOptionalContentType(params)), on the assumption the emptiness is transient ('about to be published'). But if a required content type is simply misconfigured and never published, this isn't transient: every single incoming request for that content type will bypass the cache entirely and hit clientCP.listEntries live, plus emit a console.warn each time (service.ts's fetchFirstEntryFromList). Under production traffic this turns a config mistake into sustained, unbounded load against the Content Platform API and continuous log spam, with no backoff.

Action: Consider caching empty results for a much shorter TTL (instead of not caching them at all) so a sustained misconfiguration doesn't bypass caching on every request, and/or rate-limit the 'No entries found' warning.

To dismiss: reply /dk-review dismiss [reason] under this comment

@eduardoformiga eduardoformiga mentioned this pull request Oct 29, 2026
2 of 7 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants