Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 37 ยท Measuring and Monitoring

The Performance API and Real-User Monitoring

Measure real visitors with the browser Performance API. Use marks, measures, PerformanceObserver for Web Vitals, percentiles and sendBeacon to build real-user monitoring.

Lab tests tell you what is possible on one device. Real-user monitoring (RUM) tells you what actually happens to your visitors: their devices, networks, countries and browsers. RUM works by running a small script on every page that records timings with the browser's Performance API and sends them to your server.

Marks and measures

The simplest tool is your own stopwatch. performance.mark() records a named timestamp, and performance.measure() computes the time between two marks.

JS User Timing marks and measures

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Marks and measures also appear as a track in the DevTools Performance panel, so you can see your own events next to the browser's. Put them around important steps: "app boot", "search results rendered", "checkout form ready".

What the browser records for you

performance.getEntriesByType() returns timeline entries of many kinds:

Type What it tells you
navigation Phases of loading the page: DNS, connect, request, response, DOM events
resource One entry per file loaded: timing, size, initiator
paint first-paint and first-contentful-paint
largest-contentful-paint LCP candidates
layout-shift Individual layout shifts
event Slow interactions (INP)
longtask Tasks over 50 ms

The navigation timing entry gives you the server response time (TTFB) and more:

JavaScript
const [nav] = performance.getEntriesByType("navigation");
console.log("TTFB:", Math.round(nav.responseStart - nav.startTime), "ms");
console.log("DOM interactive:", Math.round(nav.domInteractive), "ms");
console.log("Load event:", Math.round(nav.loadEventEnd), "ms");
console.log("Transfer size:", nav.transferSize, "bytes");

PerformanceObserver

Many entries (LCP, shifts, long tasks) occur after your script starts, so you observe them as they happen. Setting buffered: true also delivers entries that happened before the observer was created.

JavaScript
new PerformanceObserver((list) => {
  const entries = list.getEntries();
  const last = entries[entries.length - 1];   // the latest LCP candidate
  console.log("LCP so far:", Math.round(last.startTime), "ms", last.element);
}).observe({ type: "largest-contentful-paint", buffered: true });

let cls = 0;
new PerformanceObserver((list) => {
  for (const shift of list.getEntries()) {
    if (!shift.hadRecentInput) cls += shift.value;
  }
}).observe({ type: "layout-shift", buffered: true });

The LCP value is final only when the user first interacts or the page is hidden, and CLS and INP are measured over the whole visit. The web-vitals library from the Chrome team handles these details (including edge cases such as back/forward cache restores), so use it in production instead of reimplementing the rules.

JavaScript
import { onLCP, onINP, onCLS } from "https://unpkg.com/web-vitals@4?module";
onLCP(sendToAnalytics);
onINP(sendToAnalytics);
onCLS(sendToAnalytics);

Sending data: sendBeacon

Metrics are finalized when the page is hidden or closed, which is exactly when ordinary requests may be cancelled. navigator.sendBeacon() queues a small POST that the browser sends reliably in the background:

JavaScript
function report(metric) {
  const body = JSON.stringify({
    name: metric.name,
    value: metric.value,
    page: location.pathname,
    connection: navigator.connection?.effectiveType ?? "unknown",
  });
  if (!navigator.sendBeacon("/rum", body)) {
    fetch("/rum", { method: "POST", body, keepalive: true });
  }
}
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden") flush();
});

Do not send a request per metric; batch them into one small payload when the page is hidden. Never send personal data, and respect consent rules in your region.

Percentiles: how to read RUM data

Averages hide the people having a bad time. Performance distributions have a long tail, so report percentiles: p50 (median), p75 and p95. Core Web Vitals are assessed at the 75th percentile: a page is "good" when 75 percent of visits meet the threshold.

JS Percentiles of a sample

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Also segment: by device type, country, connection and page template. A healthy overall number can hide a slow experience in one segment.

A minimal RUM design

flowchart LR
  B["Browser<br/>web-vitals + marks"] -->|"sendBeacon"| E["/rum endpoint"]
  E --> Q["Queue / log"]
  Q --> D["Database"]
  D --> G["Dashboard<br/>p75 per page"]

Collect small, send once, aggregate on the server.

Sample on very busy sites (for example 10 percent of visits) to control cost, and add the release version so you can tie a regression to a deployment.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does performance.measure() compute?

    A measure records a named duration between two timestamps.
  2. 2. Why use buffered true in a PerformanceObserver?

    Buffered delivery includes earlier entries such as an LCP that already happened.
  3. 3. Why is navigator.sendBeacon preferred when the page is closing?

    Normal requests may be cancelled when a page unloads; beacons are queued for delivery.
  4. 4. At which percentile are Core Web Vitals assessed?

    A page passes when at least 75 percent of visits are in the good range.

Summary

  • Use marks and measures for your own timings; use the browser's built-in entries for navigation, resources, paint and shifts.
  • PerformanceObserver with buffered: true collects entries as they happen; the web-vitals library handles edge cases.
  • Send batched data with sendBeacon when the page is hidden.
  • Analyze percentiles and segments, not averages.

Next: A DevTools Profiling Workflow