karawaci.kode

2026-09-29 · 9 min

Performance Budget and Web Vitals: What Your Backend Is Actually Breaking

Your LCP is 4.2 seconds in the CrUX dashboard and your frontend team says their bundle is fine. They’re right. The problem is your API response taking 1.8 seconds because nobody put an index on that created_at column six months ago.

Backend engineers own more of the Web Vitals story than most performance discussions admit. The standard framing puts Core Web Vitals — LCP, INP, CLS — as a frontend concern. That’s only half true. Performance budget violations traced back to backend decisions account for the majority of LCP regressions I’ve seen in production. TTFB alone can make an otherwise optimized frontend score “Poor” in Google’s thresholds.

This is about understanding which backend levers move which Web Vitals, setting a performance budget with teeth, and enforcing it before it reaches users.

How Backend Decisions Map to Specific Web Vitals

TTFB (Time to First Byte) is the most direct backend metric. Google’s threshold for “Good” is under 800ms. Everything above that degrades LCP by definition, since the browser can’t start rendering the largest element until it has received enough of the page.

Common backend TTFB killers:

  • N+1 queries triggered by ORM code that looks innocent but fires a query per item in a list
  • Cold starts on serverless functions that haven’t received traffic in the last few minutes
  • Blocking middleware — auth, logging, rate limiting — that runs serially when it could run in parallel
  • Uncompressed responses — I once profiled an API at a fintech client near Alam Sutera that was sending 380KB of JSON with no gzip. On a mobile 4G connection that’s 2+ extra seconds before the browser can even parse the payload

LCP (Largest Contentful Paint) is downstream of TTFB. If TTFB is 1.2 seconds, the browser starts late. But LCP is also affected by whether the server sends correct cache headers that let a CDN serve the asset without hitting origin, and whether image optimization happens at the server or forces the browser to do it.

INP (Interaction to Next Paint) is mostly a client-side metric, but API latency bleeds into it. A button click that triggers a fetch call to a slow endpoint delays the UI update, which registers as a high INP. Target: under 200ms. If your API takes 600ms per call, INP cannot be good regardless of how efficient your React event handlers are.

Setting a Performance Budget That Teams Will Actually Enforce

A budget nobody can check is not a budget. The enforcement mechanism matters as much as the numbers.

Start with three tiers:

MetricGood (block deploys above this)Needs Improvement (warn)Poor (critical alert)
TTFB800ms1200ms1800ms
LCP2.5s4.0s> 4.0s
API P95300ms600ms1000ms
Gzipped JS150KB250KB> 250KB

The “block deploys” column is your hard budget. Everything else is signal.

For API latency specifically, P95 is more useful than average. Your average response time being 120ms while P95 is 900ms means 5% of your users are getting a terrible experience — and those outliers often cluster around real usage patterns: large accounts, complex queries, or specific geographic regions.

Enforcing the Budget in CI

Lighthouse CI for page-level metrics

# .github/workflows/performance.yml
name: Performance Budget Check

on: [pull_request]

jobs:
  lighthouse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Install dependencies
        run: npm ci

      - name: Build
        run: npm run build

      - name: Run Lighthouse CI
        uses: treosh/lighthouse-ci-action@v12
        with:
          configPath: ./lighthouserc.json
          uploadArtifacts: true
// lighthouserc.json
{
  "ci": {
    "collect": {
      "url": ["http://localhost:3000", "http://localhost:3000/dashboard"],
      "startServerCommand": "npm run start:prod",
      "numberOfRuns": 3
    },
    "assert": {
      "assertions": {
        "first-contentful-paint": ["error", { "maxNumericValue": 2000 }],
        "largest-contentful-paint": ["error", { "maxNumericValue": 2500 }],
        "interactive": ["warn", { "maxNumericValue": 3500 }],
        "total-blocking-time": ["error", { "maxNumericValue": 300 }],
        "uses-text-compression": ["error", { "minScore": 1 }]
      }
    }
  }
}

The uses-text-compression assertion catches the uncompressed JSON problem at CI. It will fail the build if your server responses aren’t gzip or brotli encoded.

API latency budget via k6

For backend-specific budget enforcement, wire a k6 smoke test into CI:

// perf/api-budget.js
import http from "k6/http";
import { check } from "k6";

export const options = {
  vus: 10,
  duration: "30s",
  thresholds: {
    // Hard budget: P95 must stay under 300ms
    http_req_duration: ["p(95)<300"],
    // No more than 1% errors
    http_req_failed: ["rate<0.01"],
  },
};

export default function () {
  const res = http.get(`${__ENV.API_BASE_URL}/api/v1/products?limit=20`);
  check(res, {
    "status is 200": (r) => r.status === 200,
    "response time under 300ms": (r) => r.timings.duration < 300,
  });
}
# In your CI workflow
- name: API Performance Budget
  run: |
    k6 run perf/api-budget.js \
      -e API_BASE_URL=${{ vars.STAGING_URL }}

k6 exits with a non-zero code when thresholds fail, which blocks the pipeline. Simple, no extra tooling needed.

The Nginx Config That Quietly Breaks Your TTFB Budget

Most performance budget tools focus on what your application code does. Fewer teams audit their web server config. This Nginx block is what I typically find and fix:

# What most teams have — missing compression config
server {
    listen 80;
    location / {
        proxy_pass http://app:3000;
    }
}

This passes responses through with no compression and no caching headers. Here’s a minimal config that moves your TTFB budget in the right direction:

server {
    listen 80;

    # Enable brotli + gzip compression
    brotli on;
    brotli_types text/plain text/css application/json application/javascript;
    brotli_comp_level 6;

    gzip on;
    gzip_types text/plain text/css application/json application/javascript;
    gzip_min_length 1024;

    location /api/ {
        proxy_pass http://app:3000;
        proxy_cache api_cache;
        proxy_cache_valid 200 10s;  # Cache successful responses for 10 seconds
        proxy_cache_key "$request_method$request_uri";
        add_header X-Cache-Status $upstream_cache_status;
    }

    location ~* \.(js|css|woff2|png|jpg|svg)$ {
        proxy_pass http://app:3000;
        expires 1y;
        add_header Cache-Control "public, immutable";
    }
}

The X-Cache-Status header is not decoration. It shows HIT, MISS, or BYPASS in your browser’s Network tab and tells you whether your cache is actually doing work. Without it, you’re guessing.

What to Actually Monitor in Production

Lighthouse CI measures lab conditions. Real users are on different networks, devices, and locations. The feedback loop between your performance budget and real-world impact requires both.

Set up these three things:

1. CrUX API dashboard — Google’s Chrome User Experience Report gives you real P75 field data for pages on your domain. Free, updates weekly. If your lab budget is green but CrUX P75 LCP is red, your lab setup is not realistic.

2. Server-side TTFB logging — log response time per endpoint in your API server, not just at the load balancer. The delta between load balancer latency and application latency is your infrastructure overhead. Log at P50, P95, and P99:

// Express middleware example
app.use((req, res, next) => {
  const start = process.hrtime.bigint();
  res.on("finish", () => {
    const durationMs = Number(process.hrtime.bigint() - start) / 1e6;
    // Send to your metrics system
    metrics.histogram("http_response_time_ms", durationMs, {
      route: req.route?.path ?? "unknown",
      status: res.statusCode,
      method: req.method,
    });
  });
  next();
});

3. Alert on budget breach, not just trend — a performance budget alert fires when P95 TTFB crosses 800ms, not when it “looks like it’s trending up.” Trend-based alerts are too slow. By the time the trend is visible, your CrUX scores are already damaged.

The Part Nobody Talks About: Database Query Time Is Your LCP Budget

Here’s the uncomfortable math. If your LCP target is 2.5 seconds and your TTFB budget is 800ms, and network overhead accounts for 200ms of that TTFB, your backend has 600ms total for processing. That 600ms must cover: auth middleware, database queries, business logic, response serialization, and any downstream service calls.

A single unindexed query that takes 400ms leaves you 200ms for everything else. With an ORM making five of those queries for a single page load, you were never going to hit your performance budget regardless of what your React code does.

Run EXPLAIN ANALYZE on your slowest queries. Add covering indexes on columns used in WHERE clauses and ORDER BY. Look at your ORM’s generated SQL — most ORMs will surprise you with what they actually send to the database versus what the code looks like.

Performance budget enforcement starts in the database, not in the Lighthouse report.

Ditulis oleh Reza Pradipta