Frontend System Design · Lesson 16 of 86 · 5 min
Browser-Level Caching Mechanisms
This is about choosing the right tool for the job: HTTP cache, Service Workers, or Web Storage. Your interviewer wants to see you weigh the trade-offs.
The four layers of browser cache
Your browser has multiple places to store data. Knowing which one to use, and when, is a core frontend skill. Think of them as layers, from automatic to fully manual.
-
HTTP Cache: The browser's built-in, automatic cache. It works based on HTTP headers you learned about in the last lesson (
Cache-Control,ETag). It's the first line of defense for static assets like CSS, images, and JS bundles. You configure it on the server, and the browser handles the rest. -
Service Worker (Cache API): A programmable proxy living between your app and the network. It lets you intercept any outgoing request and decide what to do: serve from a cache you control, fetch from the network, or generate a response yourself. This is your tool for offline support and complex caching strategies.
-
Web Storage (
localStorage/sessionStorage): Simple key-value stores. Good for small amounts of string data, like user settings or auth tokens. It's synchronous, so don't put anything large in there. -
IndexedDB: A full, client-side, transactional database. Use this when you need to store large amounts of structured data (think megabytes of JSON objects or even files) and query it efficiently.
Here is the decision flow for the most common layer, the HTTP cache, which the browser manages for you.
When to use client-side storage (and when not to)
Web Storage (localStorage and sessionStorage) is easy to use, which makes it easy to abuse.
The trap: A junior developer will suggest localStorage for caching API responses. Don't be that person. localStorage is a synchronous API, meaning it blocks the main thread. Reading or writing a large JSON string can cause your UI to stutter. It's also just a simple string-based key-value store with a typical limit around 5MB.
Use localStorage for small, non-critical data that needs to persist across sessions:
- User preferences (e.g.,
'theme': 'dark'). - A JWT or other auth token.
- A flag to indicate if you've shown a user a welcome modal.
sessionStorage is for the same kind of data, but it's cleared when the browser tab closes. It's useful for storing state related to a single user task that doesn't need to survive a browser restart.
When you need to store and query actual data, use IndexedDB. It's asynchronous, won't block the main thread, and can handle much larger datasets. It's a proper database, complete with transactions and indexes. The API is complex, so you'll likely use a wrapper library like idb or Dexie.js. This is the right tool for caching API data to build an offline-capable application.
In an interview, if you're asked to store a user's settings, say
localStorage. If you're asked to store 10,000 product records for offline browsing, sayIndexedDB. Explaining why—synchronous vs. asynchronous, size limits, and querying capabilities—is what shows seniority.
How Service Workers give you total control
A Service Worker is a JavaScript file that runs in the background, separate from your main application thread. It acts as a network proxy. Once registered, it can intercept every fetch request your application makes.
This is powerful. It means you can implement custom caching logic that goes far beyond what HTTP headers allow.
The Service Worker uses the Cache API, which is a separate storage mechanism designed specifically for storing HTTP request/response pairs. It's distinct from the HTTP cache, localStorage, and IndexedDB.
Here’s a basic "cache-first" strategy. On install, the Service Worker pre-caches critical assets (the "app shell"). For subsequent requests, it checks the cache first. If a match is found, it serves the response immediately without a network roundtrip. If not, it fetches from the network.
// sw.js - The Service Worker file
const CACHE_NAME = 'app-shell-v1';
const urlsToCache = [
'/',
'/index.html',
'/styles/main.css',
'/scripts/app.js',
'/images/logo.png'
];
// On install, populate the cache.
self.addEventListener('install', event => {
event.waitUntil(
caches.open(CACHE_NAME)
.then(cache => {
return cache.addAll(urlsToCache);
})
);
});
// On fetch, intercept requests and apply a cache-first strategy.
self.addEventListener('fetch', event => {
event.respondWith(
caches.match(event.request)
.then(response => {
// If we have it in cache, serve it.
if (response) {
return response;
}
// Otherwise, fetch from the network.
return fetch(event.request);
})
);
});
This is just one pattern. In an interview, you can mention others to show your depth:
- Network First: Try the network first. If it fails (e.g., offline), fall back to the cache. Good for data that changes frequently, like a user's timeline.
- Stale-While-Revalidate: Serve from the cache immediately for speed. Simultaneously, send a network request to get a fresh version and update the cache for the next time. This is a great balance of speed and freshness.
The Service Worker is your answer for "design an offline-first web app" or "how do you ensure a fast, reliable experience on a poor mobile connection?".
A layered caching strategy for a modern web app
No single mechanism solves everything. A robust strategy combines them. When an interviewer asks you to design the caching for a new application, this is the kind of layered approach they want to hear.
-
Static Assets (JS, CSS, fonts, images): Use the HTTP cache. Your build tool should produce fingerprinted filenames (e.g.,
main.a1b2c3d4.js). Serve these files withCache-Control: public, max-age=31536000, immutable. The longmax-age(1 year) andimmutabletell the browser it can cache this file forever without re-checking. When you deploy new code, the filename hash changes, forcing a download of the new version. -
The App Shell (e.g.,
index.html): This file must be fresh, as it references your fingerprinted assets. Serve it withCache-Control: no-cache. This forces the browser to revalidate with the server on every request, ensuring the user always gets the latest HTML. A304 Not Modifiedresponse is fast if it hasn't changed. -
API Calls: The strategy depends on the data.
- For user-specific data that must be fresh (e.g.,
/api/user/profile), useCache-Control: private, no-cache. - For public data that changes infrequently (e.g.,
/api/products), you can use a shortmax-age, likeCache-Control: public, max-age=60. - For an offline-first experience, use a Service Worker with a "stale-while-revalidate" strategy to cache API calls in the Cache API or IndexedDB.
- For user-specific data that must be fresh (e.g.,
-
User Preferences: Small, non-critical data like a theme preference or a dismissed notification belongs in
localStorage. It's simple and persistent.
This layered model demonstrates that you understand the trade-offs of each mechanism and can combine them effectively.
Try it
Open the DevTools on a complex web app like Twitter, GitHub, or your company's product. In the "Network" tab, inspect the response headers for different file types (.js, .css, .png, the main document). What Cache-Control headers do you see? Now go to the "Application" tab. Look at what's stored in Local Storage, Session Storage, and IndexedDB. Can you reverse-engineer their caching strategy?
Next: We'll cover how to handle a critical part of caching: Cache Invalidation for Frontend Apps.
Lock it in — apply this lesson under interview conditions.