Frontend System Design · Lesson 56 of 86 · 5 min
Real User Monitoring (RUM)
This is how you prove your performance optimizations actually work and show you think about the end-user experience, not just lab scores.
In an interview, you can't just say you'd "make the site faster." You need to explain how you'd measure performance, identify bottlenecks, and validate improvements. Real User Monitoring (RUM) is the system that provides those answers by collecting performance data from actual users in the wild.
What to measure and why
Your goal is to measure what the user perceives. Lab tools are clean, but RUM captures the reality of slow networks, old devices, and browser extensions. Focus on metrics that map to user experience.
The most important are Google's Core Web Vitals:
- Largest Contentful Paint (LCP): When did the main content of the page become visible? This measures perceived loading speed. Under 2.5 seconds is good.
- Interaction to Next Paint (INP): How long does the page take to visually respond to user input, like a click or tap? This measures overall responsiveness. Under 200 milliseconds is good.
- Cumulative Layout Shift (CLS): How much does the content unexpectedly move around as the page loads? This measures visual stability. A score under 0.1 is good.
Other critical metrics include Time to First Byte (TTFB) to diagnose server-side slowness and First Contentful Paint (FCP) to know when anything first appeared on screen. These metrics tell a story that window.onload never could.
How the data gets collected
A RUM system starts with a small JavaScript agent on the page. This agent uses standard browser APIs to observe performance events without blocking rendering.
The primary tool is the PerformanceObserver API. You create an observer for specific event types, and the browser notifies your callback with detailed timing entries when they occur. This is how you get LCP, CLS, INP, and other paint timings.
This diagram shows the basic flow from user action to data analysis.
Here is a minimal implementation to collect Core Web Vitals. It uses PerformanceObserver to listen for the metrics and queues them for sending.
const metrics = [];
function addMetric(name, value) {
const metric = { name, value, timestamp: Date.now() };
metrics.push(metric);
console.log(`Collected: ${name} = ${value}`);
}
// Largest Contentful Paint (LCP)
new PerformanceObserver((entryList) => {
const entries = entryList.getEntries();
const lastEntry = entries[entries.length - 1];
if (lastEntry) {
addMetric('LCP', lastEntry.startTime);
}
}).observe({ type: 'largest-contentful-paint', buffered: true });
// Cumulative Layout Shift (CLS)
let cls = 0;
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
if (!entry.hadRecentInput) {
cls += entry.value;
}
}
// CLS is cumulative, so we report the latest value.
// In a real agent, you'd update a single CLS metric.
addMetric('CLS', cls);
}).observe({ type: 'layout-shift', buffered: true });
// Interaction to Next Paint (INP)
new PerformanceObserver((entryList) => {
for (const entry of entryList.getEntries()) {
addMetric('INP', entry.duration);
}
}).observe({ type: 'event', durationThreshold: 16, buffered: true });
// Note: A robust INP implementation is more complex. It tracks the worst
// interaction over the page's lifecycle and reports on visibility change.
The trap: The monitoring script itself can degrade performance. A RUM agent must be tiny, load asynchronously, and do its work during idle time to avoid interfering with the user experience it's meant to measure.
How to send the data without breaking things
Once you've collected metrics, you need to send them to a backend for aggregation. You can't just fire off a fetch for every metric; that would create too much network traffic.
Metrics should be batched. The agent collects data in an array and sends it periodically or when the user leaves the page.
For sending the data, navigator.sendBeacon() is the correct tool. It's designed for sending small amounts of analytics data. The browser sends the request in the background, without blocking the main thread, and ensures it's sent even if the page is unloading. A traditional fetch or XMLHttpRequest in an unload event handler is unreliable and often gets cancelled by the browser.
function sendMetrics() {
if (metrics.length === 0) return;
const payload = {
page: window.location.pathname,
metrics: [...metrics],
userAgent: navigator.userAgent,
connection: navigator.connection?.effectiveType || 'unknown',
};
navigator.sendBeacon('/api/rum-data', JSON.stringify(payload));
metrics.length = 0; // Clear the queue
}
// Send data when the user navigates away or switches tabs
document.addEventListener('visibilitychange', () => {
if (document.visibilityState === 'hidden') {
sendMetrics();
}
});
// Also send on page unload as a final attempt
window.addEventListener('pagehide', sendMetrics);
The trap: Collecting data from 100% of users on a high-traffic site is expensive and unnecessary. Implement sampling. You might only enable the RUM agent for 10% of page views. This gives you a statistically significant dataset without overwhelming your backend or running up costs.
What to do with the data
Raw numbers are useless. The value of RUM is in the insights you derive from aggregated data.
The trap: Looking at averages. An average LCP of 2.5s might hide the fact that 10% of your users are experiencing an LCP of 12s. Averages hide outliers, but outliers often represent your most frustrated users.
Always analyze performance using percentiles:
- p75 (75th percentile): The experience of most users. This is your baseline.
- p90, p95, p99: The experience of your "long tail" users. This is where you'll find the worst problems, often tied to specific networks, devices, or regions. Improving the p99 score has a huge impact on user satisfaction.
Next, segment your data. A sudden performance regression is rarely global. You need to slice the data by dimensions like:
- Country or region
- Browser and version
- Device type (desktop, mobile)
- Network connection type (4g, wifi)
- A/B test variant
This is how you turn "LCP got worse" into "LCP for users on Chrome in Brazil increased by 500ms after the last deployment." Now you have a specific, actionable problem to solve.
Answering "Design a RUM system"
This is a common system design question. Don't just list APIs. Structure your answer to show you understand the entire system, from client to dashboard.
- Goals & Metrics: Start by defining what you want to achieve. "Our goal is to identify performance regressions and understand the experience of real users. We will start by tracking Core Web Vitals (LCP, INP, CLS) and JS errors."
- Client-Side Agent: Describe the JS agent. Mention it's small, async, and uses
PerformanceObserverto collect metrics. Explain that it batches data and usesnavigator.sendBeaconto send it onvisibilitychangeorpagehide. Mention sampling for high-traffic sites. - Data Pipeline: Briefly describe the backend. An ingestion endpoint receives the beacon data. This data is then processed, enriched (e.g., with GeoIP lookups), and stored in a database suitable for time-series data and fast queries (like ClickHouse or a managed data warehouse).
- Analysis & Alerting: Explain how you'll use the data. "We will build dashboards showing p75 and p95 percentiles for our key metrics, segmented by page, country, and device. We will set up automated alerts to notify the on-call engineer if the p75 LCP for our checkout page degrades by more than 10%."
Finally, discuss the build vs. buy trade-off. You can use a vendor like Datadog, Sentry, or New Relic for a quick setup with rich features. Or you can build a custom solution for more control and lower long-term cost, but with a significant upfront engineering investment. Acknowledging this trade-off shows senior-level thinking.
Try it
Open the developer console on a complex website (like a news site or e-commerce platform). Paste in the PerformanceObserver code for LCP from this lesson and navigate around. Inspect the PerformanceEntry objects that get logged to see the rich data the browser provides.
Next: We'll look at a different kind of cross-domain interaction in CORS: Cross-Origin Resource Sharing.
Lock it in — apply this lesson under interview conditions.