Files
ipal-kit/docs/performance.md
T

202 lines
20 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Performance — a light, fast site by default
What the plugin does for speed without any project work, what a project must still do, the budgets every site is
held to, how to measure, and how to read the doctor's findings. The agent's short version is AGENT.md §6.11b and the
`iapl-performance` skill. The measurements and the audit behind this page: [dev/perf/README.md](./dev/perf/README.md).
Related: [media.md](./media.md), [frontend.md](./frontend.md), [consent.md](./consent.md), [doctor.md](./doctor.md),
[design-tokens.md](./design-tokens.md).
Targets on the built site, a phone on a slow connection (the numbers Google uses, [web.dev/articles/vitals](https://web.dev/articles/vitals)):
**LCP < 2.5 s, CLS < 0.1, INP < 200 ms.** The reference site measures LCP 0.8 s, CLS 0–0.04 and a 32–48 ms tap
response on that profile (the 404 page is the exception, below).
## 1. What the plugin does for you
| Area | Default | Change it |
|---|---|---|
| Static pages | `createPageRoute` + `generateStaticParams` + `revalidate`: every page is prerendered (ISR); nothing in the layout reads `headers()` or `cookies()`, so the HTML is cached and the server answers in ~4 ms | your own `render`; never call `headers()` in the layout ([nextjs.org/docs/app/guides/caching](https://nextjs.org/docs/app/guides/caching)) |
| Data per render | the `lib/content` helpers cache every read per request (`getSettings`, `resolveRoute`, `generatePageMetadata`, `getSiteShell`), keyed by value; Site settings at depth 1; one Site integrations read shared by analytics and Turnstile; reads that need one field `select` it | `createContentHelpers({ settingsDepth })`; your own getters with `cache()` |
| LCP image | `<Media priority>`: `fetchpriority="high"`, `loading="eager"` and a preload; everything else lazy with `sizes` | `priority` / `eager` / `sizes` per image (`MEDIA_SIZES`) |
| Image formats | `buildImagesConfig()`: AVIF and WebP, the width the screen needs, a 31-day cache, R2 allowed | `buildImagesConfig({ … })` ([media.md](./media.md)) |
| Upload limits | `buildOptimizeUploadHook()`: images over 1.5 MB or 2560 px wide are stopped; the editor may let the plugin shrink them (WebP, metadata dropped) | `maxImageBytes`, `maxImageWidth`, `quality` |
| Upload metadata | every JPEG and PNG that passes the limits loses its metadata (camera, date, GPS, comments) without re-encoding — pixels and colour profile byte for byte; an EXIF "rotate" is applied once (JPEG q92) | `buildOptimizeUploadHook({ stripMetadata: false })`; the building block `stripImageMetadata(buffer, mime)` |
| No layout shift from images | width and height always from the document; a blur placeholder and the dominant colour (`buildMediaPlaceholderHook`) | `placeholderColor` |
| Embeds | `<YouTubeEmbed>`: a picture and a button; the iframe only after a click, from youtube-nocookie.com | `poster` |
| Client JavaScript | small client leaves; a page ships only the client components it renders (the `/client` barrels are no longer one client boundary); the lightbox viewer loads on the first open; the form engine and the Turnstile widget load only on pages that show a form (`BuilderForm` / `Turnstile` from `/client` are lazy wrappers, the server renders the whole form) — 6–9 KB gzip less JavaScript on every other page of the reference site (webpack −8.8, Turbopack −6.1) | `@intecion/ipal-kit/client/eager` → `<RenderForm Form={BuilderForm}>` |
| Turnstile | its 73 px are kept free before Cloudflare draws the widget: the form does not jump | `turnstileReserveHeight={0}` (an invisible widget) |
| Third parties before consent | none besides Google's tag in Consent Mode `advanced` (all signals denied); Meta, LinkedIn, TikTok and Clarity wait for consent; Turnstile only on a form's last step | `analytics={{ consentMode: 'basic' }}` — no request to Google before consent; `analytics={{ defer: true }}` — the tag after the first interaction |
| Fonts | the reference layout (and every new site from `iapl create`) uses `next/font` (self-hosted, `display: 'swap'`, fallback metrics against layout shift) and does not preload the heading font: the stylesheet and the hero get the first round trips (phone: first paint and LCP 36–52 ms sooner) | the project's own fonts; `preload: true` on the heading font |
| Motion | the token durations (`duration-fast`, `-base`, `-slow`) are 0 ms with `prefers-reduced-motion: reduce`; the cookie banner, its switches and the cookie button stop their transitions too; a background video (`<Media videoMode="background">`) is paused for those visitors; the card hover fades a shadow layer (`opacity`, compositor-only) instead of animating `box-shadow` | `motion-reduce:` classes; `<Media pauseForReducedMotion={false}>`; `CARD_INTERACTIVE_SHADOW_CLASS` (the 1.17 hover) |
| 404 | the lazy 404 (`createNotFoundPage({ load })`) keeps its content's height with `placeholder` — the reference site sets it (phone: CLS 0.319 → 0, LCP 2.5 → 1.9 s) | the placeholder's height follows your 404 content |
| Admin only | Payload's colour-scheme client hints only on `/admin`, so a public page is requested once | `withSecurityConfig(…, { adminClientHints: false })` |
## 2. What a project must do
Every row is something the plugin cannot decide for you. `iapl-doctor --only performance` finds most of them.
**Page loading** ([web.dev/articles/optimize-lcp](https://web.dev/articles/optimize-lcp))
- Exactly one `<Media priority>` per page: the first image a visitor sees (the library's hero does this itself via
`leadsWithImage`). A header logo is `<Media eager>` — at once, but without competing with the hero.
- Nothing render-blocking but the one stylesheet: no `<script src>` without `async` in the layout (use `next/script`
or the plugin's `ConsentScript` / `Analytics`), no stylesheet or `@import` from another host
([web.dev/articles/render-blocking-resources](https://web.dev/articles/render-blocking-resources)).
- Keep the page static: no `headers()`, `cookies()` or `searchParams` in the layout or page tree.
**Elements** ([web.dev/articles/cls](https://web.dev/articles/cls))
- Images through `Media` (dimensions, `sizes`, lazy below the fold, never lazy for the LCP image —
[web.dev/articles/lcp-lazy-loading](https://web.dev/articles/lcp-lazy-loading)).
- Content that arrives after the first paint reserves its space. The lazy 404 is the plugin's own case: the
reference `not-found.tsx` passes `placeholder: <div aria-hidden style={{ minHeight: 'max(290px, calc(212px + 11.5vw))' }} />`
— its 404 content's height, measured from 360 to 1920 px wide. Measure yours the same way when the 404 content
changes (the footer must not move when it arrives).
- Maps, videos and widgets behind a click: a picture and a button ([web.dev/articles/third-party-facades](https://web.dev/articles/third-party-facades)).
**Fonts** ([web.dev/articles/font-best-practices](https://web.dev/articles/font-best-practices),
[nextjs.org/docs/app/getting-started/fonts](https://nextjs.org/docs/app/getting-started/fonts))
- `next/font` only, at most two families, variable fonts, `subsets: ['latin', 'latin-ext']` for Polish,
`display: 'swap'`. Every subset of every family is a preloaded file: two variable families with two subsets are
four files (the reference site: 209 KB). The heading font gets `preload: false` (the starter's default): its files
still come, after the stylesheet and the hero. A third family or a second weight file is the first thing to cut.
**Animations** ([web.dev/articles/animations-guide](https://web.dev/articles/animations-guide),
[web.dev/articles/prefers-reduced-motion](https://web.dev/articles/prefers-reduced-motion))
- Only `transform` and `opacity`; never `height`, `top`, `margin`, `transition-all`.
- Reduced motion honoured: the token durations do it; anything else gets `motion-reduce:` or a media query.
- No work per `scroll` event: IntersectionObserver for "is it on screen", at most one update per frame
(`requestAnimationFrame`) for a reading position (the plugin's `TableOfContents` does this since 1.18.0).
**Resources** ([web.dev/articles/reduce-javascript-payloads-with-code-splitting](https://web.dev/articles/reduce-javascript-payloads-with-code-splitting))
- Server components by default; `'use client'` on the small interactive leaf, not the section.
- Compression on: Next compresses by itself; behind Coolify's proxy check that the HTML arrives with
`Content-Encoding` (`iapl-doctor --url` does). Next names its static files by content and serves them
`immutable` — nothing to do.
- No third-party request before consent (the consent rules, [consent.md](./consent.md)).
**Images** ([web.dev/articles/serve-images-avif-webp](https://web.dev/articles/serve-images-avif-webp),
[nextjs.org/docs/app/api-reference/components/image](https://nextjs.org/docs/app/api-reference/components/image))
- `images: buildImagesConfig()` in `next.config`; `buildOptimizeUploadHook()` and `buildMediaPlaceholderHook()` on the
media collection (the reference `Media.ts`).
- `sizes` = the width on screen (`MEDIA_SIZES.half`, `.third`, …): without it a phone downloads the full width.
- Images uploaded before the limits: `iapl-doctor --deep` counts those over 1.5 MB or 2560 px.
**Server** ([payloadcms.com/docs/queries/depth](https://payloadcms.com/docs/queries/depth),
[payloadcms.com/docs/queries/select](https://payloadcms.com/docs/queries/select))
- Read through `lib/content` (cached per request). Your own getters: `cache()` with primitive arguments — React
compares arguments by identity, so an array or an object argument never hits the cache.
- `depth` as low as the page needs; `select` when you need one field; no `findByID` in a loop.
- An index on fields you query: `index: true` on the slug (the plugin's `buildSlugField` does), on `slugHistory.slug`
(old addresses, asked on every unknown URL), on anything you filter a list by.
## 3. Budgets
The plugin's defaults (`PERF_BUDGETS` from `@intecion/ipal-kit/doctor`), per page, first visit:
| | Phone (Slow 4G, CPU 4×) | Desktop |
|---|---|---|
| LCP | 2500 ms | 1200 ms |
| CLS | 0.1 | 0.1 |
| INP (one scripted tap, Event Timing) | 200 ms | 100 ms |
| Total Blocking Time | 200 ms | 100 ms |
| JavaScript (compressed) | 250 KB | 250 KB |
| CSS (compressed) | 50 KB | 50 KB |
| Fonts | 250 KB | 250 KB |
| Requests | 40 | 50 |
| Render-blocking resources | 2 | 2 |
| Third-party origins before consent | none | none |
| Database queries per render (`SERVER_BUDGET`) | 40 | |
A project tightens them to what it measured (`perfBudgets({ mobile: { jsBytes: 200_000 } })`) in
`e2e/performance.spec.ts` (the `iapl-performance` skill's template): from then on the test fails when a change
makes a page slower. The reference site's gate (`reference/e2e/performance.spec.ts`, run by `pnpm e2e:built` with
both bundlers) holds each page type to its own numbers and counts the database queries of one render.
## 4. How to measure
- **The lab, per page** — `perf-lab.mjs` (the skill's `resources/`, the reference site's `e2e/`): Chromium with
Lighthouse's profiles (phone 412×823, Slow 4G — 150 ms, 1.6 Mbit/s — and a 4× slower CPU; desktop 1350×940,
40 ms, 10 Mbit/s), an empty cache, the median of several runs. It returns TTFB, FCP, LCP and the LCP element, CLS,
TBT, the response to one tap, script time, bytes per type, requests, render-blocking resources and third-party
origins.
- **The plugin repository** — `pnpm perf:measure --label=<name> --mongo-container=<docker name>` on the built
reference site: the lab numbers for eight page types on both profiles, the panel's sign-in page, cold start,
memory, TTFB, and the database queries of one render of each page (MongoDB's profiler; the render bypasses the ISR
cache with Next's own `x-prerender-revalidate` header). JSON in `docs/dev/perf/`.
- **The running site** — `pnpm exec iapl-doctor --url https://example.pl --only perf-live`, and PageSpeed Insights
for the field data of real visitors (28 days).
- Never measure `next dev`: it compiles on request and ships unminified code.
## 5. The doctor's findings
All in the `performance` group (`iapl-doctor --only performance`), warnings in 1.18.0 (`perf-budgets` is info):
| Rule | Source | It means | Fix |
|---|---|---|---|
| `perf-images-config` | static | `next.config` has no `buildImagesConfig()` | `images: buildImagesConfig()` |
| `perf-fonts` | static | a font from Google / Typekit, `font-display: block`, `@font-face` without `font-display`, more than two families | `next/font`, `display: 'swap'`, two families |
| `perf-render-blocking` | static | a `<script src>` without `async` / `defer`, a stylesheet or `@import` from another host | `next/script`, the plugin's script components, self-host |
| `perf-embeds` | static | an `<iframe>` (map, widget) that loads with the page (YouTube is `iapl-audit`'s) | a facade (picture + button), or `loading="lazy"` below the fold |
| `perf-animations` | static | a transition of a layout property, `transition-all`, a `scroll` listener, animations with nothing for reduced motion | `transform` / `opacity`, IntersectionObserver, `motion-reduce:` |
| `perf-budgets` | static | the project runs Playwright but has no performance budget test in `e2e/` | the skill's template |
| `perf-live` | `--url` | the HTML is not compressed; blocking scripts in `<head>`; more than four preloaded fonts; the first image in `<main>` is lazy; the home HTML over 150 KB | proxy compression; `async`; fewer font files; `priority`; less data to client components |
| `perf-images` | `--deep` | images stored over 1.5 MB or 2560 px wide | re-upload prepared, or tick "Optimise large image" |
Silence a finding with a reason in `iapl-doctor.json` like any other ([doctor.md](./doctor.md)).
## 6. What grows — keeping the site and its database small over the years
Measured on the reference site after a full test run (MongoDB; average record without indexes): a consent record
185 B, a form submission 647 B, a key-value entry 371 B, a page 9 KB. Every collection also carries 2–6 indexes.
| What | Grows with | What the plugin does (1.18.0) | What the project decides |
|---|---|---|---|
| Consent log (`consent-records`) | one record per banner choice | deleted after `retentionDays` (default 1095 — three years, the proof-of-consent period): on MongoDB by a TTL index (`iapl_ttl` on the hidden `iaplTtlFrom`, kept at the current retention at every start), also on a quiet site; everywhere also by the purge after a new record (at most once a day) | `consentLog: { retentionDays, ttlIndex: false }` |
| Statistics (`stats-visits`, opt-in) | one record per visit | deleted after `retentionDays` (default 90) since the visit's last page view: TTL index on MongoDB, the same purge | `stats: { retentionDays, ttlIndex: false }` |
| Form submissions | one per sent form (files are never stored: they go out by e-mail) | **kept** until deleted in the panel — unless `forms: { submissionRetentionDays }` is set (1.18.0), then deleted after that many days, once a day after a new submission | the retention: personal data, a client decision (AGENTS.md → Project decisions) |
| Versions and drafts | every save | the plugin turns versions on nowhere; when a project turns them on for one of the plugin's collections or globals (overrides) without a limit, it keeps 20 per document (Payload's default is 100) | your own limit wins (`max`, `maxPerDoc`); on your own collections `versions: { maxPerDoc: 20 }` (the doctor's `growth-versions-config` hint); never `0` |
| `payload-kv` | 2FA attempt counters (one per staff account), the mail service state (one per host), enrolment nonces | expired mail-service nonces are swept (at most once a day, when the next enrolment starts); counters and state are bounded by accounts and hosts | — |
| Cookie review (opt-in) | distinct cookie names | upserted by name; a cookie that disappears is marked `gone`, not deleted (the history of what the site set) | delete old `gone` rows in the panel when the client agrees |
| `payload-preferences`, `payload-locked-documents`, `payload-jobs` | panel users, open documents, queued jobs | Payload removes them with the user, on save, and on completion (`deleteJobOnComplete`); the plugin queues no jobs | — |
| Media | uploads | Payload deletes the files (and R2 objects) with the document; nothing deletes media by itself. `iapl({ unusedMedia: true })` shows above the Media list how many files no page, entry or setting uses (by id, or by file name inside a text) and links to Payload's list filtered to them; the editor checks and deletes them there | turn it on (then `pnpm generate:importmap`); the doctor's `growth-media` counts them either way |
| `.next/cache/images` | each image × width × format (AVIF + WebP) | kept 31 days per variant (`minimumCacheTTL`); Next caps nothing by size | no persistent volume on `.next` in Coolify: every deploy starts empty |
| ISR output | pages × languages | rewritten in place on each revalidation | — |
| Logs | — | the plugin writes no files; it logs to stdout (Coolify keeps the container's log) | Coolify's log retention |
**Postgres and SQLite:** the same purges (one `DELETE … WHERE created_at < …`); no TTL index and no `iaplTtlFrom`
column (no migration); the doctor reports counts but not sizes. A consent log without its migration records nothing and so never purges.
**What a project schedules:** nothing for the plugin's own logs — on MongoDB the TTL indexes delete by themselves,
elsewhere the purges run inside the site after a new record. A SQL site that gets no new consent records (or
submissions) for a long time keeps the old ones until the next one comes; the doctor's `growth-retention` rule says so. Database backups are the hosting's job (Coolify → the MongoDB resource → Backups).
**How to check:** `pnpm exec iapl-doctor --deep --only growth` (or `--url` with `IAPL_DOCTOR_TOKEN`): document
counts, sizes (MongoDB), the oldest record, versions per collection and global, expired KV entries, media no
document points at; and on the machine it runs on, the image cache and the local upload folder. Thresholds in
`iapl-doctor.json`:
```json
{ "growth": { "maxDocs": 200000, "maxMB": 512, "maxVersions": 50000, "submissionDays": 730, "expiredKv": 1000, "orphanedMedia": 25, "imageCacheMB": 1024, "uploadsMB": 2048 } }
```
| Rule | Source | It means |
|---|---|---|
| `growth-size` | deep | a collection over `maxDocs` documents or `maxMB` (data + indexes, MongoDB) |
| `growth-versions` | deep | a collection or global keeps versions without a limit, or over `maxVersions` |
| `growth-retention` | deep | a log with a retention holds records older than it: its purge has not run |
| `growth-submissions` | deep | form submissions kept without a retention (info; a warning when the oldest is over `submissionDays`) |
| `growth-kv` | deep | more than `expiredKv` expired entries in `payload-kv` |
| `growth-media` | deep | media nothing points at (info; a warning over `orphanedMedia`). Counted from the first 5000 documents |
| `growth-versions-config` | static | a collection or global of the project turns versions on without `maxPerDoc` / `max` (info: Payload keeps 100) |
| `growth-disk` | static | `.next/cache/images` over `imageCacheMB`, the local `media/` folder over `uploadsMB` (info) |
None of these rules deletes anything; the plugin never deletes media or submissions by itself.
## 7. Shared with IAWL
IAWL (the WordPress line) holds its sites to the same numbers where the measurement is the same: the Core Web Vitals
targets and lab profile, JS ≤ 250 KB, CSS ≤ 50 KB, fonts ≤ 250 KB and two families, requests ≤ 40 on the phone,
one render-blocking stylesheet, no third-party origin before consent, and the image rules (`IMAGE_RULES`): uploads
≤ 1.5 MB and ≤ 2560 px, served as AVIF / WebP in the width the screen needs, metadata dropped on conversion, one
high-priority LCP image, lazy below the fold. The database budget is per product (Payload counts MongoDB queries per
render; WordPress counts SQL queries per request).