Build a browser perf budget enforcement: CI checks, budgets, and alerts.
- User
Build a browser perf budget enforcement: CI checks, budgets, and alerts.
Assistant
The user wants to build a "browser performance budget enforcement" system. This is a broad topic, but crucial for web development. I need to cover the following key components:
- What is a performance budget? (Briefly define metrics: LCP, FID, CLS, bundle size, etc.)
- How to measure it? (Tools: Lighthouse, WebPageTest, etc.)
- How to enforce it in CI? (GitHub Actions, GitLab CI, etc.)
- How to set up alerts? (Slack, Email, Dashboards).
I will structure the answer as a practical guide, providing code examples and configuration files. I'll focus on a modern tech stack (e.g., GitHub Actions + Lighthouse CI + Slack).
Plan:
- Introduction: Define the concept and the metrics.
- Local Development Setup:
- Define the budget (JSON file).
- Tool: Lighthouse CI (LHCI).
- CI/CD Integration (The "Enforcement" part):
- Example: GitHub Actions workflow.
- How to fail the build if the budget is exceeded.
- Monitoring & Alerts (Post-deployment):
- Real User Monitoring (RUM) vs. Synthetic.
- Tools: Vercel/Netlify analytics, Sentry, or custom webhook for Slack.
- Advanced Strategies:
- progressive budgets (don't fail on warning, but block on error).
- caching.
Drafting the content:
-
Metrics: Time to Interactive (TTI), Largest Contentful Paint (LCP), Cumulative Layout Shift (CLS), Total Blocking Time (TBT), and resource sizes (JS, CSS).
-
Tooling: Lighthouse is the standard open-source choice.
lighthouse-ciis the specific tool for automation. -
Budget File:
budget.json(standard format supported by Lighthouse/Chrome). -
CI Example:
- Action:
treosh/lighthouse-ci-actionis a popular and easy-to-use action. - Steps: Build -> Upload static files -> Run LHCI -> Check assertions.
- Action:
-
Alerts:
- LHCI has a built-in server, but that's hard to self-host for a quick tutorial.
- Better approach for alerts: Webhooks.
- If using a platform like Vercel/Netlify, they have built-in "Speed Insights" which alert you.
- Let's stick to a generic CI approach where the CI fails (the "enforcement") and maybe a custom script for Slack alerts.
Refining the structure for clarity:
- Step 1: Define Your Budgets (The
budget.json). - Step 2: Local Validation (Pre-commit hooks or local CLI).
- Step 3: CI Enforcement (GitHub Actions example).
- Step 4: Automated Alerts (Slack webhook example).
- Step 5: Architecture Diagram (Mental model).
Self-Correction during drafting: Make sure to distinguish between Build Time budgets (bundle size) and Runtime budgets (Lighthouse metrics). Both are important. I'll focus primarily on Lighthouse (Runtime) as it's usually the harder part to automate, but mention bundle size (webpack/vite size-limit) briefly.
Actually, combining them is best.
size-limitis great for asset budgets.lighthouse-ciis great for performance metrics. I will focus on Lighthouse CI as the primary tool for "browser perf" because it covers loading behavior, not just file size.Code Snippets to include:
budget.json(Lighthouse format).lighthouserc.json(Configuration for CI).- GitHub Action YAML.
- Node.js script for Slack alert (optional, but adds value).
Final Polish: Ensure tone is authoritative yet practical. Use formatting (bolding, code blocks) to make it readable.
Let's write the response.
- Intro: What is it?
- Metrics: Core Web Vitals.
- Tooling: Lighthouse CI.
- Config:
lighthouserc.js. - CI: GitHub Actions.
- Alerts: Slack integration.
(Self-Correction): Should I suggest WebPageTest? It's excellent but harder to automate in standard free CI pipelines due to API limits and queue times. Lighthouse CI is the standard for "shift left". I will stick to Lighthouse CI.
Let's add a specific section on "Resource Budgets" (MB) vs "Timing Budgets" (ms).
Resulting Structure:
- Conceptual Architecture
- Phase 1: Definition (budget.json)
- Phase 2: Configuration (lighthouserc.json)
- Phase 3: CI Pipeline (GitHub Actions)
- Phase 4: Alerts (Slack/Dashboard)
This looks solid. I will proceed with this structure. Building a robust performance budget enforcement system requires three layers: Definition (establishing limits), Automation (CI checks), and Observability (alerts).
Here is a comprehensive guide to implementing this using modern tooling (Lighthouse CI, GitHub Actions, and Webpack/Vite).
1. The Architecture
We will split the enforcement into two distinct budget types:
- Asset Budgets (Build Time): JavaScript bundle sizes, CSS sizes. Fast feedback.
- Runtime Budgets (CI/Testing): Core Web Vitals (LCP, CLS), Time to Interactive. Accurate feedback.
2. Define Your Budgets
Create a configuration file to hold your limits. It is best to separate "warnings" (soft limits) from "errors" (hard limits).
File:
.performance-budget.json{ "resourceSizes": [ { "resourceType": "script", "budget": 300, "unit": "kB", "level": "error" }, { "resourceType": "stylesheet", "budget": 100, "unit": "kB", "level": "error" }, { "resourceType": "image", "budget": 500, "unit": "kB", "level": "warn" }, { "resourceType": "total", "budget": 1500, "unit": "kB", "level": "error" } ], "timings": [ { "metric": "first-contentful-paint", "budget": 2000, "unit": "ms" }, { "metric": "interactive", "budget": 5000, "unit": "ms" }, { "metric": "largest-contentful-paint", "budget": 2500, "unit": "ms" } ] }
3. Implementation: Layer 1 (Build Time)
Before deploying, you should check the raw asset sizes. This prevents massive libraries from entering the codebase.
Option A: Webpack
If using Webpack, use the
performanceconfiguration option inwebpack.config.js:// webpack.config.js module.exports = { // ... performance: { maxEntrypointSize: 300000, // 300kb maxAssetSize: 300000, hints: 'error', // Fails the build on violation }, };Option B: Vite / Rollup
Use the
rollup-plugin-filesizeandsize-limitpackages.Install:
npm install --save-dev size-limit @size-limit/preset-apppackage.json:
{ "size-limit": [ { "path": "dist/assets/*.js", "limit": "300 kB" } ], "scripts": { "check-size": "size-limit" } }
4. Implementation: Layer 2 (CI Runtime Checks)
This is the most critical layer. We will use Lighthouse CI to run audits against a live preview URL (e.g., Vercel Preview, Netlify Deploy Preview) or a static server within the CI runner.
Setup: Create a
lighthouserc.jsonfile.// lighthouserc.json { "ci": { "collect": { "url": ["http://localhost:3000/"], "numberOfRuns": 3 }, "assert": { "assertions": { "first-contentful-paint": ["error", {"maxNumericValue": 2000}], "interactive": ["error", {"maxNumericValue": 5000}], "largest-contentful-paint": ["error", {"maxNumericValue": 2500}], "cumulative-layout-shift": ["error", {"maxNumericValue": 0.1}], "total-byte-weight": ["error", {"maxNumericValue": 1500000}], "unused-javascript": ["warn", {"maxLength": 20000}] } }, "upload": { "target": "temporary-public-storage" // For production, use 'lhci' server or Google Storage } } }GitHub Actions Workflow
Create a workflow that builds your app, serves it, and runs Lighthouse CI.
File:
.github/workflows/performance.ymlname: Performance Budget on: pull_request: branches: [main] jobs: lighthouse: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - name: Setup Node uses: actions/setup-node@v3 with: node-version: 18 cache: 'npm' - name: Install dependencies run: npm ci - name: Build Application run: npm run build - name: Run Lighthouse CI uses: treosh/lighthouse-ci-action@v9 with: configPath: './lighthouserc.json' uploadArtifacts: true # Saves the Lighthouse reports as build artifacts temporaryPublicStorage: trueWhat happens here?
- The CI builds your app.
- Lighthouse CI starts a server, runs tests 3 times (to average out variance), and asserts the metrics defined in
lighthouserc.json. - If
largest-contentful-paintexceeds 2500ms, the CI step fails, blocking the PR merge.
5. Implementation: Layer 3 (Alerting)
If the code passes CI and gets deployed to production, you need to monitor Real User Monitoring (RUM).
Approach A: Google Search Console (Manual/Email)
Google Search Console has a dedicated "Core Web Vitals" report. It will email you if pages fail assessments, but it is slow (uses 28-day windows).
Approach B: Sentry / DataDog (Programmatic)
If you use an APM tool like Sentry, you can set up "Cron Monitors" or "Alert Rules".
Example Sentry Alert Rule:
- Condition:
transaction.duration(LCP) >2.5s. - Frequency: Critical issues occur > 5 times in 1 hour.
- Action: Send Slack message to
#engineering.
Approach C: Custom Slack Bot (Budget Alert)
You can write a simple script to run daily against your production site and post a status to Slack.
File:
scripts/check-prod-perf.jsconst lighthouse = require('lighthouse'); const chromeLauncher = require('chrome-launcher'); const { WebClient } = require('@slack/web-api'); const slackClient = new WebClient(process.env.SLACK_BOT_TOKEN); async function runCheck() { const chrome = await chromeLauncher.launch({ chromeFlags: ['--headless'] }); const options = { logLevel: 'info', output: 'json', port: chrome.port }; const runnerResult = await lighthouse('https://your-production-site.com', options); await chrome.kill(); // Extract metrics const lcp = runnerResult.lhr.audits['largest-contentful-paint'].numericValue; // Check Budget const BUDGET_LCP = 2500; if (lcp > BUDGET_LCP) { await slackClient.chat.postMessage({ channel: '#alerts', text: `🚨 Performance Budget Exceeded! LCP is ${(lcp/1000).toFixed(2)}s (Limit: 2.5s).` }); process.exit(1); // Fail the cron job } else { console.log("Performance is within budget."); } } runCheck();
Summary Checklist
To successfully enforce a budget, ensure you have these three gates:
Gate Tool Action Editor/Local ESLint / Import Cost Plugin Warn developer immediately while typing. Pull Request GitHub Actions + Lighthouse CI Block Merge if metrics fail. Production Sentry / Vercel Analytics / RUM Alert via Slack/PagerDuty if real users suffer slowness.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.