Frontend Development 17 min read

Understanding HTTP Caching, Service Worker, Push and CDN Caching Strategies

This article explains the principles and practical configurations of HTTP forced and negotiated caching, Service Worker lifecycle and caching, HTTP/2 server push, and CDN caching, providing concrete header examples, code snippets, and recommendations for optimal front‑end performance.

IEG Growth Platform Technology Team
IEG Growth Platform Technology Team
IEG Growth Platform Technology Team
Understanding HTTP Caching, Service Worker, Push and CDN Caching Strategies

1. HTTP Caching

HTTP caching can be divided into forced caching and negotiated caching. The difference lies in whether a request to the server is needed to validate the cached response; forced caching takes precedence over negotiated caching.

1.1 Forced Caching

Key response headers related to forced caching are Cache-Control and Expires . Cache-Control has higher priority than Expires . Example headers:

cache-control: max-age=30758400
content-encoding: gzip
content-length: 73157
content-type: text/css
date: Sun, 17 Apr 2022 06:14:17 GMT
expires: Sat, 08 Apr 2023 06:14:16 GMT

The max-age directive defines the freshness period in seconds. Additional directives such as no-cache , no-store , private , public , s-maxage control validation and proxy behavior:

1.1.1 no-cache and no-store

no-cache forces a revalidation with the server on each request; no-store disables any caching. They are mutually exclusive.

1.1.2 private and public

private limits caching to the browser; public allows both browsers and shared proxies to cache the response. The default is private if not specified.

1.1.3 max-age and s-maxage

max-age sets the client‑side freshness period; s-maxage sets the freshness for shared caches and is effective only when public is present.

1.2 Negotiated Caching

Negotiated caching requires a conditional request before using the local cache. The first response includes a Last-Modified header:

last-modified: Fri, 01 Apr 2022 22:45:16 GMT

Subsequent requests send If-Modified-Since with the same timestamp. If the resource has not changed, the server returns 304 Not Modified ; otherwise it returns the fresh content.

Limitations of Last-Modified include unchanged content with a new timestamp and timestamp granularity of one second.

Etag provides a stronger validator by hashing the resource. Example headers:

content-length: 20193
content-type: image/png
date: Fri, 15 Apr 2022 02:00:36 GMT
etag: a360f3899899d21a6416236680023e8e

Etag validation is more accurate but adds CPU overhead and can be either strong or weak, affecting cache hit rates.

Choosing the appropriate validator depends on the resource characteristics.

2. Service Worker Caching

Service Workers run in a background thread independent of the main UI thread, enabling offline caching, push notifications, background sync, request interception, and custom cache strategies without blocking page rendering.

2.1 Basic Features

Runs off the main thread; cannot access the DOM directly.

Works on localhost during development; requires HTTPS in production.

Can intercept all network requests for custom handling.

State should be stored in IndexedDB because the worker may be terminated and restarted.

Uses Promises for asynchronous operations.

Supports push messages and background sync.

2.2 Lifecycle

Registration

// Check if Service Worker is supported
if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        // Register the Service Worker with optional scope
        navigator.serviceWorker.register('./serviceWorker.js', { scope: './' })
            .then(function (n) {
                console.log('ServiceWorker registration successful with scope: ', n.scope);
            })
            .catch(function (err) {
                console.log('ServiceWorker registration failed: ', err);
            });
    });
}

Installation

During registration the browser downloads serviceWorker.js and executes it. If any error occurs, the install promise rejects and the worker becomes redundant.

Activation

After installation the worker becomes active and can control pages. Calling self.skipWaiting() or reloading the page can accelerate this step.

Cache Response

In the active state the worker can intercept fetch events and serve cached resources via caches.match() . If a match is found, the cached response is returned; otherwise the request is forwarded to the network.

// Register fetch event to intercept all requests
self.addEventListener('fetch', function (event) {
    event.respondWith(
        caches.match(event.request)
            .then(function (response) {
                // Return cached response if found
                if (response) {
                    return response;
                }
                // Otherwise perform a network fetch
                return fetch(event.request);
            })
    );
});

Update

Updating a Service Worker follows the same lifecycle as a fresh installation. Cache cleanup should be performed in the activate event to avoid the old worker accessing stale caches.

3. Push Caching (HTTP/2 Server Push)

HTTP/2 introduces server push, allowing the server to send multiple responses for a single client request, reducing round‑trip latency for resources that are known in advance.

3.1 The Last Cache Layer

Browser caching consists of four layers: in‑memory cache, Service Worker cache, HTTP cache, and HTTP/2 Push cache.

3.2 Push vs. Preload

Push is initiated by the server; preload is triggered by the client after parsing link rel="preload" .

Push works only for same‑origin or authorized origins; preload can fetch from any origin.

Push uses the server‑side push cache; preload uses the in‑memory cache.

Resources pushed by the server are shared across tabs; preload resources are scoped to the requesting page.

Preload can attach onload / onerror handlers; push is transparent to the client.

Preload can negotiate content via headers; push cannot.

3.2.1 Use Cases

Server‑side push is useful when the server can predict resources needed later (e.g., server‑side rendering) or when pushing inline assets such as critical CSS.

3.2.2 Decision Flow

If a resource cannot be pushed efficiently, preload may be preferred for critical inline scripts or styles; otherwise push can pre‑cache resources that the server knows will be requested soon.

4. CDN Caching

A Content Delivery Network (CDN) distributes content across edge servers to reduce latency and offload origin servers. CDN caching complements the other three cache layers by accelerating first‑time requests.

4.1 How CDN Works

Without CDN, a request follows four steps: DNS resolution, IP address retrieval, direct request to origin server, and response delivery. With CDN, DNS points to a CDN‑specific DNS server, which returns a load‑balanced IP address of an edge node. The edge node serves cached content or fetches it from upstream caches, eventually falling back to the origin if needed.

Although the process is more complex, it is transparent to users and significantly improves load speed.

This article summarizes four caching mechanisms—HTTP cache, Service Worker cache, HTTP/2 push cache, and CDN cache—highlighting their priorities, configurations, and appropriate usage scenarios to help developers design optimal front‑end performance strategies.

web performanceCDNservice-workerHTTP CachingPush cache
IEG Growth Platform Technology Team
Written by

IEG Growth Platform Technology Team

Official account of Tencent IEG Growth Platform Technology Team, showcasing cutting‑edge achievements across front‑end, back‑end, client, algorithm, testing and other domains.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.