Repository navigation
perf(cms): cut admin list/edit N+1 and unbundle publish from its integrations - #279
Merged
Merged
Conversation
…grations The admin was slow to load and slow to publish for four independent reasons, none of them a slow database. List and edit views — batch relationship resolution: `wireCustomFields` stamps `RelationshipCell` onto every relationship column, and Payload's list view fetches at `depth: 0`, so each cell had only an id and fetched the doc itself. A 25-row Blogs list fired ~75 authenticated REST calls after hydration, each re-running access control and hitting Postgres. The module-level cache deduped nothing, because every row checks it in the same tick before any fetch resolves. None of the requests passed `select`, so resolving a `relatedPosts` reference shipped the referenced article's whole Lexical body to draw a chip. New `admin/lib/related-docs.ts` coalesces ids queued in the same tick into one `?where[id][in]=…` request per collection, caches the in-flight promise (not just the result), and trims the response with `select`. The cell also now resolves only the entries it renders, not all of them. `RelationshipField` pills and its picker search go through the same path. Publish — move integrations past the commit and bound them: Payload runs `afterChange` hooks inside the write transaction, so search indexing, the IndexNow ping and the Teams/generic webhook fan-out were all awaited inside the editor's Publish request — and none of them had a fetch timeout, so undici only gave up after 300s. A merely slow integration stalled Publish for as long as it took. `lib/after-commit.ts` generalises the deferral the ISR purge already used; the three hooks now schedule past the commit and report failures through the same log lines. Every outbound publish-path call gained an explicit `AbortSignal.timeout`. `siteSettings.baseUrl` is read once per minute per process instead of three times per publish. Per-navigation and per-process overhead: `NavBadges` mounts through `admin.components.actions`, which remounts on every admin navigation, so it re-fired ~10 count requests per page; it now repaints from cache inside the poll window. `pg`'s default pool of 10 is below what a single admin page-load costs, so requests queued on connection checkout — raised to 25, tunable via `DB_POOL_MAX`. CodeMirror now loads on demand behind a textarea fallback rather than sitting in the admin's synchronous graph for one infrastructure collection's code field. lint / typecheck / build / 2051 unit tests pass. Not yet measured against production data — the request-count reductions are structural, the wall-clock win is not. Also logs the root causes in docs/operations/INCIDENTS.md, including one found-but-unfixed issue: verify:bundle-budget reads a manifest that under app-router + Turbopack never contains the admin route, so that gate has been green while measuring nothing. Co-Authored-By: Claude Opus 5 <[email protected]> Claude-Session: https://claude.ai/code/session_01PDxwMj3RfMoZ2MoNAzbAoQ
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Addresses the reported "all the editors and pages load very slow, and publishing takes a long time."
Four independent causes. None of them is the database being slow.
What was slow
1. Every list view was an N+1 over HTTP.
wireCustomFieldsstampsRelationshipCellonto every relationship column, and Payload's list view fetches atdepth: 0— so each cell received an id and went and fetched the document itself. A 25-row Blogs list (authors+categories) fired ~75 authenticated REST calls from the browser after hydration, each re-running access control against the same connection pool that was serving the page the editor was waiting on.The module-level cache in that file deduped nothing: all 25 rows check it in the same tick, before any fetch has resolved, so identical ids stampede in parallel. The cell also resolved every entry while rendering only the first three.
2. Whole documents crossed the wire to render one line of text. None of those requests passed
select, so resolving arelatedPostsreference shipped the referenced article's entire Lexicalbodyto draw a chip.3. Publish waited on four network calls inside the write transaction. Payload runs
afterChangehooks beforecommitTransaction, so search indexing, the IndexNow ping and the Teams/generic webhook fan-out were all awaited inside the editor's Publish request — and none of them had a fetch timeout. Node'sfetchhas no default; undici only gives up after its 300 s headers timeout. An integration that is merely slow, not down, stalls Publish for as long as it takes. Only the ISR purge was already deferred (revalidateWebAfterCommit). Three of those hooks also each re-read thesiteSettingsglobal for a value that never changes.4. The
pgpool was at its defaultmax: 10. The dashboard alone issues ~20 concurrent counts andNavBadgesanother ~10 — andNavBadgesmounts throughadmin.components.actions, which remounts on every admin navigation, so that fan-out re-fired per page. Past ten in flight, everything queues on connection checkout, which reads as "the CMS is slow" against an idle database.Changes
admin/lib/related-docs.ts(new)?where[id][in]=…&select[…]request per collection; caches the in-flight promise, not just the result. List column: ~75 requests → 2. Falls back to per-id fetches if a batch 400s.RelationshipCellRelationshipFieldselecttrimming the payload.lib/after-commit.ts(new)AbortSignal.timeout(5 s / 8 s / 8 s / 8 s).lib/site-base-url.ts(new)siteSettings.baseUrlread once a minute per process instead of three times per publish. The existing cache insearch/sync.tsnever expired, so an operator changing the base URL had to restart.NavBadgespayload.config.tsmax25, tunable viaDB_POOL_MAX; idle + checkout timeouts.CodeFieldChecks
lint ✓ · typecheck ✓ · build ✓ · 2051 unit tests ✓New tests cover the batcher (coalescing, in-flight dedupe,
limitnot capping at Payload's default 10,select, batch-failure fallback, per-shape cache buckets) andrunAfterCommit(inline vs deferred, error routing).Four existing hook tests failed on the first pass — deferred failures had stopped being logged. Fixed in the hooks by routing
onErrorto the samelogger.warncall, not by changing the tests.Two things worth knowing before merge
Not measured against production data. No Postgres or production-sized dataset in the authoring environment. The request-count reductions are structural and readable off the code; the wall-clock win is not something I have verified. Worth confirming publish latency on the droplet after deploy.
Check
max_connectionsbefore the pool bump lands. 25 per app process needs headroom if more than one process runs against that database.Found but not fixed:
verify:bundle-budgetis measuring nothing.scripts/check-bundle-budget.tsreads.next/build-manifest.jsonpages, which under app-router + Turbopack contains only/_app— the admin route never appears in it. The gate reports "129.4 KB gz / 500 KB budget ✓" regardless of what the admin actually ships, so the admin bundle has been growing unmetered behind a green check. Out of scope here; logged inINCIDENTS.mdand worth its own pass.Reverted mid-way rather than shipped
payload.countswap on the Dashboard tiles —CountOptionshas nodraftoption, so it would have changed the draft tally.importMap.jsregeneration that droppedS3ClientUploadHandler, because the build ran without R2 env vars. Committing it would have broken direct-to-R2 uploads in the media picker.Root causes and reusable lessons are recorded in
docs/operations/INCIDENTS.md.🤖 Generated with Claude Code
https://claude.ai/code/session_01PDxwMj3RfMoZ2MoNAzbAoQ
Generated by Claude Code