Browser Performance Budget Gate: LCP, CLS, INP
I'll build a complete performance budget gate for your web app. This enforces Core Web Vitals thresholds:
| Metric | Good Threshold | Budget (Gate Fail) |
|---|
| LCP (Largest Contentful Paint) | ≤2.5s | >2.5s |
| CLS (Cumulative Layout Shift) | ≤0.1 | >0.1 |
| INP (Interaction to Next Paint) | ≤200ms | >200ms |
Architecture Overview
Lab Data (CI Gate) Field Data (RUM + Alerts)
├── GitHub Actions + LHCI ├── web-vitals.js (browser)
│ └── Fails PRs/MRs ├── Report to backend API
│ └── Slack alerts └── Node.js backend: Check budgets → Alerts
- CI Gate (Lab Data): Uses Lighthouse CI (LHCI) to audit URLs/PR builds. Fails CI if budgets breached.
- RUM Gate (Field Data): Client-side
web-vitals reports real-user metrics to a Node.js backend. Backend aggregates (e.g., p75) and alerts on breaches (Slack/Email).
Prerequisites:
- Node.js 18+
- GitHub repo (for CI example)
- Slack webhook for alerts (free)
1. CI Gate: Lab Data with LHCI (Fails Builds)
LHCI runs Lighthouse audits in CI, asserts budgets, and collects baselines.
Step 1: Install LHCI
npm init -y
npm i -D @lhci/cli lighthouse
npx lhci autorun --collect.url=https://your-site.com
Step 2: Config File (lighthouse-ci.config.js)
module.exports = {
ci: {
collect: {
url: ['https://your-site.com'], // Or dynamic PR preview URLs
numberOfRuns: 3,
settings: {
formFactor: 'desktop', // Or 'mobile'
screenEmulation: { mobile: false, width: 1350, height: 940 },
throttling: { rttMs: 40, throughputKbps: 10240, cpuSlowdownMultiplier: 1 },
onlyCategories: ['performance'],
},
},
assert: {
assertions: {
'categories:performance': ['warn', { minScore: 0.9 }], // Overall perf score
'largest-contentful-paint': ['error', { maxNumericValue: 2500 }], // ms
'cumulative-layout-shift': ['error', { maxNumericValue: 0.1 }],
'interaction-to-next-paint': ['error', { maxNumericValue: 200 }], // Requires Lighthouse 11+
},
},
upload: {
target: 'temporary-public-storage', // Or GitHub/GCS/S3
},
},
};
Step 3: GitHub Actions Workflow (.github/workflows/perf-gate.yml)
This runs on PRs/pushes, fails if budgets breached, posts Slack alert.
name: Perf Budget Gate
on: [pull_request, push]
jobs:
lhci:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 20 }
- run: npm ci
- run: npm run build # Build your app (e.g., next build)
- uses: lighthouse-ci/action@v0.2.0 # Or manual npx lhci autorun
with:
configPath: lighthouse-ci.config.js
env:
LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} # Optional for PR previews
- name: Slack Alert on Failure
if: failure()
uses: 8398a7/action-slack@v3
with:
status: failure
fields: repo,message,commit,author,action,eventName,ref,workflow
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} # Add to GitHub secrets
Usage:
Other CI: Jenkins (npx lhci autorun), GitLab (similar YAML).
2. RUM Monitoring & Alerts: Field Data Gate
Client-side metrics → Backend → Aggregate (p75) → Alert if >budget.
Step 1: Client-Side (web-vitals.js)
Add to your site (e.g., <head> or app.tsx for Next.js).
<script src="https://unpkg.com/web-vitals@4/dist/web-vitals.umd.js"></script>
<script>
const API_URL = 'https://your-backend.com/api/perf'; // Your server
// Report on session end or periodically
webVitals.getCLS(sendToAnalytics);
webVitals.getLCP(sendToAnalytics);
webVitals.getINP(sendToAnalytics);
function sendToAnalytics(metric) {
fetch(API_URL, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
metric: metric.name,
value: metric.value,
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: Date.now(),
}),
});
}
</script>
Step 2: Backend (Node.js + Express)
Simple server: Receives metrics, stores in SQLite (or Postgres/Redis), computes p75 every 5min, alerts if breached.
mkdir perf-gate-backend && cd $_
npm init -y
npm i express sqlite3 better-sqlite3 cron node-fetch
npm i -D nodemon
server.js:
const express = require('express');
const Database = require('better-sqlite3');
const cron = require('node-cron');
const fetch = require('node-fetch');
const app = express();
app.use(express.json());
const db = new Database('perf-metrics.db');
db.exec(`
CREATE TABLE IF NOT EXISTS metrics (
id INTEGER PRIMARY KEY, metric TEXT, value REAL, url TEXT, ua TEXT, timestamp INTEGER
)
`);
// Receive metric
app.post('/api/perf', (req, res) => {
const stmt = db.prepare('INSERT INTO metrics (metric, value, url, ua, timestamp) VALUES (?, ?, ?, ?, ?)');
stmt.run(req.body.metric, req.body.value, req.body.url, req.body.ua, req.body.timestamp);
res.sendStatus(200);
});
// Aggregate p75 & check budgets every 5min
cron.schedule('*/5 * * * *', async () => {
const now = Date.now();
const hourAgo = now - 3600000; // Last hour for rolling window
const budgets = {
'largest-contentful-paint': 2500,
'cumulative-layout-shift': 0.1,
'interaction-to-next-paint': 200,
};
for (const [metric, budget] of Object.entries(budgets)) {
const recent = db.prepare(`
SELECT value FROM metrics
WHERE metric = ? AND timestamp > ?
ORDER BY value
`).all(metric, hourAgo);
if (recent.length === 0) continue;
// p75 (75th percentile)
const p75 = recent[Math.floor(recent.length * 0.75)].value;
if (p75 > budget) {
await alertSlack(`🚨 Perf Budget Breach!\n${metric.toUpperCase()}: p75=${p75.toFixed(0)}${metric.includes('paint') ? 'ms' : ''} > ${budget}`);
console.log(`Alert sent: ${metric} p75=${p75} > ${budget}`);
}
}
});
async function alertSlack(message) {
await fetch('https://hooks.slack.com/services/YOUR/SLACK/WEBHOOK', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ text: message }),
});
}
app.listen(3000, () => console.log('Perf backend on :3000'));
Run: node server.js (or nodemon server.js). Deploy to Vercel/Heroku/Railway.
- Dashboard Bonus: Add
/api/dashboard endpoint for Grafana/Prometheus export.
- Scale: Use Redis for metrics, ClickHouse for big data.
3. Testing & Baselines
- Local Test:
npx lhci autorun
- RUM Test: Open site incognito, interact, check backend DB.
- Baselines: Run LHCI 10x, set budgets to p90 of baselines.
Customization
- Thresholds: Edit budgets in configs.
- Alerts: Email (nodemailer), PagerDuty, Discord.
- Advanced:
- INP polyfill for older browsers.
- URL-specific budgets.
- Integrate with Sentry/Cloudflare Web Analytics.
This gates deploys and alerts prod regressions. Ping me for tweaks! 🕵️♂️