Optimizing INP and LCP for Modern Single Page Applications: A Production Playbook
INP and LCP failures in SPAs are almost never caused by one slow function — they're architectural. This playbook breaks down interaction phases, long-task elimination, LoAF-driven debugging, and LCP preload strategies you can ship today.
AI Generated with Qwen 3.0 via CometAPIWhy INP Became the Hardest Vital for Single Page Applications
Interaction to Next Paint (INP) replaced First Input Delay as a Core Web Vital in March 2024, and the substitution quietly redefined what "fast" means. FID measured only input delay — the gap between a tap and the first line of your handler executing. INP measures the entire lifecycle of an interaction, from the moment the browser receives the input until the next frame is actually painted to the screen. It then reports approximately the 98th percentile of all interactions observed during the page's lifetime.
That last detail is what punishes SPAs. In a multi-page app, the document is destroyed after every navigation, so the session is naturally bounded. In a single page application, one document can live for ten minutes, accumulate hundreds of event listeners, hold dozens of megabytes of normalized state, and mount and unmount entire component trees. INP is the metric that eventually finds your worst architectural decision.
The thresholds are unforgiving because they are perceptual:
| Rating | INP | LCP |
|---|---|---|
| Good | ≤ 200 ms | ≤ 2.5 s |
| Needs improvement | 200–500 ms | 2.5–4.0 s |
| Poor | > 500 ms | > 4.0 s |
Deconstructing an Interaction Into Three Phases
Every INP candidate is the sum of three phases, and each has a different owner on your team:
- Input delay — time from the hardware event to when your handler starts. Caused by the main thread being occupied with long tasks, hydration, or third-party scripts.
- Processing duration — the sum of your event handler execution plus microtasks, up to the point where the browser can begin rendering again.
- Presentation delay — style recalculation, layout, paint, and compositing. This includes
requestAnimationFramecallbacks and any DOM mutations your handler queued.
A handler that runs in 8 ms but mutates 4,000 DOM nodes inside a requestAnimationFrame can still produce a 300 ms interaction. Optimizing only "JavaScript speed" misses two-thirds of the metric.
Instrumenting INP and LCP in the Field
Lab tools lie about INP. Lighthouse cannot simulate a real user tapping a filter chip on a mid-tier Android device while a WebSocket flush is competing for the main thread. Field measurement is mandatory.
INP Attribution With the web-vitals Library
The attribution build of web-vitals decomposes each interaction for you. Use reportAllChanges during rollout so you see the p98 shift as you ship fixes:
import { onINP, onLCP, type Metric } from 'web-vitals';
function send(payload: Record<string, unknown>): void {
const body = JSON.stringify(payload);
if (navigator.sendBeacon?.('/rum/vitals', body)) return;
// Fallback for browsers/conditions where sendBeacon is unavailable.
fetch('/rum/vitals', { method: 'POST', body, keepalive: true }).catch(() => {
/* never let telemetry throw inside a performance callback */
});
}
onINP(
(metric: Metric) => {
const attr = metric.attribution;
if (!attr) return;
send({
name: 'INP',
value: metric.value,
rating: metric.rating,
navigationType: metric.navigationType,
target: attr.interactionTarget, // CSS selector of the culprit
interactionType: attr.interactionType, // 'pointer' | 'keyboard'
inputDelay: attr.inputDelay,
processingDuration: attr.processingDuration,
presentationDelay: attr.presentationDelay,
loafCount: attr.longAnimationFrameEntries?.length ?? 0,
});
},
{ reportAllChanges: true, durationThreshold: 40 }
);
onLCP((metric: Metric) => {
send({
name: 'LCP',
value: metric.value,
element: metric.attribution?.lcpEntry?.element?.tagName ?? 'unknown',
url: metric.attribution?.lcpEntry?.url,
ttfb: metric.attribution?.timeToFirstByte,
loadDelay: metric.attribution?.resourceLoadDelay,
loadDuration: metric.attribution?.resourceLoadDuration,
renderDelay: metric.attribution?.elementRenderDelay,
});
});Grouping interactionTarget by p98 value gives you a ranked list of components to fix. This is the single highest-leverage dashboard in front-end performance work.
Long Animation Frames Give You the Actual Culprit
The Long Tasks API tells you a 340 ms task existed. The Long Animation Frames (LoAF) API tells you which script, which function, and which invoker caused it:
interface LoafScript {
sourceURL: string;
sourceFunctionName: string;
invoker: string;
duration: number;
}
if (PerformanceObserver.supportedEntryTypes.includes('long-animation-frame')) {
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries() as PerformanceLongAnimationFrameTiming[]) {
if (entry.duration < 80) continue; // ignore noise
const scripts: LoafScript[] = entry.scripts
.filter((s) => s.duration > 20)
.map((s) => ({
sourceURL: s.sourceURL || 'inline',
sourceFunctionName: s.sourceFunctionName || '(anonymous)',
invoker: s.invoker,
duration: Math.round(s.duration),
}));
navigator.sendBeacon?.(
'/rum/loaf',
JSON.stringify({ duration: Math.round(entry.duration), blockingDuration: entry.blockingDuration, scripts })
);
}
});
observer.observe({ type: 'long-animation-frame', buffered: true });
}invoker values like 'React', 'TimerHandler', or 'IMG.onload' instantly classify the failure mode.
Killing Long Tasks Without Breaking UX
Every task over 50 ms is a candidate to delay an interaction. The fix is not "write faster code" — it is yielding: splitting work into chunks and returning control to the browser between them so input can be dispatched and frames can paint.
scheduler.yield() and Safe Fallbacks
type SchedulerLike = {
yield?: () => Promise<void>;
postTask?: <T>(cb: () => T, opts?: { priority?: 'user-blocking' | 'user-visible' | 'background'; signal?: AbortSignal }) => Promise<T>;
};
const sched = (globalThis as { scheduler?: SchedulerLike }).scheduler;
async function yieldToMain(): Promise<void> {
if (sched?.yield) {
await sched.yield(); // resumes at the front of the queue — no starvation
return;
}
await new Promise<void>((resolve) => {
const channel = new MessageChannel();
channel.port1.onmessage = () => resolve();
channel.port2.postMessage(null);
});
}
export async function processInChunks<T>(
items: readonly T[],
work: (item: T) => void,
chunkSize = 100
): Promise<void> {
for (let i = 0; i < items.length; i += chunkSize) {
for (let j = i; j < Math.min(i + chunkSize, items.length); j++) {
work(items[j]);
}
if (i + chunkSize < items.length) await yieldToMain();
}
}The critical property of scheduler.yield() over setTimeout(0) is priority inversion avoidance: continuations resume ahead of newly queued tasks, so a chunked job that yields 40 times does not get starved by unrelated timers.
Offload Real CPU Work to Workers
Anything deterministic and CPU-bound — search indexing, diffing large payloads, CSV parsing, crypto — belongs off the main thread. Serialize deliberately and never structure-clone a 20 MB object graph per message:
// search.worker.ts
interface Query { id: number; term: string }
self.onmessage = (e: MessageEvent<{ corpus: string[]; query: Query }>) => {
const { corpus, query } = e.data;
const needle = query.term.toLowerCase();
const hits = corpus.filter((row) => row.toLowerCase().includes(needle)).slice(0, 50);
(self as unknown as Worker).postMessage({ id: query.id, hits });
};React Patterns That Actually Move INP
Concurrent Features Are an INP Primitive
useTransition and useDeferredValue let React interrupt a render that was triggered by user input and paint the urgent update first:
function SearchPanel({ items }: { items: Item[] }) {
const [query, setQuery] = useState('');
const [isPending, startTransition] = useTransition();
const deferredQuery = useDeferredValue(query);
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const next = e.target.value;
setQuery(next); // urgent: keeps the caret responsive
startTransition(() => { // interruptible: the heavy list re-render
setQuery(next);
});
};
const results = useMemo(() => filterItems(items, deferredQuery), [items, deferredQuery]);
return (
<>
<input value={query} onChange={handleChange} aria-busy={isPending} />
<ResultList items={results} dimmed={isPending} />
</>
);
}Controlled Inputs Are a Presentation-Delay Trap
A controlled <input> whose onChange triggers a synchronous state update of a 2,000-row table will show up as presentation delay, not processing duration. Two rules: never run synchronous filtering during the keystroke, and prefer uncontrolled inputs with a debounced sync for large forms.
Fixing LCP in a Client-Rendered SPA
An SPA's LCP element is usually a hero image or an <h1> that cannot render until the JS bundle parses and the first route mounts. That is a render delay problem masquerading as an image problem. Break LCP into its four subparts and attack the largest.
The Preload + fetchpriority Combination
<link
rel="preload"
as="image"
href="/img/hero-800.avif"
imagesrcset="/img/hero-400.avif 400w, /img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
imagesizes="(max-width: 800px) 100vw, 800px"
type="image/avif"
fetchpriority="high" />
<img
src="/img/hero-800.avif"
srcset="/img/hero-400.avif 400w, /img/hero-800.avif 800w, /img/hero-1600.avif 1600w"
sizes="(max-width: 800px) 100vw, 800px"
width="1600" height="900"
alt="Dashboard overview"
fetchpriority="high"
loading="eager"
decoding="sync" />Three anti-patterns to audit for immediately: loading="lazy" on the hero, decoding="async" on the LCP image, and hero images rendered behind a skeleton that only mounts after useEffect. The last one can add a full second of render delay on its own.
Stream and Split Routes
// vite.config.ts
export default defineConfig({
build: {
modulePreload: { polyfill: true },
rollupOptions: {
output: {
manualChunks(id: string) {
if (!id.includes('node_modules')) return;
if (id.includes('react')) return 'vendor-react';
if (id.includes('chart')) return 'vendor-charts';
return 'vendor';
},
},
},
},
});Combine route-level React.lazy splitting with streaming SSR (renderToPipeableStream) so HTML, including the hero markup, arrives before hydration. Note the trade-off: SSR reduces LCP render delay but can increase INP if hydration blocks the main thread for 400 ms. Mitigate with selective or progressive hydration of below-the-fold regions.
The SPA Soft-Navigation Caveat
Standard LCP only measures the initial document load. Route changes do not produce new LCP entries. If your product is session-heavy, instrument the proposed Soft Navigations API with startSoftNavigation() and emit route-scoped custom metrics alongside it — otherwise your p75 LCP looks great while the in-app experience does not.
Fonts, Third-Party Tags, and Speculation Rules
- Fonts: self-host, subset to Latin + your locale ranges,
font-display: swap, and preload only the single weight used above the fold. Multiple preloaded fonts compete with the LCP image for bandwidth and can regress LCP by 300+ ms. - Third parties: never ship an autoplay-capable YouTube iframe or a chat widget in the critical path. Use a facade that swaps in the real embed on
pointerenter, and load analytics withdeferplus a queued stub. - Speculation Rules turn route transitions into instant paint for pre-rendered pages:
<script type="speculationrules">
{
"prerender": [{
"where": { "href_matches": "/product/*" },
"eagerness": "moderate"
}],
"prefetch": [{
"where": { "href_matches": "/*", "not": { "href_matches": "/checkout/*" } },
"eagerness": "conservative"
}]
}
</script>Guardrails: Put Budgets in CI and RUM
- Assert on bundle size per route in CI (e.g. fail if the entry chunk exceeds 170 KB gzipped).
- Run Lighthouse CI with
--preset=desktopand--throttling-method=devtoolson the three highest-traffic routes; fail on LCP > 2.5 s. - Add a synthetic "tap the primary CTA" Puppeteer step using
PerformanceObserverwithdurationThreshold: 16, and fail if p75 > 200 ms. - Alert in RUM when p75 INP regresses more than 10% week over week, segmented by device class and country.
Operational Checklist
- Attribution-enabled
web-vitalsreporting INP withinteractionTarget,inputDelay,processingDuration,presentationDelay - LoAF observer shipping
sourceFunctionNameandinvokerto RUM - No task over 50 ms during route mount — verified in the DevTools Performance panel
- All scroll/touch listeners registered
{ passive: true } - LCP image preloaded with
fetchpriority="high", neverloading="lazy" font-display: swapwith at most one preloaded font- Third-party embeds behind a facade
- Routes code-split;
modulePreloadenabled content-visibility: autoon long below-the-fold lists
Pitfalls to Avoid
- Optimizing only input delay. On modern hardware, input delay is rarely the dominant phase — processing and presentation usually are.
- Debouncing your way out of INP. Debounce reduces work frequency, not the latency of a single interaction. A 300 ms debounce does not help a 400 ms render.
- Reading layout in a loop.
offsetHeightinside aforEachforces synchronous reflow per iteration. Batch reads, then batch writes. - Over-memoizing.
useMemowith an unstable dependency array recreates on every render and makes things strictly worse. Profile before addingmemo. - Preloading everything. Six preloads is zero preloads; you have recreated the queue you tried to escape.
- Trusting Lighthouse for INP. It cannot measure real interactions. Use RUM.
Sources & Technical References
- Web.dev — Core Web Vitals — official metric definitions and thresholds.
- Web.dev — Interaction to Next Paint (INP) — phase decomposition and scoring.
- Web.dev — Optimize INP — yielding,
scheduler.yield(), and handler patterns. - Web.dev — Largest Contentful Paint and Optimize LCP — four-subpart model and preload guidance.
- W3C — Event Timing API — normative spec for
evententries anddurationThreshold. - W3C — Long Animation Frames — LoAF entry structure and
blockingDuration. - W3C — Largest Contentful Paint — LCP entry algorithm.
- Chrome for Developers — Long Animation Frames API — attribution walkthrough.
- Chrome for Developers — `scheduler.yield()` — priority-preserving yielding semantics.
- MDN — `Scheduler` interface and `PerformanceObserver`.
- MDN — `fetchpriority` attribute — preload priority hints.
- GitHub — GoogleChrome/web-vitals — attribution build and
onINP/onLCPAPIs. - React — `useTransition` and `useDeferredValue` — concurrent rendering primitives.
- Chrome for Developers — Soft Navigations — measuring SPA route transitions.
- Chrome for Developers — Speculation Rules / Prerender — eagerness levels and caching implications.
- RFC 9111 — HTTP Caching —
Cache-Control/stale-while-revalidatesemantics underpinning load-delay reductions.
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.