Create a browser perf budget: LCP/CLS/INP gates and alerts.
- User
Create a browser perf budget: LCP/CLS/INP gates and alerts.
Assistant
The user wants to create a "browser performance budget" with specific focus on:
- Core Web Vitals metrics: Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), and Interaction to Next Paint (INP).
- Mechanisms: "Gates" (blocking a build/deploy if thresholds are exceeded) and "Alerts" (notifications when thresholds are near or breached).
I need to structure the answer to provide actionable advice for different contexts (CI/CD pipelines, browser tools, and monitoring services).
1. Defining the Thresholds (The Budget):
- First, I need to define what "good" values are based on Google's recommendations.
- LCP: < 2.5s (Good), > 4.0s (Poor).
- CLS: < 0.1 (Good), > 0.25 (Poor).
- INP: < 200ms (Good), > 500ms (Poor).
- Strategy: Set the "Warning" slightly above "Good" and the "Error/Gate" at or slightly below "Poor" to catch regressions early.
2. Implementation Strategies:
- Local/Development: Lighthouse CLI, Chrome DevTools.
- CI/CD (The "Gate"): This is crucial. How do we block a PR?
- Tools: Lighthouse CI (Github Actions), Sitespeed.io, Webpack/Build plugins.
- Configuration: JSON config files for Lighthouse.
- RUM (Real User Monitoring) (The "Alert"): Catching issues in production.
- Tools: Google Search Console (basic), Vercel/Netlify analytics, DataDog/New Relic/Sentry, or the Performance API.
3. Structuring the Response:
- The Numbers: Start with the specific budget numbers in a table.
- The "Gate" (CI/CD): Show how to implement this in a CI pipeline (using Lighthouse CI as the standard example).
- The "Alert" (RUM/Synthetics): Show how to set up monitoring.
- The Code: Provide actual configuration snippets (JSON for Lighthouse, JS for custom checks).
Drafting the Content - Section by Section:
-
Section 1: The Budget Table.
- Metric | Good (Target) | Warning | Fail (Gate).
- I should emphasize INP as it's the newest metric replacing FID.
-
Section 2: CI/CD Gate (Pull Request checks).
- Tool: Lighthouse CI (LHCI). It's the industry standard for this.
- Config:
lighthouserc.json. - Code:
"assertions": { "categories:performance": ["error", {"minScore": 0.9}], "largest-contentful-paint": ["error", {"maxNumericValue": 2500}], ... } - Alternative: Webpack performance hints (asset size) - but user asked for LCP/CLS/INP specifically, which are runtime metrics, not just bundle size. Stick to Lighthouse/Puppeteer.
-
Section 3: Production Alerts (RUM).
- This is harder to code generically because it depends on the provider.
- I will provide a generic JavaScript snippet using the
web-vitalslibrary to send data to an analytics endpoint. This allows the user to build a custom alert in their dashboard (Grafana/DataDog). - Code:
import { onLCP, onFID, onCLS, onINP } from 'web-vitals'; function sendToAnalytics(metric) { const body = JSON.stringify(metric); // Use navigator.sendBeacon or fetch } onLCP(sendToAnalytics); onCLS(sendToAnalytics); onINP(sendToAnalytics);
-
Section 4: Implementation Details & Best Practices.
- Budget setting: Don't set the gate at exactly 2.5s for LCP if your current average is 2.4s. It will be flaky. Set it at 3.0s or set a percentage regression limit.
- Environments: Lab data (CI) vs Field data (RUM). CI is usually faster/better hardware than real users. Adjust budget accordingly.
Refining the Content:
- Correction: INP replaced FID. Make sure to highlight INP.
- Clarification: A "Gate" usually prevents merging. An "Alert" usually notifies via Slack/Email.
Final Polish:
- Create a clear, copy-pasteable configuration for the CI part.
- Create a clear, copy-pasteable script for the RUM part.
- Explain why specific values were chosen.
(Self-Correction during drafting): The user might be using a specific platform like Vercel or Netlify. I should mention that these platforms have built-in "Performance Guards" now. However, a generic CI approach (GitHub Actions + LHCI) is more universally applicable. I will focus on the generic approach but mention platform specifics as a side note.
Plan:
- Define the Metrics & Thresholds: Standard Google thresholds adjusted for a strict budget.
- The "Gate" (CI/CD): Lighthouse CI configuration.
- The "Alert" (Production/RUM):
web-vitalslibrary implementation. - Tooling: Recommendations for monitoring services. Here is a comprehensive Performance Budget strategy focusing on the Core Web Vitals (LCP, CLS, INP).
This guide is divided into three parts:
- The Thresholds: Recommended limits for "Good" (pass), "Warn" (alert), and "Fail" (gate).
- The Gate (CI/CD): How to block deployments that regress performance using Lighthouse CI.
- The Alert (RUM): How to monitor real users in production using the
web-vitalslibrary.
1. The Thresholds
Based on Google's Core Web Vitals standards (passing the 75th percentile), here is a strict budget configuration.
Metric Target (Good) Warn (Needs Opt) Fail (Gate Break) Context LCP (Largest Contentful Paint) < 2.5s 2.5s – 4.0s > 4.0s Loading speed INP (Interaction to Next Paint) < 200ms 200ms – 500ms > 500ms Interactivity CLS (Cumulative Layout Shift) < 0.1 0.1 – 0.25 > 0.25 Visual stability TTFB (Time to First Byte) < 800ms 800ms – 1800ms > 1800ms Server response
2. The Gate: CI/CD Implementation
To prevent regressions, we use Lighthouse CI in your pipeline (GitHub Actions, GitLab CI, Jenkins). This runs tests against every Pull Request.
Setup:
- Create a
lighthouserc.jsonfile in your project root. - Configure the
assertsection to enforce the budget.
File:
lighthouserc.json{ "ci": { "collect": { "url": ["http://localhost:3000/"], "numberOfRuns": 3 }, "assert": { "assertions": { "categories:performance": ["error", {"minScore": 0.9}], "largest-contentful-paint": ["error", {"maxNumericValue": 4000}], "cumulative-layout-shift": ["error", {"maxNumericValue": 0.25}], "interaction-to-next-paint": ["error", {"maxNumericValue": 500}], "total-blocking-time": ["warn", {"maxNumericValue": 600}], "speed-index": ["warn", {"maxNumericValue": 5000}] } }, "upload": { "target": "temporary-public-storage" } } }How it works:
- Error: If a metric exceeds the
maxNumericValue(or falls belowminScore), the CI job fails (Exit code 1), blocking the merge. - Warn: The build passes, but a warning is printed in the logs. Use this for metrics you are currently optimizing but haven't mastered yet.
3. The Alert: Real User Monitoring (RUM)
Lab data (CI) isn't enough. You need to track how real users on 4G networks or low-end devices experience your site.
We use the
web-vitalslibrary to send data to your analytics backend (Google Analytics, Datadog, Splunk, or a custom endpoint).Step 1: Install the library
npm install web-vitalsStep 2: Implement the Observer Create a utility function to calculate INP (since it requires observing interactions over time) and capture LCP/CLS.
// utils/performanceMonitoring.js import { onLCP, onINP, onCLS } from 'web-vitals'; const sendToAnalytics = (metric) => { // Replace this URL with your analytics endpoint (e.g., Datadog, Splunk, GA4) const url = 'https://analytics.example.com/vitals'; // Determine the status for alerting logic const status = metric.rating === 'good' ? 'pass' : metric.rating === 'needs-improvement' ? 'warn' : 'fail'; const body = JSON.stringify({ name: metric.name, value: metric.value, rating: metric.rating, delta: metric.delta, id: metric.id, page: window.location.pathname, // Add user context if relevant (e.g., device type, logged in status) }); // Use `navigator.sendBeacon` if available to ensure data is sent // even if the page closes during the request. if (navigator.sendBeacon) { navigator.sendBeacon(url, body); } else { fetch(url, { body, method: 'POST', keepalive: true }); } }; export const initPerformanceMonitoring = () => { onLCP(sendToAnalytics); onINP(sendToAnalytics); onCLS(sendToAnalytics); };Step 3: Initialize in App Entry
// index.js or App.js import { initPerformanceMonitoring } from './utils/performanceMonitoring'; // Only run in production to save costs/traffic if (process.env.NODE_ENV === 'production') { initPerformanceMonitoring(); }
4. Alerting Logic (The Dashboard)
Simply collecting data isn't enough; you need to configure the Alert in your dashboarding tool (e.g., Datadog, Grafana, Sentry).
Recommended Alert Policy:
Trigger a "High Priority" alert (Slack/PagerDuty) if the 75th percentile (p75) of users exceeds the failure threshold over a rolling 1-hour window.
- Why p75? Core Web Vitals are assessed at the 75th percentile. Averages hide outliers; p75 ensures the experience is good for the majority of users, not just the fastest ones.
Example Alert Configuration (Pseudo-code):
IF p75(real_user_lcp) > 4.0s FOR 1 hour: TRIGGER Critical Alert: "LCP Regression Detected" IF p75(real_user_inp) > 500ms FOR 1 hour: TRIGGER Critical Alert: "Site is Unresponsive (INP)"
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.