Optimizing INP and LCP for Modern SPAs: A Production Playbook for Web Vitals
Single-page applications fail Core Web Vitals for structural reasons — runtime rendering, hydration, and monolithic bundles. This playbook shows you how to instrument, diagnose, and fix Interaction to Next Paint and Largest Contentful Paint with production-grade code and CI guardrails.
AI Generated with Qwen 3.0 via CometAPIModern single-page applications are built on a structural contradiction. The architectural decisions that make an SPA feel instantaneous after the first navigation — client-side routing, a monolithic JavaScript bundle, and runtime rendering — are precisely what inflate Interaction to Next Paint (INP) and Largest Contentful Paint (LCP). Since INP permanently replaced First Input Delay in March 2024, teams can no longer rely on one fast first click to carry a poor score.
This is a practitioner's playbook: how to instrument both metrics with attribution, how to diagnose what is actually blocking the main thread, and how to fix it without rewriting your application.
The SPA Performance Tax: Why Runtime Rendering Costs You Twice
A server-rendered multi-page app ships meaningful HTML on the first byte. The browser can discover the hero image, start the LCP clock's resource load phase early, and paint content before a single line of JavaScript executes.
An SPA ships a nearly empty shell. The browser must:
- Download and parse the document skeleton.
- Download, parse, compile, and execute the framework runtime and route chunk.
- Mount the component tree, which then inserts the hero
<img>into the DOM — and only then does the browser discover and fetch it. - Hydrate, attaching every event handler the page needs for INP.
Steps 2–4 are the performance tax. They push LCP's resource load delay and element render delay into the hundreds of milliseconds, and they occupy the main thread at exactly the moment a user is most likely to tap something — which converts directly into input delay for INP.
Field Thresholds You Are Being Measured Against
All Core Web Vitals are evaluated at the 75th percentile of real-user page loads, segmented by mobile and desktop.
| Metric | Good | Needs improvement | Poor |
|---|---|---|---|
| LCP | ≤ 2.5 s | 2.5 – 4.0 s | > 4.0 s |
| INP | ≤ 200 ms | 200 – 500 ms | > 500 ms |
| CLS | ≤ 0.1 | 0.1 – 0.25 | > 0.25 |
A passing CI Lighthouse score is not evidence of a passing field score. Synthetic runs are single-sample, desktop-weighted, and unthrottled relative to a mid-tier Android device.
INP Anatomy: Input Delay, Processing Time, and Presentation Delay
INP is not the average interaction — it is the 98th percentile of interaction latencies for the page (the worst interaction when fewer than 50 are recorded). One pathological handler is enough to fail the metric.
Every interaction decomposes into three phases:
| Phase | What it measures | Typical SPA culprit |
|---|---|---|
| Input delay | Time before your handlers run | Hydration, third-party tags, competing long tasks |
| Processing time | Handler + framework work | Synchronous state updates, large list re-renders, JSON parsing |
| Presentation delay | Style, layout, paint | DOM size, forced synchronous layout, heavy compositing |
The 50 ms Long Task Ceiling
Any task occupying the main thread for more than 50 ms is a long task. During a long task, the browser cannot dispatch an event, run a handler, or paint. If a user taps at 10 ms into a 400 ms task, their input delay alone is 390 ms — the interaction has already failed before a single line of your code runs.
The practical rule: keep every task under 50 ms, and treat 200 ms of blocking work in a single frame as an outage.
Instrumenting INP and LCP With Attribution in Production
You cannot optimize what you cannot attribute. The web-vitals attribution build attaches the diagnostic data you need — which element was the LCP candidate, what caused the slow interaction — to each sample.
// rum/vitals.ts — requires web-vitals v4+ (attribution build)
import { onCLS, onINP, onLCP, type Metric } from 'web-vitals/attribution';
type Attribution = Record<string, string | number | undefined>;
interface VitalSample {
name: Metric['name'];
value: number;
rating: Metric['rating'];
id: string;
navigationType: Metric['navigationType'];
attribution: Attribution;
route: string;
ts: number;
}
const ENDPOINT = '/api/rum/vitals';
const MAX_BUFFER = 100;
const buffer: VitalSample[] = [];
function flush(useBeacon = false): void {
if (buffer.length === 0) return;
const batch = buffer.splice(0, buffer.length);
const body = JSON.stringify(batch);
if (useBeacon && typeof navigator.sendBeacon === 'function') {
const blob = new Blob([body], { type: 'application/json' });
if (navigator.sendBeacon(ENDPOINT, blob)) return;
}
void fetch(ENDPOINT, {
method: 'POST',
body,
keepalive: true,
headers: { 'Content-Type': 'application/json' },
}).catch(() => {
// Re-queue on failure, but cap growth to protect memory on flaky networks.
buffer.unshift(...batch.slice(-MAX_BUFFER));
});
}
// Normalize dynamic segments so routes aggregate correctly:
// /orders/8812/receipt -> /orders/:id/receipt
function currentRoute(): string {
return location.pathname.replace(/\/\d+\b/g, '/:id');
}
function report(metric: Metric): void {
buffer.push({
name: metric.name,
value: metric.value,
rating: metric.rating,
id: metric.id,
navigationType: metric.navigationType,
attribution: (metric.attribution ?? {}) as unknown as Attribution,
route: currentRoute(),
ts: Date.now(),
});
if (buffer.length >= 10) flush();
}
onLCP(report);
onINP(report);
onCLS(report);
addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') flush(true);
});Two details matter here. First, sendBeacon on visibilitychange is the only reliable delivery path on mobile Safari, where fetch({ keepalive: true }) can be dropped during page teardown. Second, aggregating by normalized route turns a wall of noisy percentiles into an actionable leaderboard of slow screens.
Diagnosing Long Tasks With the Long Animation Frames API
The Long Animation Frames (LoAF) API supersedes the blunt longtask observer. It attributes blocking time to specific scripts and functions — including third-party code you did not write.
interface LoafSample {
startTime: number;
duration: number;
blockingDuration: number;
scripts: ReadonlyArray<{ sourceURL: string; sourceFunctionName: string; duration: number }>;
}
export function watchLongAnimations(onSample: (sample: LoafSample) => void): () => void {
if (!PerformanceObserver.supportedEntryTypes?.includes('long-animation-frame')) {
return () => {};
}
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries() as PerformanceLongAnimationFrameTiming[]) {
onSample({
startTime: entry.startTime,
duration: entry.duration,
blockingDuration: entry.blockingDuration,
scripts: entry.scripts.map((s) => ({
sourceURL: s.sourceURL || '(anonymous)',
sourceFunctionName: s.sourceFunctionName || '(anonymous)',
duration: s.duration,
})),
});
}
});
observer.observe({ type: 'long-animation-frame', buffered: true });
return () => observer.disconnect();
}
// Usage: surface the top offender per frame in staging/RUM.
const stop = watchLongAnimations((sample) => {
if (sample.blockingDuration < 100) return;
const worst = [...sample.scripts].sort((a, b) => b.duration - a.duration)[0];
console.warn(
`[LoAF] ${sample.blockingDuration.toFixed(0)}ms blocking — worst script: ` +
`${worst?.sourceFunctionName} (${worst?.duration.toFixed(0)}ms) @ ${worst?.sourceURL}`,
);
});PerformanceLongAnimationFrameTiming ships in TypeScript's lib.dom from 5.3 onward; on older toolchains, add a local ambient declaration rather than reaching for any.
INP Fix #1: Yield to the Main Thread — Correctly
The single highest-leverage INP change in any SPA is breaking work into yieldable chunks. The modern primitive is scheduler.yield(), which yields to the browser and resumes with priority ahead of queued tasks.
type YieldScheduler = { yield?: () => Promise<void> };
export async function yieldToMain(): Promise<void> {
const scheduler = (globalThis as { scheduler?: YieldScheduler }).scheduler;
if (typeof scheduler?.yield === 'function') {
await scheduler.yield();
return;
}
// Fallback: a macrotask, so pending input and rendering can interleave.
await new Promise<void>((resolve) => setTimeout(resolve, 0));
}| Primitive | Interleaves rendering | Preserves task priority | Support |
|---|---|---|---|
scheduler.yield() | Yes | Yes (resumes early) | Chromium 129+ |
setTimeout(fn, 0) | Yes | No (goes to back of queue) | Universal |
requestAnimationFrame | After paint only | No | Universal |
await Promise.resolve() | No | No | Universal (microtask — do not use) |
The common anti-pattern is await Promise.resolve() as a "yield". Microtasks drain before the browser can process input or paint, so the long task is never actually broken.
Chunked Work With an Abort Contract
export interface ChunkOptions {
signal?: AbortSignal;
chunkSize?: number;
budgetMs?: number;
}
export async function processInChunks<T>(
items: readonly T[],
handle: (item: T, index: number) => void,
{ signal, chunkSize = 50, budgetMs = 8 }: ChunkOptions = {},
): Promise<{ processed: number; aborted: boolean }> {
let processed = 0;
for (let i = 0; i < items.length; i += chunkSize) {
if (signal?.aborted) return { processed, aborted: true };
const chunkStart = performance.now();
const end = Math.min(i + chunkSize, items.length);
for (let j = i; j < end; j++) {
handle(items[j] as T, j);
processed++;
}
// Yield only when we actually consumed the frame budget.
if (performance.now() - chunkStart > budgetMs) {
await yieldToMain();
}
}
return { processed, aborted: false };
}INP Fix #2: Keep Handlers Off the Critical Path
Framework-level work is where processing time accumulates. Three patterns deliver most of the win.
Defer Non-Urgent Renders With Transitions
import { useDeferredValue, useMemo, useState } from 'react';
interface Row { id: string; label: string; amount: number }
export function LedgerSearch({ rows }: { rows: readonly Row[] }): JSX.Element {
const [query, setQuery] = useState('');
// Keeps the keystroke paint urgent; the expensive list re-render is deferred.
const deferredQuery = useDeferredValue(query);
const results = useMemo(() => {
const needle = deferredQuery.trim().toLowerCase();
if (!needle) return rows;
return rows.filter((r) => r.label.toLowerCase().includes(needle));
}, [rows, deferredQuery]);
return (
<>
<input
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search ledger"
aria-busy={query !== deferredQuery}
/>
<LedgerList rows={results} />
</>
);
}Use startTransition for route changes and filter transitions; use useDeferredValue when a value drives expensive rendering. Both let React abandon and restart work, which is the difference between a 60 ms and a 400 ms interaction.
Batch DOM Reads and Writes
Interleaving reads (offsetHeight, getBoundingClientRect) with writes (style.x = ..., classList.add) forces synchronous layout — the classic presentation-delay amplifier.
const pendingWrites: Array<() => void> = [];
let frameScheduled = false;
export function scheduleWrite(write: () => void): void {
pendingWrites.push(write);
if (frameScheduled) return;
frameScheduled = true;
requestAnimationFrame(() => {
frameScheduled = false;
// All writes land in one paint, after all reads have completed.
while (pendingWrites.length > 0) pendingWrites.shift()?.();
});
}Shrink the DOM and Stop Re-Rendering the World
- Virtualize any list above ~100 rows.
- Apply
content-visibility: autowithcontain-intrinsic-sizeto offscreen sections. - Memoize row components and pass stable keys — index keys cause full-list reconciliation on reorder.
- Register scroll and touch listeners as
{ passive: true }so the compositor never waits on your handler.
LCP Fix #1: Make the Hero Element Discoverable in the Initial HTML
The most common SPA LCP failure is lazy-loading the hero. If the LCP image carries loading="lazy", the browser deprioritizes it until layout settles — guaranteeing a multi-second LCP.
<!-- In <head>: start the fetch before the parser reaches the element -->
<link
rel="preload"
as="image"
href="/hero-1600.avif"
imagesrcset="/hero-800.avif 800w, /hero-1600.avif 1600w"
imagesizes="100vw"
fetchpriority="high"
/>
<!-- The element itself: never lazy, always sized, high priority -->
<img
src="/hero-800.avif"
srcset="/hero-800.avif 800w, /hero-1600.avif 1600w"
sizes="100vw"
width="1600"
height="900"
fetchpriority="high"
decoding="async"
alt="Quarterly revenue overview"
/>fetchpriority="high" maps to the u priority parameter defined in RFC 9218, letting you explicitly rank the hero above below-the-fold media without starving the critical CSS.
LCP Fix #2: Attack the Four LCP Subparts
Instrument each phase separately, then fix the largest:
- Time to First Byte — Edge-cache the document shell; move personalization to the client. Use
103 Early Hints(RFC 8297) to preload critical assets while the origin renders. - Resource load delay — Eliminate it with server-rendered markup or an explicit
<link rel="preload">. Target < 100 ms. - Resource load duration — Serve AVIF/WebP at the actual rendered size via
srcset, behind a CDN withCache-Control: public, max-age=31536000, immutable. - Element render delay — Stop blocking paint on JavaScript. Stream the shell, defer hydration, and avoid render-blocking font CSS.
Tame Hydration and Fonts
- Adopt selective or progressive hydration (islands,
client:visible, React Server Components) so the hero paints before the route chunk executes. - Self-host critical fonts, use
font-display: swap, and preload only the single weight used above the fold. - Audit
<head>for render-blocking third parties — a synchronous tag manager is a guaranteed LCP regression on 4G.
Guardrails: CI Budgets and Field Alerts
Synthetic checks catch regressions before they ship; field data confirms the fix. Wire both.
{
"ci": {
"collect": {
"url": ["http://localhost:3000/", "http://localhost:3000/pricing"],
"numberOfRuns": 5,
"settings": { "preset": "desktop" }
},
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.9 }],
"largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
"total-blocking-time": ["error", { "maxNumericValue": 200 }],
"dom-size": ["warn", { "maxNumericValue": 1400 }],
"network-requests": ["warn", { "maxNumericValue": 60 }]
}
}
}
}Total Blocking Time is the best lab proxy for INP — it directly measures main-thread blocking past 50 ms per task. Assert on it in CI and on INP in RUM.
Operational Checklist
web-vitals/attributiondeployed; samples tagged by normalized route and device class.- LoAF observer enabled in staging; the top 5 blocking scripts identified and owned.
- No task in the critical path exceeds 50 ms; all long loops use
processInChunks. scheduler.yield()shipped with asetTimeoutfallback; noawait Promise.resolve()yields in the codebase.- LCP image is server-rendered, preloaded,
fetchpriority="high", and never lazy-loaded. - Hero LCP < 2.5 s at p75 on throttled mobile, not just localhost.
- DOM node count under 1,500 for the initial view; lists virtualized above 100 rows.
- RUM alerting at p75 thresholds with per-route regression detection.
Pitfalls to Avoid
- Optimizing the average interaction. INP is a 98th-percentile metric. One slow handler dominates.
- Trusting Lighthouse as ground truth. Lighthouse cannot measure INP; it measures TBT. Validate with field data.
- Preloading everything. Over-preloading thrashes connection bandwidth and delays the hero. Priority is a zero-sum budget.
- Deferring work into `setTimeout` without yielding. Dropping a 300 ms task into six 50 ms tasks in the same frame changes nothing — you must yield between them.
- Ignoring third parties. Analytics, chat widgets, and A/B tools routinely own 30–50% of blocking time. Audit them with LoAF, not with a bundle analyzer.
- Measuring only the first load. SPA route transitions re-trigger LCP candidates and can introduce heavy synchronous renders; instrument navigation, not just initial pageview.
Sources & Technical References
- web.dev — Interaction to Next Paint (INP): https://web.dev/articles/inp
- web.dev — Optimize INP: https://web.dev/articles/optimize-inp
- web.dev — Largest Contentful Paint (LCP): https://web.dev/articles/lcp
- web.dev — Optimize LCP: https://web.dev/articles/optimize-lcp
- web.dev — Optimize long tasks: https://web.dev/articles/optimize-long-tasks
- web.dev — Defining Core Web Vitals thresholds: https://web.dev/articles/vitals
- W3C Event Timing API Specification: https://w3c.github.io/event-timing/
- W3C Largest Contentful Paint Specification: https://w3c.github.io/largest-contentful-paint/
- W3C Long Animation Frames Specification: https://w3c.github.io/long-animation-frames/
- Chrome for Developers — Long Animation Frames API: https://developer.chrome.com/docs/web-platform/long-animation-frames
- MDN — PerformanceObserver: https://developer.mozilla.org/en-US/docs/Web/API/PerformanceObserver
- MDN — Scheduler.yield(): https://developer.mozilla.org/en-US/docs/Web/API/Scheduler/yield
- MDN — HTMLImageElement.fetchPriority: https://developer.mozilla.org/en-US/docs/Web/API/HTMLImageElement/fetchPriority
- MDN — content-visibility: https://developer.mozilla.org/en-US/docs/Web/CSS/content-visibility
- RFC 9218 — Extensible Prioritization Scheme for HTTP: https://www.rfc-editor.org/rfc/rfc9218.html
- RFC 8297 — An HTTP Status Code for Indicating Hints (103 Early Hints): https://www.rfc-editor.org/rfc/rfc8297.html
- GoogleChrome/web-vitals — Attribution build documentation: https://github.com/GoogleChrome/web-vitals
- React Documentation — useTransition / startTransition: https://react.dev/reference/react/useTransition
Discussion (0)
Continue Reading
More production-grade engineering deep dives and architectural guides

Signals vs Virtual DOM at 1B Monthly Renders: React 19 vs SolidJS vs Svelte 5 vs Vue 3.5 — Measured p99 Frame Time, Memory, Bundle Size, and True Cost per 1M Updates
We rebuilt the same 10,000-row update workload in React 19, SolidJS, Svelte 5, and Vue 3.5 and measured p99 frame time, retained heap, bundle weight, and a defensible cost model per million updates. The numbers show that architecture, not micro-optimization, decides whether your tail latency survives a billion renders.

Postgres Egress Cost Optimization: Cutting Network Bandwidth by 70% in High-Throughput APIs
Your Postgres bill is rarely about CPU — it is about bytes leaving the database, crossing an availability zone, and traversing a NAT gateway. Here is the systematic playbook we used to cut data transfer cost by 70% in a high-throughput API without touching query latency.

Gemini 4 Neon: A Principal Engineer's Deep Dive into the Architecture
Gemini 4 Neon is a serving-systems release disguised as a model launch: the interesting engineering lives in its control plane, cache fabric, and streaming transport, not the benchmark table. This analysis breaks down the four-plane topology, the latency budget you must own, and the production patterns that keep a Neon integration from melting down under load.