Back to journal

Web Engineering · 17 min read

Web Performance and Optimization Techniques: A Practical Guide with Examples

Diagnose bottlenecks, implement fixes, and enforce performance budgets across releases using Core Web Vitals, Web Standards, TypeScript, Node.js, PostgreSQL, and Redis.

Web Performance and Optimization Techniques: A Practical Guide with Examples

Web performance is a production concern, not a frontend nicety. Slow time-to-first-byte, layout shifts, and blocked main threads directly affect conversion, retention, and infrastructure cost. This guide is written for experienced web and full-stack engineers who need to diagnose bottlenecks, implement fixes, and govern performance across releases. Every section explains why a bottleneck occurs and how to resolve it in production systems using Web Standards, TypeScript, Node.js, PostgreSQL, and Redis as an example.

1. Core Web Vitals and Performance Metrics

1.1 The metrics that matter

Performance telemetry divides into field data (Real User Monitoring, or RUM) and lab data (synthetic tests). You need both because lab tests reproduce controlled conditions while RUM captures real device, network, and user variability.

Largest Contentful Paint (LCP) measures when the largest visible element—usually a hero image, heading, or block of text—renders. A slow LCP indicates that the critical resource path is blocked by server latency, render-blocking JavaScript or CSS, or client-side rendering delays. LCP is a user-centric proxy for perceived load speed.

Interaction to Next Paint (INP) replaced First Input Delay (FID) as a Core Web Vital. INP observes the latency of all click, tap, and keyboard interactions throughout a page’s lifetime and reports the worst (or near-worst) interaction delay. High INP means the main thread is occupied by long JavaScript tasks, preventing the browser from painting the next frame after user input.

Cumulative Layout Shift (CLS) quantifies unexpected movement of visible elements after the page has loaded. Layout shifts occur when injected content, late-loading web fonts, or images without intrinsic dimensions push existing content around. High CLS erodes trust and causes misclicks.

Supporting metrics include Time to First Byte (TTFB), First Contentful Paint (FCP), and Speed Index. TTFB isolates server and network latency before the browser begins parsing HTML. FCP marks when any content appears in the DOM. Speed Index measures how quickly visible parts of the page are populated during loading.

1.2 Measuring INP in the browser

Rather than relying only on synthetic scores, capture interaction latency in production using the Event Timing API. The following TypeScript snippet observes event entries and reports the processing duration from startTime to processingEnd.

const observer = new PerformanceObserver((list) => {
  for (const entry of list.getEntries()) {
    if (entry.entryType === 'event') {
      const eventEntry = entry as PerformanceEventTiming;
      const delay = eventEntry.processingEnd - eventEntry.startTime;
      // Send delay to your analytics endpoint.
      // Aggregate by interaction type and URL path before alerting.
      void navigator.sendBeacon?.(
        '/__perf/inp',
        JSON.stringify({
          name: eventEntry.name,
          delay,
          timestamp: eventEntry.startTime,
        })
      );
    }
  }
});

observer.observe({ entryTypes: ['event'], buffered: true });

Trade-off: Event Timing entries can be noisy because they include passive listeners and framework overhead. Aggregate at the p75 or p95 level per page group before treating a value as a regression.

1.3 Performance budgets

A performance budget is a quantitative ceiling on resource size, metric timing, or request count. Budgets fail when they are aspirational but unenforced. Enforce them in CI and in production monitoring.

Example JSON budget:

{
  "lcps": { "maxNumericValue": 2500, "unit": "ms" },
  "inps": { "maxNumericValue": 200, "unit": "ms" },
  "cls": { "maxNumericValue": 0.1 },
  "resourceBudgets": [
    { "resourceType": "script", "budget": 150, "unit": "KB" },
    { "resourceType": "stylesheet", "budget": 50, "unit": "KB" },
    { "resourceType": "image", "budget": 500, "unit": "KB" }
  ],
  "timing": { "TTFB": 800 }
}

Numeric thresholds such as LCP ≤ 2.5 s and INP ≤ 200 ms are current public guidance; confirm against the latest Web Vitals documentation because thresholds can be updated.

1.4 Lab vs. field telemetry

Dimension Lab (Lighthouse, WebPageTest) RUM (field telemetry)
Environment Emulated or fixed hardware, throttled network Real devices, real networks, real users
Reproducibility High; deterministic for regressions Low; subject to device and network variance
Coverage Single page load or scripted flow All page views and interactions
Best use case Pre-merge regression detection Post-release degradation alerts
Limitation Does not capture INP reliably across full session Requires instrumentation and endpoint cost

Use lab tests to block pull requests. Use RUM to confirm that lab improvements translated to real users.

2. Network and Transport Optimization

2.1 HTTP/2 and HTTP/3 (QUIC)

HTTP/2 allows multiplexing over a single TCP connection, header compression via HPACK, and server push (deprecated in many implementations). HTTP/3 runs over QUIC, which uses UDP and reduces head-of-line blocking at the transport layer, offers faster connection establishment, and supports connection migration.

Production implications: HTTP/2 is broadly supported and should be enabled on origin and CDN. HTTP/3 improves tail latency on lossy mobile networks but requires UDP egress through firewalls and load balancers. Terminating HTTP/3 at the edge and HTTP/2 to the origin is a common topology.

HTTP/3 support in your CDN provider and client browser versions should be verified before relying on it for critical paths.

2.2 Cache-Control, ETag, and stale-while-revalidate

Browsers cache responses based on Cache-Control. Versioned assets (e.g., main.a1b2c3.js) can be cached aggressively:

Cache-Control: public, max-age=31536000, immutable
ETag: "a1b2c3"

HTML and API responses usually need shorter lifetimes or revalidation:

Cache-Control: no-cache
ETag: "W/abc123"

The stale-while-revalidate directive permits the browser to serve a stale response while asynchronously fetching a fresh one. Example:

Cache-Control: public, max-age=60, stale-while-revalidate=86400

This is ideal for non-critical JSON APIs where slight staleness is acceptable but blocking on revalidation is not.

In Node.js:

import { createServer } from 'node:http';

const server = createServer((req, res) => {
  if (req.url === '/app.js') {
    res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');
    res.setHeader('ETag', '"a1b2c3"');
    res.end(Buffer.from('...'));
  } else if (req.url === '/api/config') {
    res.setHeader('Cache-Control', 'public, max-age=60, stale-while-revalidate=86400');
    res.setHeader('ETag', '"W/config-v2"');
    res.end(JSON.stringify({ featureFlags: {} }));
  } else {
    res.setHeader('Cache-Control', 'no-cache');
    res.statusCode = 404;
    res.end();
  }
});

ETags support conditional requests (If-None-Match), but weak validators (W/) indicate semantic equivalence rather than byte equality. Strong validators are preferable for cached binary assets; weak validators work for content that may differ in formatting but not meaning.

2.3 CDNs and edge logic

Content Delivery Networks cache static assets at points of presence (PoPs) close to users. Beyond static caching, edge functions can rewrite headers, run A/B experiments, or serve personalized HTML without reaching the origin.

Trade-offs: Edge cache invalidation is slower and more complex than browser cache invalidation. Purge APIs have propagation delays. Personalization at the edge increases cache key cardinality, which can reduce hit ratios unless you segment by cookie or device class deliberately.

2.4 Resource hints

Resource hints tell the browser to prepare for future navigations or downloads. They do not block rendering but consume early bandwidth.

Hint Purpose When to use
dns-prefetch Resolve DNS for a third-party domain Domains you know you will contact but cannot preconnect to securely
preconnect Perform DNS, TCP, and TLS handshake early Origins serving critical resources (fonts, APIs, CDN)
preload Fetch a specific resource with high priority Fonts, hero images, or critical CSS needed for LCP
prefetch Fetch a resource for a likely future navigation Next-page assets when navigation probability is high
modulepreload Preload ES modules Module graph entry points before execution

HTML example:

<link rel="preconnect" href="https://api.example.com" crossorigin>
<link rel="preconnect" href="https://fonts.example.com" crossorigin>
<link rel="preload" as="image" href="/hero.avif" imagesrcset="/hero-800.avif 800w, /hero-1200.avif 1200w" imagesizes="(min-width: 1200px) 1200px, 100vw">
<link rel="modulepreload" href="/app/main.js">

preload competes with other resources for bandwidth. Do not preload assets that are not needed for the initial render; doing so can delay LCP-critical resources by saturating the connection.

3. Asset and Media Optimization

3.1 Image formats and responsive markup

AVIF and WebP provide superior compression compared to JPEG and PNG, reducing transfer size for the same visual quality. Serve them conditionally with fallback formats.

<picture>
  <source srcset="hero.avif" type="image/avif">
  <source srcset="hero.webp" type="image/webp">
  <img
    src="hero.jpg"
    alt="Product hero image"
    width="1200"
    height="800"
    loading="eager"
    decoding="async"
  >
</picture>

Always include width and height on `` elements, or reserve space with CSS aspect-ratio, so the browser can allocate layout space before the image decodes. This prevents layout shift and improves CLS.

Use loading="lazy" for images below the fold:

<img src="below-fold.jpg" alt="..." loading="lazy" width="600" height="400">

Trade-off: Never apply loading="lazy" to the LCP candidate image. Lazy-loading the hero image delays its fetch until after the initial render cycle, directly harming LCP.

The srcset and sizes attributes let the browser select an asset based on viewport width and device pixel ratio:

<img
  srcset="photo-480.jpg 480w, photo-800.jpg 800w, photo-1200.jpg 1200w"
  sizes="(min-width: 1024px) 800px, (min-width: 600px) 60vw, 100vw"
  src="photo-800.jpg"
  alt="..."
>

3.2 Video and audio delivery

For video, avoid preload="auto" unless playback is certain. Use preload="none" or preload="metadata" and provide a poster image so the first paint does not include a black video box.

<video
  poster="video-poster.jpg"
  preload="none"
  width="1280"
  height="720"
>
  <source src="video.av1.mp4" type='video/mp4; codecs="av01.0.05M.08"'>
  <source src="video.h264.mp4" type='video/mp4; codecs="avc1.42E01E"'>
  Your browser does not support the video tag.
</video>

AV1 codec support varies by browser and operating system; confirm target audience coverage before removing H.264 fallbacks.

For adaptive bitrate streaming, HLS or DASH with segmented delivery is preferable to serving a single large MP4, because the client can match bitrate to network conditions.

3.3 Web fonts: subsetting, WOFF2, and font-display

Web fonts are render-blocking by default in many browsers because text remains invisible until the font loads (FOIT). Serve WOFF2, subset glyphs to the characters you actually use, and control the swap behavior with font-display.

@font-face {
  font-family: 'Inter';
  src: url('/fonts/inter-latin-subset.woff2') format('woff2');
  unicode-range: U+000-5FF; /* Basic Latin and Latin-1 Supplement */
  font-weight: 400 700;
  font-display: swap;
  font-style: normal;
}

body {
  font-family: 'Inter', system-ui, sans-serif;
}

font-display: swap shows a system font immediately and swaps to the web font when ready, eliminating invisible text but potentially causing a layout shift if the fallback and web fonts have different metrics. font-display: optional uses the web font only if it is available in the first ~100 ms, otherwise falls back permanently; this is safest for CLS but sacrifices branding on slow connections.

Subsetting reduces file size significantly but means any character outside the subset renders with the fallback. Build font subsets as part of your asset pipeline rather than serving entire typeface families.

4. Frontend Rendering and JavaScript Optimization

4.1 Critical rendering path

The browser parses HTML into the DOM, parses CSS into the CSSOM, combines them into the render tree, performs layout, and then paints. JavaScript blocks the parser unless deferred or async, and CSS blocks rendering until the CSSOM is constructed.

Place stylesheets in <head>, defer non-critical scripts, and inline critical CSS for above-the-fold content so the first paint does not wait for external stylesheet round trips.

4.2 Code splitting, tree shaking, and bundle size

Monolithic JavaScript bundles increase parse and compile time, delaying interactivity. Split code at route or feature boundaries using dynamic import().

// routes/dashboard.ts
async function loadDashboardModule() {
  const { Dashboard } = await import('./Dashboard');
  return new Dashboard(document.getElementById('app')!);
}

Tree shaking removes unused exports at build time when using ES module syntax. Side-effect-free imports ("sideEffects": false in package.json) improve tree shaking reliability, but be cautious: some packages rely on side effects for polyfills or CSS injection.

Trade-off: Code splitting introduces additional network round trips. Pair dynamic imports with loading states or skeleton UIs so users are not presented with a blank shell while a chunk fetches.

4.3 Breaking up long tasks

Long tasks (> 50 ms) block the main thread and inflate INP. Yield to the browser between chunks of work so it can handle input and paint.

Modern browsers expose scheduler.yield():

// scheduler.yield() browser support should be confirmed before production use
async function processItems(items: unknown[]) {
  for (const item of items) {
    processItem(item);
    if (shouldYield()) {
      await scheduler.yield();
    }
  }
}

If scheduler.yield() is unavailable, fall back to setTimeout or requestIdleCallback:

async function yieldToMain(): Promise<void> {
  return new Promise((resolve) => setTimeout(resolve, 0));
}

If you are doing some heavy computation you can move it off the main thread entirely using Web Workers.

worker.ts:

type ComputePayload = { data: number[] };
type ComputeResult = { sum: number; mean: number };

self.onmessage = (event: MessageEvent<ComputePayload>) => {
  const { data } = event.data;
  let sum = 0;
  for (let i = 0; i < data.length; i++) {
    sum += data[i];
  }
  self.postMessage({ sum, mean: sum / data.length } as ComputeResult);
};

main.ts:

const worker = new Worker(new URL('./worker.ts', import.meta.url), { type: 'module' });

worker.onmessage = (event: MessageEvent<ComputeResult>) => {
  console.log('computed', event.data);
};

worker.postMessage({ data: [1, 2, 3, 4, 5] } as ComputePayload);

Trade-off: Workers cannot access the DOM. Marshaling data between threads has serialization cost; only offload tasks expensive enough to justify that overhead.

4.4 Layout thrashing and CLS prevention

Layout thrashing occurs when JavaScript interleaves reading layout properties (offsetWidth, getBoundingClientRect) with writing styles (style.width, classList.add). Each read forces the browser to flush pending layout invalidations.

Bad:

for (const element of elements) {
  element.style.width = `${element.offsetWidth + 10}px`; // read then write per iteration
}

Good:

const widths = elements.map((el) => el.offsetWidth); // batch reads
elements.forEach((el, i) => {
  el.style.width = `${widths[i] + 10}px`; // batch writes
});

Use requestAnimationFrame for visual updates and CSS contain: layout or content-visibility: auto to isolate expensive subtrees from the main layout calculation.

Note a minor CSS quirk in the snippet itself: offsetWidth includes content + padding + border, whereas setting style.width sets only the content width (unless box-sizing: border-box is applied). If an element uses the default content-box and has 20px of padding, setting style.width = offsetWidth + 10 will actually grow the element by 30px

5. Backend, Database and Caching Architecture

5.1 Reducing Time to First Byte (TTFB) in Node.js

TTFB comprises DNS, TCP/TLS, server processing, and the first byte of the response. On the application side, reduce processing time by streaming responses rather than buffering full payloads, and compress compressible content.

TTFB=Redirect+Service Worker Startup+DNS Lookup+TCP/TLS Handshake+Request Transit+Server Processing\text{TTFB} = \text{Redirect} + \text{Service Worker Startup} + \text{DNS Lookup} + \text{TCP/TLS Handshake} + \text{Request Transit} + \text{Server Processing}

Node.js with native Brotli and Gzip:

import { createServer } from 'node:http';
import { createBrotliCompress, createGzip } from 'node:zlib';
import { createReadStream } from 'node:fs';

const server = createServer((req, res) => {
  const acceptEncoding = req.headers['accept-encoding'] ?? '';
  let compressionStream;

  if (acceptEncoding.includes('br')) {
    res.setHeader('Content-Encoding', 'br');
    compressionStream = createBrotliCompress();
  } else if (acceptEncoding.includes('gzip')) {
    res.setHeader('Content-Encoding', 'gzip');
    compressionStream = createGzip();
  }

  const fileStream = createReadStream('./public/index.html');

  if (compressionStream) {
    fileStream.pipe(compressionStream).pipe(res);
  } else {
    fileStream.pipe(res);
  }
});

server.listen(3000);

Brotli generally achieves better compression ratios than Gzip at the cost of higher CPU usage. Pre-compress static assets at build time and serve them with Content-Encoding headers so the origin does not compress on every request.

For server-side rendering, use streaming APIs (e.g., renderToPipeableStream) so the browser receives HTML chunks while the server continues rendering the remainder. This reduces TTFB and FCP compared to waiting for full HTML generation before sending anything.

5.2 PostgreSQL query tuning

Slow database queries are a leading cause of elevated TTFB. Start with EXPLAIN ANALYZE to inspect execution plans.

Indexes should match query predicates, but adding indexes indiscriminately slows writes and increases storage. Create indexes concurrently to avoid locking production tables:

CREATE INDEX CONCURRENTLY idx_orders_user_id_created_at
  ON orders (user_id, created_at DESC);

CREATE INDEX CONCURRENTLY cannot run inside a transaction in PostgreSQL; manage migrations accordingly.

Eliminate N+1 queries by fetching related rows in a single query with a JOIN or ANY clause instead of looping.

Bad pattern (conceptual):

// N+1: one query for users, then one query per user for posts
const users = await db.query('SELECT * FROM users');
for (const user of users.rows) {
  const posts = await db.query('SELECT * FROM posts WHERE user_id = $1', [user.id]);
}

Better pattern:

const result = await db.query(
  `
  SELECT u.id, u.name, p.title, p.created_at
  FROM users u
  LEFT JOIN posts p ON p.user_id = u.id
  WHERE u.id = ANY($1::int[])
  ORDER BY u.id, p.created_at DESC
  `,
  [[1, 2, 3]]
);

Connection pooling prevents exhausting PostgreSQL connections under load.

import { Pool } from 'pg';

const pool = new Pool({
  max: 20,
  idleTimeoutMillis: 30_000,
  connectionTimeoutMillis: 5_000,
});

async function getUser(id: number) {
  const client = await pool.connect();
  try {
    const { rows } = await client.query('SELECT * FROM users WHERE id = $1', [id]);
    return rows[0];
  } finally {
    client.release();
  }
}

Read replicas scale read traffic but introduce replication lag. Route writes to the primary and reads to replicas only when eventual consistency is acceptable (e.g., public profiles, not checkout flows).

5.3 Redis caching and invalidation

Use Redis as an application cache with the cache-aside pattern: check the cache, miss to the database, populate the cache, and invalidate on writes.

import Redis from 'ioredis';

const redis = new Redis({ maxRetriesPerRequest: 3 });

async function getUserProfile(userId: string) {
  const key = `profile:${userId}:v1`;
  const cached = await redis.get(key);

  if (cached !== null) {
    return JSON.parse(cached);
  }

  const { rows } = await pool.query(
    'SELECT id, email, display_name FROM users WHERE id = $1',
    [userId]
  );
  const profile = rows[0];

  if (profile) {
    await redis.set(key, JSON.stringify(profile), 'EX', 3600);
  }

  return profile;
}

async function updateUserProfile(userId: string, data: Record<string, unknown>) {
  await pool.query(
    'UPDATE users SET display_name = $1 WHERE id = $2',
    [data.display_name, userId]
  );

  // Invalidate after the commit succeeds
  await redis.del(`profile:${userId}:v1`);
}

Trade-offs: Cache stampede occurs when a popular key expires and many requests hit the database simultaneously. Mitigate with short probabilistic early expiration, per-key mutexes, or background refresh. Invalidation must happen after database commits, not before, to avoid serving stale data following a failed transaction.

Version cache keys (v1, v2) when schema changes so old clients do not interpret new payload shapes under the same key.

6. Modern Architectural and Delivery Patterns

6.1 SSG, SSR, ISR, and islands

Static Site Generation (SSG) renders HTML at build time. It offers the lowest TTFB because edge nodes serve static files, but content staleness is tied to the build cadence.

Server-Side Rendering (SSR) renders HTML per request. TTFB is higher than SSG, but content is always fresh.

Incremental Static Regeneration (ISR) regenerates static pages on demand or at intervals after deployment, combining static delivery with limited freshness.

Islands Architecture hydrates only interactive components (“islands”) rather than the entire page, reducing client-side JavaScript execution and improving INP on content-heavy sites.

Mode Build cost Request-time cost TTFB Staleness risk Best for
SSG High Minimal Lowest High (until rebuild) Marketing sites, docs, blogs
SSR Low Moderate Moderate Low Dashboards, personalized content
ISR High Low (on revalidate) Low Moderate E-commerce product pages
Islands Moderate Minimal to low Low Depends on island Content sites with interactive widgets

6.2 Service Worker caching

Service Workers intercept network requests and can implement cache-first, network-first, or stale-while-revalidate strategies independent of HTTP headers.

// sw.ts
const CACHE_NAME = 'assets-v1';

self.addEventListener('install', (event) => {
  event.waitUntil(
    caches.open(CACHE_NAME).then((cache) => {
      return cache.addAll(['/', '/app.js', '/style.css']);
    })
  );
});

self.addEventListener('fetch', (event) => {
  const { request } = event;
  event.respondWith(
    caches.match(request).then((cached) => {
      if (cached) return cached;
      return fetch(request).then((response) => {
        if (!response || response.status !== 200 || response.type !== 'basic') {
          return response;
        }
        const responseToCache = response.clone();
        caches.open(CACHE_NAME).then((cache) => {
          cache.put(request, responseToCache);
        });
        return response;
      });
    })
  );
});

Trade-offs: Service Workers control cache invalidation outside HTTP semantics. Old caches can serve stale assets indefinitely unless versioned and cleared during activation. Scope and storage quotas also limit how much you can persist.

6.3 Progressive enhancement

Deliver core functionality in server-rendered HTML and enhance with JavaScript. If JavaScript fails to load or execute, forms should still submit and navigation should still work. This reduces reliance on client hydration for critical paths and improves resilience on slow networks or low-capability devices.

7. Performance in CI/CD and Ongoing Governance

7.1 Performance budgets in pull requests

Automate performance enforcement so regressions are caught before merge. Lighthouse CI can run audits against preview deployments and assert against budgets.

.lighthouserc.js example:

module.exports = {
  ci: {
    collect: [
      {
        url: 'https://preview.example.com',
        numberOfRuns: 3,
      },
    ],
    assert: {
      assertions: {
        'categories:performance': ['error', { minScore: 0.9 }],
        'LCP': ['error', { maxNumericValue: 2500 }],
        'CumulativeLayoutShift': ['error', { maxNumericValue: 0.1 }],
        'InteractionToNextPaint': ['error', { maxNumericValue: 200 }],
      },
    },
  },
};

Lighthouse CI assertion names and metric identifiers may differ by version; consult the installed package schema before committing this config.

GitHub Actions workflow example:

name: performance
on:
  pull_request:
    branches: [main]

jobs:
  lighthouse:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Install dependencies
        run: npm ci
      - name: Run Lighthouse CI
        run: npx lighthouse-ci assert --config=.lighthouserc.js

7.2 Bundle size gates

Use a bundle size tool such as size-limit to fail CI when JavaScript or CSS budgets are exceeded.

package.json:

{
  "scripts": {
    "size": "size-limit"
  },
  "size-limit": [
    {
      "path": "dist/assets/*.js",
      "limit": "150 KB"
    },
    {
      "path": "dist/assets/*.css",
      "limit": "40 KB"
    }
  ]
}

Bundle budgets should differentiate between initial and lazy-loaded chunks. A large lazy-loaded module is less harmful than a large entry-point script because it does not block time-to-interactive.

7.3 Tracking regressions across releases

Record RUM metrics keyed by release version. Compare p75 LCP, INP, and CLS between deployments. Alert when p75 degrades beyond a threshold (for example, > 10% regression) rather than on absolute values alone, because user geography and device mix can shift baselines.

Maintain a performance dashboard that correlates releases with metric changes. When a regression is detected, roll back or ship a hotfix before investigating root cause; performance governance is only effective if remediation is faster than detection.

Conclusion

Web performance optimization is a systems problem spanning network protocols, asset delivery, browser rendering, database queries, and release governance. Start by instrumenting RUM and lab tests, set measurable budgets, and enforce them in production and CI. Optimize the critical path first—TTFB, LCP-critical assets, and render-blocking resources—then address long tasks and layout stability. Cache aggressively at the browser, CDN, and application layers, but invalidate predictably. Finally, treat performance budgets as code: version them, test them, and monitor them across every release.

Written by

Chizoba Jude Ojini

Senior Software Engineer at 360dialog. I write about architecture, teams and building software people enjoy.

Say hello
Esc
↑↓ to navigate ↵ to open Esc to close