Repository navigation
fix(core): cache global and single CMS content across page generations - #3539
Conversation
| */ | ||
| export function createPromiseCache<T>(ttlMs = CONTENT_CACHE_TTL_MS) { | ||
| const entries = new Map<string, PromiseCacheEntry<T>>() | ||
|
|
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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] |
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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 Review — Audit SummaryVerdict:
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
📋 Findings (3)RESTRICT
SUGGEST
DK Review v1.0.0 | To dismiss a finding: reply |
lemagnetic
left a comment
There was a problem hiding this comment.
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.
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
| versionId: template.versionId, | ||
| }, | ||
| { cache: true } | ||
| ) |
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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 } | ||
| ) |
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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>>() |
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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, |
There was a problem hiding this comment.
[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
There was a problem hiding this comment.
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.
|
Thanks for the review and for testing on brandless, @lemagnetic.
I also addressed the DK review findings in 8cec85f: expired cache entries are removed on insert, and the tests now run the real |
|
| } | ||
|
|
||
| return cmsPageCache.get(JSON.stringify(['list', options.contentType]), () => | ||
| listCMSPages(options, cmsClient) |
There was a problem hiding this comment.
[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) | ||
| ) |
There was a problem hiding this comment.
[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

0 New Issues
0 Fixed Issues
0 Accepted Issues
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+getEntryscan. The other CMS calls made by everygetStaticPropsare still repeated per page:getGlobalSectionsDataalways runs three lookups (globalSections,globalHeaderSections,globalFooterSections). Each one is alistEntriesfollowed by agetEntryof 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.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 47plplistings of ~700 ms each.How it works?
createPromiseCache(newsrc/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:shouldCachepredicate, so a caller can drop a resolved value from the cache;The PLP/PDP template list cache now uses it with unchanged behavior.
CP single content.
getEntrycaches the "first entry of the content type" lookup, used when there is no slug and noentryId. 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.
getCMSPagecaches unfiltered listings by content type. This is the path that matters for stores withoutCMS_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/releaseIdare only cached when the caller passes{ cache: true }: the PLP/PDP template chosen fromCMS_DATA, andgetSingleContentoutside preview. This only applies to stores that receiveCMS_DATAat 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 deveach page is compiled with its ownContentService, so the cache is not shared across pages there. It is shared undernext 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/serverpromiseCache.test.ts: dedupe, per-key entries, TTL, failures, late failure,shouldCache, expired-entry cleanup, clear.service.test.ts: 20 concurrent global lookups share onelistEntries+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 andMultipleContentErrorbypass the cache; TTL expiry; hCMS locator reuse outside preview and refetch in preview. The content source is switched through a mockeddiscovery.config, so the realisBranchPreviewruns.cms/index.test.ts: shared unfiltered listing, filtered listing not cached, locator cached only on opt-in and keyed by version, failures not cached.Starters Deploy Preview
N/A (server-side content fetching only)
References
Checklist
bug/performance