Build a performance budget CI gate: bundle budgets, image limits, font constraints,…
- User
Build a performance budget CI gate: bundle budgets, image limits, font constraints, failing build actions, and ownership.
Assistant
The user wants to build a "Performance Budget CI Gate". This means creating a system or configuration that runs within a Continuous Integration (CI) pipeline (like GitHub Actions, GitLab CI, Jenkins, etc.) to check if the code changes violate predefined performance budgets.
The request asks for specific components:
- Bundle budgets: Limits on JS/CSS bundle sizes.
- Image limits: Constraints on image sizes (individual or total).
- Font constraints: Limits on font file sizes or numbers.
- Failing build actions: What happens when a budget is exceeded (the gate should fail).
- Ownership: Assigning responsibility for specific budgets.
I need to provide a comprehensive solution. Since the user didn't specify a specific tool (like Lighthouse, Webpack, bundlesize, custom scripts), I should choose a modern, popular, and robust stack.
Proposed Stack:
- Tooling:
Lighthouse CI(LHCI) is the industry standard for automated performance auditing, but for just budgets (specifically file sizes), tools likebundlesizeorsize-limitare often simpler. However,Lighthousecovers runtime performance as well. - Let's go with a hybrid approach or a specific configuration file approach that is tool-agnostic but implementable.
- Actually,
webpack/vitehave built-in performance hints, but a CI gate needs to be more explicit. - Best Approach: Use a configuration file (JSON/YAML) that defines the budget, and a script/CI workflow to enforce it.
- I will provide a complete example using Lighthouse CI (LHCI) because it's the most comprehensive (covers runtime + resource sizes) and is widely supported.
- Alternative: I will also include a lightweight alternative using
size-limitor a custom Node.js script for specific file constraints because LHCI can be heavy to set up for just file sizes. - Let's focus on a structured, "best practice" configuration using Lighthouse CI as the primary engine, as it handles "performance budget" natively via the
budget.jsonstandard.
Structure of the Response:
- Conceptual Overview: Briefly explain what a Performance Budget CI Gate is.
- Configuration (The Budget): Create a
budget.jsonfile. This is the standard format supported by Lighthouse and Chrome DevTools. I will define the constraints here (bundles, images, fonts). - CI Workflow (The Gate): Create a GitHub Actions workflow (as it's the most common) to run the check.
- Ownership (The People): Explain how to map these budgets to teams/codeowners.
- Failing Strategy: How to block the PR.
Drafting the Content:
-
1. The Budget File (
budget.json):- Need
resourceSizes. - Script: Limit
totalbytes forscript. - Stylesheet: Limit
totalbytes forstylesheet. - Image: Limit
totalbytes forimage. - Font: Limit
totalbytes forfont. - Document: Limit
document. - Also, mention
resourceCount(too many requests).
- Need
-
2. The CI Pipeline (GitHub Actions):
- Checkout code.
- Install dependencies.
- Build the app.
- Run Lighthouse CI.
- LHCI needs a
lighthouserc.jsonfile.
-
3.
lighthouserc.jsonConfiguration:- Point to the
budget.json. - Define
assertsettings. This is where the "Fail" logic lives.assertPreset: "lighthouse:all"or custom assertions.
- Point to the
-
4. Ownership:
- How to tie this to developers?
CODEOWNERSfile is the standard way in GitHub. - Example:
*-failure.mdreports or commenting on PRs.
- How to tie this to developers?
-
5. "Failing Build Actions":
- Explain that exit codes kill the CI job.
- Explain how to generate reports (GitHub PR comments).
Refining the specifics:
- Bundle Budgets: Often people want specific entry points (e.g.,
main.js< 200kb).budget.jsonhandles resource types well, but specific file checks might need a tool likebundlesizeor a custom script. - Decision: I will provide a solution that uses Lighthouse CI for resource types (easier standard) and a custom Node.js script (or
size-limit) for specific file checks. This adds value by covering both bases. - Actually, let's keep it cohesive. Lighthouse is great for the "page weight" aspect. Let's stick to Lighthouse CI as the primary "Gate" mechanism because it validates the final rendered page, which is what users actually experience.
- Wait, the prompt asks for specific constraints.
- Bundle:
scriptresource type. - Image:
imageresource type. - Font:
fontresource type.
- Bundle:
- Ownership: I will suggest using a
performance-fallback.mdor assigning owners in the config comments.
Let's structure the solution into 3 parts:
- The Configuration (The
budget.json). - The CI Workflow (The GitHub Action).
- The Governance (Ownership & Actions).
Self-Correction during drafting: Just showing
budget.jsonisn't enough. The user needs to know how to run it. I will create a standard Lighthouse CI setup.- Step 1:
budget.json(The core request).- Define limits for script, image, font.
- Step 2:
lighthouserc.json(The CI config).- Link budget.
- Define assertions (fail the build if budget exceeded).
- Step 3: GitHub Action.
- Run the check.
- Step 4: Ownership & Actions.
- Explain
CODEOWNERS. - Explain PR comments.
- Explain
Let's add a "Custom Budget Script" alternative. Sometimes Lighthouse is overkill or hard to configure in headless environments for just raw file sizes. A simple Node script using
fsandglobis often better for "hard" limits on build artifacts. I'll include a bonus section for a "Hard Asset Budget" script.Plan:
- Introduction: Philosophy of the gate.
- Layer 1: High-Level Resource Budgets (Lighthouse CI). Use
budget.json.- Good for: Total page weight, script time, network requests.
- Layer 2: Strict Artifact Budgets (Custom Node Script).
- Good for: "bundle.js must be < X bytes", "hero.png must be < Y bytes".
- I will write a concise script for this.
- Layer 3: CI Configuration (GitHub Actions).
- Integrates both layers.
- Layer 4: Ownership & Governance.
- CODEOWNERS integration.
Let's refine the "Custom Script" part. It's very practical.
- Script reads a config:
[{ path: "dist/*.js", limit: "500kb" }]. - It checks file sizes.
- It outputs a report.
- It exits 1 on failure.
This combination (Lighthouse for page-level, Script for file-level) is the "Professional" way to do it.
Final Polish of the Content:
- Make sure to explicitly mention "Failing Build Actions" (Exit codes).
- Make sure to explain "Ownership" (Tagging teams).
Let's write the response. This implementation guide establishes a Performance Budget CI Gate using a two-layered approach:
- Layer 1 (Strict Asset Limits): Hard limits on specific files (JS bundles, images, fonts) using a lightweight Node.js script. This fails the build immediately if a single file is too big.
- Layer 2 (Page Weight Budgets): holistic budgets using Lighthouse CI to check total page weight and network transfer costs.
Here is the complete system.
1. Define the Budgets (
performance-budget.json)Create a configuration file at the root of your project. This acts as the single source of truth.
{ "ownership": { "default": "#frontend-platform", "assets/images": "#design-system", "src/fonts": "#brand-team" }, "assetLimits": [ { "name": "Main Bundle", "path": "dist/static/js/main.*.js", "limitKb": 150, "owner": "#frontend-platform" }, { "name": "Vendor Bundle", "path": "dist/static/js/vendor.*.js", "limitKb": 300, "owner": "#frontend-platform" }, { "name": "Hero Images", "path": "dist/assets/images/hero-*.{jpg,png,webp}", "limitKb": 100, "owner": "#design-system" }, { "name": "Custom Fonts (per weight)", "path": "dist/fonts/*.woff2", "limitKb": 50, "owner": "#brand-team" } ], "lighthouseBudgets": { "resourceSummary": { "script": 500, "stylesheet": 100, "image": 1000, "font": 150, "total": 2000 } } }2. The CI Gate Script (
scripts/check-budgets.js)This script runs during CI. It glob-matches your built files against the budget config.
const fs = require('fs'); const path = require('path'); const { globSync } = require('glob'); // Ensure 'glob' is installed const configPath = path.join(process.cwd(), 'performance-budget.json'); const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); let hasViolations = false; console.log('🔍 Running Performance Budget Check...\n'); config.assetLimits.forEach(rule => { // Find files matching the pattern const files = globSync(rule.path); if (files.length === 0) { console.log(`⚠️ SKIP: No files found for pattern "${rule.name}" (${rule.path})`); return; } files.forEach(file => { const stats = fs.statSync(file); const sizeKb = stats.size / 1024; const fileName = path.basename(file); if (sizeKb > rule.limitKb) { hasViolations = true; const diff = (sizeKb - rule.limitKb).toFixed(2); console.error( `❌ FAIL: ${rule.name} (${fileName}) is ${sizeKb.toFixed(2)}KB. ` + `Limit is ${rule.limitKb}KB (Over by ${diff}KB). ` + `Owner: ${rule.owner}` ); } else { console.log( `✅ PASS: ${rule.name} (${fileName}) - ${sizeKb.toFixed(2)}KB / ${rule.limitKb}KB` ); } }); }); if (hasViolations) { console.error('\n🚨 Performance Budget Violated! Build Failing.'); process.exit(1); } else { console.log('\n✅ All Performance Budgets Passed.'); process.exit(0); }3. Lighthouse CI Integration (Page Weight)
While the script above checks individual files, Lighthouse checks the loaded page. Create a
lighthouserc.jsonto enforce total constraints (e.g., total JS shouldn't exceed 500KB compressed).// lighthouserc.json { "ci": { "assert": { "assertions": { "resource-summary:script:size": ["error", {"maxNumericValue": 500000}], "resource-summary:total:size": ["error", {"maxNumericValue": 2000000}], "uses-optimized-images": "error", "uses-webp-images": "error", "font-display": "error" } }, "upload": { "target": "temporary-public-storage" } } }4. GitHub Actions Workflow (
.github/workflows/performance.yml)This workflow runs on Pull Requests. It builds your app, checks specific file sizes using the script, and then runs Lighthouse against a static server.
name: Performance Budget Gate on: pull_request: branches: [main] jobs: check-budgets: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-node@v3 with: node-version: 18 - name: Install Dependencies run: npm ci - name: Build Application run: npm run build # Gate 1: Strict Asset Checks - name: Check Asset Budgets run: node scripts/check-budgets.js # Gate 2: Lighthouse Checks (Runtime & Network) - name: Run Lighthouse CI uses: treosh/lighthouse-ci-action@v9 with: configPath: './lighthouserc.json' uploadArtifacts: true # Saves Lighthouse reports as CI artifacts5. Ownership & Failing Actions Strategy
When this CI gate fails, you need a protocol to handle it without blocking critical hotfixes indefinitely.
A. The
CODEOWNERSIntegrationMap the owners defined in your
performance-budget.jsonto yourCODEOWNERSfile (GitHub/GitLab feature).- File:
.github/CODEOWNERS - Content:
# Performance infra /performance-budget.json @frontend-platform @tech-lead # Specific heavy assets /dist/assets/images/ @design-system /dist/fonts/ @brand-team - Result: When a PR fails the budget, the system automatically requests a review from the responsible team.
B. Failure Escalation Policy
Don't just let the build fail; annotate the PR.
- Immediate Failure: The CI exits code 1. The PR cannot be merged into the protected branch.
- Notification: Use a bot (like Slack or GitHub Actions annotations) to comment on the PR:
- Example: "🚨 Performance Budget Exceeded. The
hero-bg.jpgis 1.2MB (Limit: 100KB). Owner: @design-system."
- Example: "🚨 Performance Budget Exceeded. The
- The "Emergency Valve":
Sometimes a budget must be exceeded (e.g., a critical new feature requires a large library).
- Process: The owner must update the
performance-budget.jsonfile in the same PR. - Review: This change triggers a required review from the
@frontend-platformteam (via CODEOWNERS) to approve the regression.
- Process: The owner must update the
Summary of Protection
- Bundles: Prevent unchecked library bloat (checked by
check-budgets.js). - Images: Prevent unoptimized uploads (checked by
check-budgets.jsand Lighthouseuses-optimized-images). - Fonts: Prevent loading heavy system fonts (checked by
check-budgets.js). - Ownership: Ensures the right people are tagged to fix the issue, preventing the "someone else's problem" syndrome.