Skip to content
TheChatArchiveThe Chat Archive
GLMGLM-5 / Pony Alpha· unknownHugging Face Frontier Reasoning Traces

Build a performance budget CI gate: bundle budgets, image limits, font constraints,…

  1. User

    Build a performance budget CI gate: bundle budgets, image limits, font constraints, failing build actions, and ownership.

  2. GLM 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:

    1. Bundle budgets: Limits on JS/CSS bundle sizes.
    2. Image limits: Constraints on image sizes (individual or total).
    3. Font constraints: Limits on font file sizes or numbers.
    4. Failing build actions: What happens when a budget is exceeded (the gate should fail).
    5. 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 like bundlesize or size-limit are often simpler. However, Lighthouse covers 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/vite have 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-limit or 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.json standard.

    Structure of the Response:

    1. Conceptual Overview: Briefly explain what a Performance Budget CI Gate is.
    2. Configuration (The Budget): Create a budget.json file. This is the standard format supported by Lighthouse and Chrome DevTools. I will define the constraints here (bundles, images, fonts).
    3. CI Workflow (The Gate): Create a GitHub Actions workflow (as it's the most common) to run the check.
    4. Ownership (The People): Explain how to map these budgets to teams/codeowners.
    5. Failing Strategy: How to block the PR.

    Drafting the Content:

    • 1. The Budget File (budget.json):

      • Need resourceSizes.
      • Script: Limit total bytes for script.
      • Stylesheet: Limit total bytes for stylesheet.
      • Image: Limit total bytes for image.
      • Font: Limit total bytes for font.
      • Document: Limit document.
      • Also, mention resourceCount (too many requests).
    • 2. The CI Pipeline (GitHub Actions):

      • Checkout code.
      • Install dependencies.
      • Build the app.
      • Run Lighthouse CI.
      • LHCI needs a lighthouserc.json file.
    • 3. lighthouserc.json Configuration:

      • Point to the budget.json.
      • Define assert settings. This is where the "Fail" logic lives. assertPreset: "lighthouse:all" or custom assertions.
    • 4. Ownership:

      • How to tie this to developers? CODEOWNERS file is the standard way in GitHub.
      • Example: *-failure.md reports or commenting on PRs.
    • 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.json handles resource types well, but specific file checks might need a tool like bundlesize or 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: script resource type.
      • Image: image resource type.
      • Font: font resource type.
    • Ownership: I will suggest using a performance-fallback.md or assigning owners in the config comments.

    Let's structure the solution into 3 parts:

    1. The Configuration (The budget.json).
    2. The CI Workflow (The GitHub Action).
    3. The Governance (Ownership & Actions).

    Self-Correction during drafting: Just showing budget.json isn'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.

    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 fs and glob is often better for "hard" limits on build artifacts. I'll include a bonus section for a "Hard Asset Budget" script.

    Plan:

    1. Introduction: Philosophy of the gate.
    2. Layer 1: High-Level Resource Budgets (Lighthouse CI). Use budget.json.
      • Good for: Total page weight, script time, network requests.
    3. 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.
    4. Layer 3: CI Configuration (GitHub Actions).
      • Integrates both layers.
    5. 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:

    1. 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.
    2. 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.json to 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 artifacts
    

    5. Ownership & Failing Actions Strategy

    When this CI gate fails, you need a protocol to handle it without blocking critical hotfixes indefinitely.

    A. The CODEOWNERS Integration

    Map the owners defined in your performance-budget.json to your CODEOWNERS file (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.

    1. Immediate Failure: The CI exits code 1. The PR cannot be merged into the protected branch.
    2. Notification: Use a bot (like Slack or GitHub Actions annotations) to comment on the PR:
      • Example: "🚨 Performance Budget Exceeded. The hero-bg.jpg is 1.2MB (Limit: 100KB). Owner: @design-system."
    3. 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.json file in the same PR.
      • Review: This change triggers a required review from the @frontend-platform team (via CODEOWNERS) to approve the regression.

    Summary of Protection

    • Bundles: Prevent unchecked library bloat (checked by check-budgets.js).
    • Images: Prevent unoptimized uploads (checked by check-budgets.js and Lighthouse uses-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.