Skip to main content

RUM · Web Performance · Tutorial

INP Debugging in Production: Fixing Interaction to Next Paint

Your INP fails on mobile and every click feels instant on your laptop. How to find the slow interaction in field data, name the script behind it, and fix it.

aiAxonIQ Team, Engineering at aiAxonIQ

Nov 23, 20269 min read

Search Console says your mobile pages fail Interaction to Next Paint. You open the site on your laptop, click everything, and it all feels instant. That is the normal starting point for INP debugging: the metric describes the worst interactions of real users on real phones, and it rarely reproduces on a fast machine with an empty cache and no third-party tags. This guide is about getting from a failing p75 to the specific handler, script and line responsible, and then fixing it. Collecting the metric in the first place is covered in our guide to Core Web Vitals monitoring; here we assume you have field data and need to act on it.

What INP measures, precisely

An interaction is a click, a tap or a key press. Hovering and scrolling do not count. One tap dispatches several events (pointerdown, pointerup, click), and the interaction latency is the longest of them, measured from the moment the user acted until the browser presents the next frame. The Event Timing API reports these durations rounded to the nearest 8 ms.

A page view's INP is close to its worst interaction; on pages with many interactions, one outlier is ignored for every 50. The thresholds apply at the 75th percentile of page views: 200 ms or less is good, more than 500 ms is poor. So the number you are fixing is not a typical click. It is the slowest click in a quarter of all visits, usually on the slowest devices, often during page load. A median interaction latency of 60 ms says nothing about it.

The three phases of an interaction

Every interaction splits into three consecutive phases, and each one has different causes and different fixes. Finding the dominant phase is always the first step.

  • Input delay: from the user's input until the first event listener starts. The main thread was busy with something else: hydration, a third-party tag, a timer, or the leftover work of a previous interaction.
  • Processing duration: from the first listener starting until the last one finishes. This is your own handler code, and every listener that runs for those events.
  • Presentation delay: from the end of the handlers until the frame is on screen. It includes requestAnimationFrame callbacks, ResizeObserver and IntersectionObserver callbacks, style recalculation, layout, paint and compositing.

Collecting attribution you can act on

The attribution build of Google's web-vitals library computes the three phases for the interaction that set INP, and since version 5 it also summarizes the Long Animation Frame data for that interaction. The current major version is 6. Send the breakdown, not just the value:

import { onINP } from 'web-vitals/attribution';

onINP(
  (metric) => {
    const a = metric.attribution;
    const s = a.longestScript;
    const body = JSON.stringify({
      value: metric.value,
      rating: metric.rating,
      id: metric.id,
      route: document.body.dataset.route || location.pathname,
      target: a.interactionTarget,
      type: a.interactionType,
      loadState: a.loadState,
      inputDelay: a.inputDelay,
      processing: a.processingDuration,
      presentation: a.presentationDelay,
      scriptTotal: a.totalScriptDuration,
      styleLayoutTotal: a.totalStyleAndLayoutDuration,
      longestScript: s && {
        subpart: s.subpart,
        duration: s.intersectingDuration,
        invoker: s.entry.invoker,
        invokerType: s.entry.invokerType,
        sourceURL: s.entry.sourceURL,
        fn: s.entry.sourceFunctionName,
        charPosition: s.entry.sourceCharPosition,
        forcedLayout: s.entry.forcedStyleAndLayoutDuration,
      },
    });
    navigator.sendBeacon('/rum/inp', body);
  },
  {
    // Report a stable component name instead of a long CSS selector
    generateTarget: (el) =>
      el instanceof Element
        ? el.closest('[data-inp-name]')?.getAttribute('data-inp-name')
        : null,
  },
);

A few of these fields deserve explanation:

  • interactionTarget is a CSS selector for the element the user touched. Selectors built from class names are long and change with every CSS refactor, so generateTarget lets you return your own name; returning null or undefined falls back to the default selector. An empty string usually means the element was removed from the DOM by the interaction itself.
  • loadState says where the document was in its lifecycle when the interaction happened: loading, dom-interactive, dom-content-loaded or complete. It separates "slow during hydration" from "slow forever", which have different fixes.
  • longestScript names the single longest script that overlapped the interaction, which phase it fell in (input-delay, processing-duration or presentation-delay), and how much of the interaction it covered.
  • totalScriptDuration and totalStyleAndLayoutDuration split the interaction into script time and rendering time, which often answers the question before you look at any single script.

Long Animation Frames: which script, which line

The longestScript field comes from the Long Animation Frames API (LoAF), available in Chromium-based browsers from Chrome 123. A long animation frame is one that took more than 50 ms from its start to its rendering. You can observe the entries directly with PerformanceObserver and the long-animation-frame type, and each one carries a scripts array of PerformanceScriptTiming entries for scripts that ran longer than 5 ms during the frame.

The useful fields on each script entry:

  • invokerType: how the script was called, such as event-listener, user-callback (timers, requestAnimationFrame), resolve-promise, classic-script or module-script
  • invoker: what called it, such as the element and event for a listener
  • sourceURL, sourceFunctionName and sourceCharPosition: where the code lives
  • forcedStyleAndLayoutDuration: time the script spent forcing synchronous style and layout, the signature of layout thrashing

In production bundles, sourceFunctionName is often a minified one-letter name. sourceCharPosition is a character offset into the file, and for a bundle minified onto one line it doubles as a column number, so your source maps turn it back into a file and function. Group your field data by sourceURL host first: the split between your own bundles and third-party scripts decides who has to fix the problem.

The frame entry itself has timestamps worth using. renderStart marks the beginning of the rendering steps, and styleAndLayoutStart the start of style and layout. A frame where most time falls after styleAndLayoutStart is a rendering problem, not a JavaScript one.

Reading the phases

When input delay dominates

Check loadState first. If slow interactions cluster in loading or dom-interactive, users are tapping before your application is ready, usually during hydration. Smaller bundles, deferring non-critical scripts and hydrating the parts of the page users interact with first all help. If they happen at complete, something keeps occupying the main thread after load: analytics and tag managers, polling timers, a chat widget initializing late, or the tail of a previous interaction. longestScript with subpart input-delay usually names it.

When processing dominates

Your handler does too much before the browser is allowed to paint. Common examples are a state update that re-renders a large component tree, filtering or sorting thousands of rows synchronously, parsing a large JSON payload, synchronous localStorage access, and analytics calls made inline in the click handler.

When presentation delay dominates

The handlers were quick, but the frame they produced was expensive. Look at totalStyleAndLayoutDuration: large DOM insertions, a class toggled on <body> that forces style recalculation for the whole page, and requestAnimationFrame or observer callbacks doing heavy work all land here.

Fixing INP

Yield before the expensive part

INP stops at the next paint after the interaction. If the handler updates the UI first and then gives the browser a chance to paint, the expensive work that follows no longer counts against that interaction:

function yieldToMain() {
  if (globalThis.scheduler?.yield) return scheduler.yield();
  return new Promise((resolve) => setTimeout(resolve, 0));
}

filterButton.addEventListener('click', async () => {
  filterButton.setAttribute('aria-busy', 'true'); // CSS shows a spinner
  await yieldToMain(); // let the browser paint it

  const rows = applyFilters(allRows); // the expensive part
  await yieldToMain();

  renderRows(rows);
  filterButton.removeAttribute('aria-busy');
  track('filter_applied');
});

scheduler.yield() is available in Chrome from version 129 and Firefox from version 142, and not yet in Safari, hence the fallback. The difference matters: a scheduler.yield() continuation runs ahead of other queued tasks, while a setTimeout callback goes to the back of the queue, behind whatever third-party work is waiting. Two caveats. Yielding moves work rather than removing it, so if the user taps again while it runs, that work becomes the next interaction's input delay. And anything that must happen synchronously, such as event.preventDefault(), has to run before the first await.

Break up long tasks

For loops over large data, yield on a time budget rather than after every item, so the main thread is never held for more than about 50 ms:

async function processInChunks(items, fn, budgetMs = 40) {
  let deadline = performance.now() + budgetMs;
  for (const item of items) {
    fn(item);
    if (performance.now() > deadline) {
      await yieldToMain();
      deadline = performance.now() + budgetMs;
    }
  }
}

Work that never touches the DOM, such as parsing, diffing or search indexing, can move to a Web Worker. In React, wrapping non-urgent state updates in startTransition lets React interrupt that rendering work to handle new input.

Avoid layout thrashing

Reading a layout property such as offsetWidth or getBoundingClientRect() after writing styles forces the browser to compute layout synchronously. Doing it in a loop forces it once per iteration:

// Each read forces a layout, because the previous write invalidated it
for (const el of items) {
  el.style.width = container.offsetWidth / 3 + 'px';
}

// Read once, then write: one layout, after the handler finishes
const third = container.offsetWidth / 3;
for (const el of items) {
  el.style.width = third + 'px';
}

A high forcedStyleAndLayoutDuration on a script entry is the field evidence for exactly this pattern.

Reduce DOM size and rendering work

Style and layout cost grows with the number of elements affected. Virtualize long lists and tables so only visible rows exist in the DOM, apply content-visibility: auto to long off-screen sections, and scope style changes to the component that changed instead of toggling classes high in the tree. If an interaction must insert a large amount of content, render a first screenful, yield, and add the rest.

Contain third-party scripts

If sourceURL points at a tag, chat widget or A/B testing script, the fix is about loading strategy: load it after the page is interactive, replace heavy widgets with a lightweight facade that loads the real thing on first click, and remove tags nobody uses. Show the numbers to whoever owns the tag; LoAF data grouped by script host is hard to argue with.

Lab and field: reproducing the interaction

Field data tells you which interaction is slow and under what conditions. Lab tools tell you why, line by line. Use the first to set up the second. Take the top interactionTarget on a failing route, note its dominant phase and loadState, and reproduce exactly that in Chrome DevTools: the Performance panel shows INP live for interactions as you perform them, and a recorded trace with CPU throttling enabled shows the interaction, its phases and the tasks behind it. If the field loadState was dom-interactive, interact while the page is still loading, not after.

A standard Lighthouse navigation run cannot measure INP, because it has no interactions. Lighthouse timespan mode and scripted browser flows can, which makes a regression test for a known slow interaction possible in CI. Keep in mind which browsers your field data covers: LoAF is Chromium-only, so script-level attribution comes from Chromium users, and Google's Core Web Vitals assessment is based on Chrome data.

Verify every fix in the field. Compare the p75 INP for the route and the share of slow interactions on the target you changed, per device class, over several days of traffic. A fix that only works on a fast laptop will not move the number.

A short workflow

  • Find routes failing INP at p75, per device class.
  • Group slow interactions on each route by interactionTarget and take the top few.
  • For each target, find the dominant phase and the loadState distribution.
  • Read longestScript and the script totals, and map minified positions back through source maps.
  • Reproduce in DevTools with CPU throttling, fix, and confirm the change in field data.

INP debugging with aiAxonIQ

aiAxonIQ Real User Monitoring collects INP automatically along with LCP and CLS, reports it at the 75th and 95th percentiles, and breaks it down by geography, device type, operating system and browser, with alerts when a vital degrades past a performance budget. Session replay, synchronized with console logs, network requests and DOM mutations, shows what the user did around a slow interaction. The browser SDK is compatible with the OpenTelemetry Web Tracer, so when the slow part of an interaction is waiting on an API call, the request links to its backend trace in APM and distributed tracing.

Put this into practice with aiAxonIQ Real User Monitoring.

More articles