Create a CWV regression guard: budgets, performance gates, and rollbacks.
- User
Create a CWV regression guard: budgets, performance gates, and rollbacks.
Assistant
Create a CWV regression guard: budgets, performance gates, and rollbacks.
The user wants a "CWV regression guard". CWV stands for Core Web Vitals. The request asks for three specific components:
I need to create a system or a guide on how to implement this. I should probably frame this as a technical implementation guide or a configuration template for a CI/CD environment (like GitHub Actions).
Key components to cover:
Defining Budgets:
Performance Gates (The "Guard"):
Rollbacks:
Drafting the solution structure:
budgets.json or similar.Refining the details:
Self-Correction/Refinement during thought process:
main in the first place (Shift Left). But if they mean production monitoring, I should include a mention of Real User Monitoring (RUM) based rollbacks (though that's advanced). I'll stick to the Pre-deploy CI Guard as the primary solution, and mention Production Monitoring as the safety net.Final Plan:
performance-budget.json.Let's write the code.
{
"ci": { "assert": { "assertions": { ... } } }
}
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@...
Let's add a more "programmatic" guard (custom script) for flexibility if they don't want to just use LHCI default assertions. Actually, LHCI is better. I'll stick to the standard LHCI configuration but explain the assertion matrix clearly.
Core Web Vitals Thresholds (Google):
I will provide a complete, copy-pasteable solution using GitHub Actions and Lighthouse CI, as this is the most common implementation of this request.
Structure:
lighthouserc.json.Let's write it out. This guide implements a Core Web Vitals (CWV) Regression Guard using a "Shift-Left" strategy. This system defines strict performance budgets, enforces them as a quality gate in your CI/CD pipeline, and outlines the strategy for automated rollbacks.
We will use Lighthouse CI (the industry standard) and GitHub Actions, but the logic applies to any CI platform.
First, we must define what "good" looks like. We will define this in a configuration file that lives in your repository. This creates a "Single Source of Truth" for performance.
Create a file named budget.json (or place this inside your lighthouserc.json).
The Thresholds (based on Google's "Good" ratings):
budget.json
[
{
"path": "/*",
"timings": [
{
"metric": "largest-contentful-paint",
"budget": 2500
},
{
"metric": "interaction-to-next-paint",
"budget": 200
},
{
"metric": "cumulative-layout-shift",
"budget": 0.1
},
{
"metric": "total-blocking-time",
"budget": 300
},
{
"metric": "speed-index",
"budget": 3000
}
],
"resourceSizes": [
{ "resourceType": "script", "budget": 300 },
{ "resourceType": "total", "budget": 1000 }
]
}
]
The "Gate" prevents code from merging if it violates the budget. We will use Lighthouse CI to run audits on every Pull Request.
Configuration: Create lighthouserc.json in your project root.
{
"ci": {
"collect": {
"url": ["http://localhost:3000/"],
"numberOfRuns": 3
},
"assert": {
"assertions": {
"categories:performance": ["error", { "minScore": 0.9 }],
"largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
"interaction-to-next-paint": ["error", { "maxNumericValue": 200 }],
"cumulative-layout-shift": ["error", { "maxNumericValue": 0.1 }]
}
},
"upload": {
"target": "temporary-public-storage"
}
}
}
The Workflow (GitHub Actions):
Create .github/workflows/cwv-guard.yml.
name: CWV Regression Guard
on:
pull_request:
branches: [main]
jobs:
check-performance:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node
uses: actions/setup-node@v3
with:
node-version: 18
- name: Install Dependencies
run: npm ci
- name: Build Application
run: npm run build
# Run the server in the background
- name: Run Server
run: npm run start &
env:
PORT: 3000
# The Gate: Lighthouse CI
- name: Run Lighthouse CI
uses: treosh/lighthouse-ci-action@v9
with:
configPath: ./lighthouserc.json
uploadArtifacts: true
How the Gate Works:
assert configuration checks the results against your budget.If you need complex logic (e.g., "Fail only if regression is > 10%"), standard config files aren't enough. You need a custom script.
scripts/check-cwv.js
const fs = require('fs');
// 1. Load current results (usually output by Lighthouse CI as .json)
// In a real CI, you would parse the output file from the previous step
const summaryResults = JSON.parse(fs.readFileSync('./lhci/results.json'));
// 2. Define Guards
const GUARDS = {
lcp: { max: 2500, degradationAllowance: 0.05 }, // Allow 5% degradation, but hard cap at 2.5s
cls: { max: 0.1, degradationAllowance: 0 },
inp: { max: 200, degradationAllowance: 0.1 }
};
let shouldFail = false;
// 3. Compare against Baseline (Mocking baseline fetch)
const baseline = { lcp: 2100, cls: 0.05, inp: 150 };
const current = summaryResults.audits;
console.log("--- CWV Regression Report ---");
for (const [metric, rules] of Object.entries(GUARDS)) {
const value = current[metric].numericValue;
const limit = rules.max;
const prev = baseline[metric];
const isHardCapHit = value > limit;
const isRegression = value > prev * (1 + rules.degradationAllowance);
if (isHardCapHit || isRegression) {
console.error(`❌ FAIL [${metric.toUpperCase()}]: ${value} (Baseline: ${prev}, Limit: ${limit})`);
shouldFail = true;
} else {
console.log(`✅ PASS [${metric.toUpperCase()}]: ${value}`);
}
}
if (shouldFail) {
process.exit(1); // Kills the CI pipeline
}
If a regression slips through CI (e.g., it only happens on production data or specific user segments), you need a Runtime Guard and a Rollback plan.
If you use a platform like Vercel, Netlify, or AWS Amplify, configure the build settings to "fail the build" if the CI step (Step 2) fails. This effectively creates a "Pre-deploy Rollback."
For specific regressions caused by a heavy interactive component (e.g., a new Chatbot widget causing high INP):
Conceptual RUM Alert Logic:
// Pseudo-code for a Lambda/Sentry/SpeedCurve webhook handler
module.exports = (req, res) => {
const { metric, value } = req.body;
if (metric === 'INP' && value > 300) {
// Trigger Rollback API call
await fetch('https://api.vercel.com/v13/deployments/{id}/rollback', {
method: 'POST',
headers: { Authorization: `Bearer ${VERCEL_TOKEN}` }
});
console.log("CWV Regression detected. Rolled back deployment.");
}
};
budget.json.lighthouse-ci-action runs on every PR. If metrics exceed budget, the build fails.