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

Build a browser perf budget enforcement: CI checks, budgets, and alerts.

  1. User

    Build a browser perf budget enforcement: CI checks, budgets, and alerts.

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

    1. What is a performance budget? (Briefly define metrics: LCP, FID, CLS, bundle size, etc.)
    2. How to measure it? (Tools: Lighthouse, WebPageTest, etc.)
    3. How to enforce it in CI? (GitHub Actions, GitLab CI, etc.)
    4. 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:

    1. Introduction: Define the concept and the metrics.
    2. Local Development Setup:
      • Define the budget (JSON file).
      • Tool: Lighthouse CI (LHCI).
    3. CI/CD Integration (The "Enforcement" part):
      • Example: GitHub Actions workflow.
      • How to fail the build if the budget is exceeded.
    4. Monitoring & Alerts (Post-deployment):
      • Real User Monitoring (RUM) vs. Synthetic.
      • Tools: Vercel/Netlify analytics, Sentry, or custom webhook for Slack.
    5. 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-ci is the specific tool for automation.

    • Budget File: budget.json (standard format supported by Lighthouse/Chrome).

    • CI Example:

      • Action: treosh/lighthouse-ci-action is a popular and easy-to-use action.
      • Steps: Build -> Upload static files -> Run LHCI -> Check assertions.
    • 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:

    1. Step 1: Define Your Budgets (The budget.json).
    2. Step 2: Local Validation (Pre-commit hooks or local CLI).
    3. Step 3: CI Enforcement (GitHub Actions example).
    4. Step 4: Automated Alerts (Slack webhook example).
    5. 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-limit is great for asset budgets. lighthouse-ci is 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:

    1. budget.json (Lighthouse format).
    2. lighthouserc.json (Configuration for CI).
    3. GitHub Action YAML.
    4. 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:

    1. Conceptual Architecture
    2. Phase 1: Definition (budget.json)
    3. Phase 2: Configuration (lighthouserc.json)
    4. Phase 3: CI Pipeline (GitHub Actions)
    5. 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:

    1. Asset Budgets (Build Time): JavaScript bundle sizes, CSS sizes. Fast feedback.
    2. 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 performance configuration option in webpack.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-filesize and size-limit packages.

    Install:

    npm install --save-dev size-limit @size-limit/preset-app
    

    package.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.json file.

    // 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.yml

    name: 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: true
    

    What happens here?

    1. The CI builds your app.
    2. Lighthouse CI starts a server, runs tests 3 times (to average out variance), and asserts the metrics defined in lighthouserc.json.
    3. If largest-contentful-paint exceeds 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:

    1. Condition: transaction.duration (LCP) > 2.5s.
    2. Frequency: Critical issues occur > 5 times in 1 hour.
    3. 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.js

    const 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:

    GateToolAction
    Editor/LocalESLint / Import Cost PluginWarn developer immediately while typing.
    Pull RequestGitHub Actions + Lighthouse CIBlock Merge if metrics fail.
    ProductionSentry / Vercel Analytics / RUMAlert via Slack/PagerDuty if real users suffer slowness.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.