completefrontend
Open lab My progress
THE WEB PERFORMANCE FIELD GUIDE

Slow and unreliable networks

Keep a page usable on slow, patchy networks: lost packets and long waits, timeouts and retries with backoff, offline-first service workers, and data costs.

By the end, you can
  • 01
    Test a page on a bad networkCopy long waits and no signal in DevTools, and know that its Packet Loss box doesn't touch a page load.
  • 02
    Stop waiting, and try again with careGive every fetch a time limit with AbortSignal.timeout, then retry a few times with a doubling, random wait.
  • 03
    Open with no signal, and count the costKeep the shop and its last data in a service worker, and turn a page's bytes into money on a prepaid plan.

Asha's trip home

In lesson 37.2, Ravi built a lighter Mint tea page for Asha. It downloads 15 KB instead of 338 KB. Now Asha takes it on the road.

Every evening, Asha rides the train home to her village. The signal comes and goes. Near the city, it's Slow 4G. Further out, every answer takes longer to start. In the tunnels, there's no signal at all. And Asha pays for her data in advance, on a small prepaid plan.

So here is the question. What happens to Ravi's shop on a network like that? And what can Ravi do about it? The course recorded Asha's trip in Chrome. Here is what she saw at three points, without Ravi's fixes and with them:

Real frames of Ravi's Mint tea page on Asha's trip, in three columns, without and with Ravi's fixes. Long waits: without the fix, Full page, photo still loading; with it, Lighter page, photo at 2,540 ms. A silent shop: without the fix, No time limit, Loading… at 30 s; with it, Limit and retries, reviews at 5,848 ms. No signal: without the fix, Lighter page, Chrome's error page; with it, Offline-first page, shop at 44 ms.Long waitsA silent shopNo signalWithoutthe fixLong waits, Full page: photo still loadingFull pagephoto still loadingA silent shop, No time limit: Loading… at 30 sNo time limitLoading… at 30 sNo signal, Lighter page: Chrome's error pageLighter pageChrome's error pageWiththe fixLong waits, Lighter page: photo at 2,540 msLighter pagephoto at 2,540 msA silent shop, Limit and retries: reviews at 5,848 msLimit and retriesreviews at 5,848 msNo signal, Offline-first page: shop at 44 msOffline-first pageshop at 44 ms
Real frames from the recording. Top row: what Asha saw. Bottom row: the same moment with Ravi's fix. The first column is the screen 2,800 ms after she opened the page, on the network with long waits.

The top row is what went wrong. The bottom row is the same moment with Ravi's fix. Here are the numbers behind the frames:

Asha's trip, without and with the fixesPop out in the code editor (opens in a new tab)JavaScript
// Asha's trip home. Each line: what she saw without Ravi's fix, then with it.const trip = [  { where: "Long waits", without: "photo at 3,040 ms", fixed: "photo at 2,540 ms" },  { where: "A silent shop", without: "Loading… after 30 s", fixed: "50 reviews at 5,848 ms" },  { where: "No signal", without: "Chrome's error page", fixed: "the shop at 44 ms" },];for (const { where, without, fixed } of trip) {  console.log(`${where}: ${without} → ${fixed}`);}
  • Line 1 is a comment. A millisecond (ms) is a thousandth of a second. The photo's time is its largest contentful paint, or LCP, from lesson 17.1.
  • Lines 3 to 5 hold one point of the trip each. Each has what Asha saw without the fix, and what she saw with it.
  • Line 8 prints one line for each point.
  • It prints Long waits: photo at 3,040 ms → photo at 2,540 ms. Then A silent shop: Loading… after 30 s → 50 reviews at 5,848 ms. Then No signal: Chrome's error page → the shop at 44 ms.

Three problems, and three different fixes. With long waits, the lighter page showed its photo sooner. When the shop went silent, a time limit and a second try brought the reviews in about 5.8 seconds. With no signal, a copy kept on the phone opened the shop in 44 ms. Why it matters: a bad network isn't one problem. Each kind needs its own fix.

Real-life analogyA phone call on a train

You call a friend from the train. Near town, every word arrives a moment late, so you talk over each other. Now and then a word drops out, and your friend asks you to say it again. In a tunnel, the line goes quiet. You wait a few seconds, hang up, and call back later.

In real life: Every word arrives a moment late
In JavaScript: Long waits: each answer is slow to start
In real life: "Sorry, can you say that again?"
In JavaScript: A lost packet, sent again
In real life: The line goes quiet in a tunnel
In JavaScript: No signal: requests can't get through
In real life: Hanging up, then calling back
In JavaScript: A time limit, then a retry
The main idea

On a slow, patchy network, answers come late, or never, or can't come at all. Give every request a time limit and a careful retry. Keep a copy of the shop on the phone. And send as few bytes as you can. The next four sections take one problem each: the network itself, a silent shop, no signal, and the cost of every byte.

How the course recorded it

  • Ravi's pages: both versions from lesson 37.2, served by a small Node server on the laptop.
  • Asha's phone: Chrome 157, with the CPU 4 times slower, in a window 412 by 480 pixels, as in lesson 37.1.
  • Her networks: DevTools' Slow 4G preset, and two profiles of Ravi's own. One has longer waits. The other has DevTools' Packet Loss box set.
  • A silent shop: the server didn't answer some requests for the reviews. Asha's taps were mouse clicks, sent through the DevTools protocol.
  • No signal: the DevTools protocol switched the page and its service worker offline, as DevTools' Offline preset does. The server answered nothing.
  • Three of each: every test ran three times, taking turns. The lesson quotes the middle one.

Lost packets and long waits

Start with the network itself. Two things make a mobile network feel bad, even when it works. Some packets get lost. And every answer takes a long time to start.

Lost packets

A packet is one small piece of data on its way across the network. Rough radio signals lose some of them. Lesson 4.3 showed what TCP does then:

  • It sends the packet again. That costs at least one more round trip: a message there and its answer back.
  • It sends more slowly for a while. It takes the loss as a sign that the road is full.
  • On that connection, everything behind the lost packet waits for it.

If no answer comes at all, TCP waits for a timer. RFC 6298, the standard for that timer, starts it at 1 second. Each time it runs out, TCP sends the packet again and doubles the timer. The standard calls this "back off the timer". Remember that idea: Ravi's page will use it too. HTTP/3 runs on QUIC instead, and lesson 4.6 showed that a lost packet there holds up only its own file.

What DevTools' Packet Loss box does

DevTools lets you make your own network profile. Its form has boxes for download speed, upload speed and latency. It also has a Packet Loss box. So Ravi made a profile: Slow 4G with 10% packet loss. The recorder set the same thing through the DevTools protocol:

Slow 4G with 10% packet lossJavaScript
// Slow 4G, plus DevTools' Packet Loss box at 10%.await cdp.send("Network.emulateNetworkConditions", {  offline: false,  latency: 562.5,  downloadThroughput: 180000,  uploadThroughput: 84375,  packetLoss: 10,});
  • Line 2 is the protocol's command for network conditions. DevTools' menu sends the same settings.
  • Lines 4 to 6 are Slow 4G: 562.5 ms of latency, and its two speeds in bytes per second.
  • Line 7 asks for 10% packet loss.

The page loaded just as before. The full page's photo was on screen at 1,772 ms, against 1,756 ms on plain Slow 4G. Not one request failed. Why? The protocol's own description calls it "WebRTC packet loss" (Network.pdl, lines 997 to 1000). WebRTC is what web pages use for video calls. In Chromium, only the throttle for WebRTC's connections reads the box (throttling_p2p_network_interceptor.cc, lines 88 to 107). Chrome's docs say the same.

Why it matters: DevTools can't copy a lossy network for a page load. Test that on a real phone, on a real bad network.

Long waits

DevTools can copy the other problem well. Latency is how long a request waits before its answer starts. Ravi made a second profile, Long waits. It has Slow 4G's speeds, but every answer starts at least 1,200 ms after its request, instead of 562.5 ms.

The same pages, with longer waitsPop out in the code editor (opens in a new tab)JavaScript
// The photo's paint (LCP) and the last file, in ms. The middle of three loads each.const loads = [  { page: "Full page", slow4g: { photo: 1756, done: 3084 }, longWaits: { photo: 3040, done: 5328 } },  { page: "Lighter page", slow4g: { photo: 1248, done: 1242 }, longWaits: { photo: 2540, done: 2521 } },];for (const { page, slow4g, longWaits } of loads) {  console.log(`${page}: photo ${longWaits.photo - slow4g.photo} ms later, done ${longWaits.done - slow4g.done} ms later`);}
  • Lines 3 and 4 hold one page each. photo is the LCP. done is when the page's last file arrived.
  • Line 7 subtracts Slow 4G's times from the long waits' times.
  • It prints Full page: photo 1284 ms later, done 2244 ms later and Lighter page: photo 1292 ms later, done 1279 ms later.

Both photos came about 1.3 seconds later. That's two longer waits: one for the page, then one for the photo. But the full page finished 2.2 seconds later, and the lighter page only 1.3. Why the difference?

Some of the full page's files come in a chain. Each one is only asked for after the one before it arrives. It's like asking questions by post: you can't send the next letter until the answer to the last one comes back.

A chain of four waitsPop out in the code editor (opens in a new tab)JavaScript
// Each file is asked for only after the one before it has arrived.const chain = ["the page", "page.js", "fonts.css", "caveat.woff2"];const wait = 1200; // ms before each answer startsconsole.log(`${chain.length} waits in a row: at least ${chain.length * wait} ms`);
  • Line 2 is the chain. The page loads page.js. page.js adds fonts.css. fonts.css asks for the font, caveat.woff2. The recording shows the same order.
  • Line 3 is the wait before each answer starts.
  • Line 4 prints 4 waits in a row: at least 4800 ms.

Every link in the chain pays the whole wait. The lighter page has only two links: the page, then the photo. Why it matters: on a network with long waits, count the links in your longest chain, not only the bytes. Each link you remove saves one whole wait.

Read each row across: what goes wrong, what happens next, and what DevTools can copy.

Three kinds of bad network
What goes wrongWhat happensWhat DevTools can copy
A few packets go missingTCP or QUIC sends them again, and sends more slowly for a while. Everything behind a lost packet on a TCP connection waits.Nothing, for a page load. The Packet Loss box only reaches WebRTC calls.
Every answer is slow to startEach request waits longer. Files that are asked for one after another add up their waits.Latency, in a custom profile.
No signal at allNew requests fail. Chrome shows its error page for a page with no copy on the phone.The Offline preset.

Pick a network to see both pages on it:

Playground: Ravi's two pages on three networks
Full page
  1. Photo on screen (LCP)1,756 ms
  2. Last file done3,084 ms
  3. Downloaded338 KB
  4. Requests that didn't finish0 of 7
Lighter page
  1. Photo on screen (LCP)1,248 ms
  2. Last file done1,242 ms
  3. Downloaded15 KB
  4. Requests that didn't finish0 of 3
Try it yourself
Slow 4G

Asha's usual network. Every answer waits 562.5 ms before it starts.

From the course's recording in Chrome 157: the middle of 3 loads, with the CPU 4 times slower.

Timeouts and retries

Now the shop itself. On the train, Asha taps Show 50 reviews. Her request leaves the phone. Then nothing comes back. Maybe the answer was lost on the way. Maybe the server is busy. The page can't tell which. What should it do?

Here is the lighter page's code from lesson 37.2:

The reviews, with no time limitJavaScript
async function showReviews() {  const reviews = await (await fetch("reviews.json")).json();  // ... show the 50 reviews}

Line 2 asks for reviews.json and waits for the answer. Then it reads the answer as JSON. Nothing in it says how long to wait.

The course made Ravi's server ignore the first request for the reviews. Asha's button said Loading… after 1 second. It still said Loading… after 10 seconds, and after 30. The request stayed open the whole time. fetch() has no time limit of its own. Its options include a signal that can stop it, but no timeout. Why it matters: to Asha, a silent shop looks exactly like a slow one.

Real-life analogyWaiting for a bus that doesn't come

The buses come every 10 minutes. After 20 minutes with no bus, you stop waiting. You don't know if it broke down or got stuck. It doesn't matter. You take the next one, or you walk.

In real life: The bus that doesn't come
In JavaScript: An answer that never arrives
In real life: Deciding to give up after 20 minutes
In JavaScript: A time limit: AbortSignal.timeout(5000)
In real life: Taking the next bus, or walking
In JavaScript: Trying again, or showing a message

A time limit for one request

The browser gives you the time limit ready-made. AbortSignal.timeout(ms) makes a signal: an object that tells a fetch to stop. This one goes off by itself after that many milliseconds.

One fetch with a 5-second limitJavaScript
try {  const response = await fetch("reviews.json", { signal: AbortSignal.timeout(5000) });  showReviews(await response.json());} catch (error) {  if (error.name === "TimeoutError") showMessage("The shop didn't answer.");  else showMessage("The reviews couldn't load.");}
  • Line 2 passes the signal to fetch. If the answer isn't complete after 5,000 ms, the fetch stops.
  • When it stops, fetch() fails with an error named "TimeoutError". Line 5 checks for that name.
  • Line 6 handles every other error. With no network at all, for example, fetch fails at once.

How long should the limit be? Long enough for a normal answer on a slow network. Short enough that Asha doesn't give up first. On Slow 4G, the reviews took about 600 ms to arrive. Ravi picked 5 seconds: about eight times that.

Two details from MDN. The limit counts active time, so it pauses while the page sits in the back/forward cache. And Chrome before version 124 stopped with an "AbortError" instead of a "TimeoutError".

Trying again, a little later each time

A time limit turns silence into an error. But giving up after one try wastes a good chance: the next try often works. So Ravi tries up to three times, with a wait between tries.

Real-life analogyComing back to a closed bakery

After a power cut, the bakery door is locked. You come back in a few minutes, then later, then later still. Now picture the whole street coming back at exactly 9:05. The baker would be swamped. It works better when each neighbour picks a time of their own.

In real life: Coming back later
In JavaScript: A retry after a wait
In real life: Waiting longer each time
In JavaScript: Exponential backoff: the wait's ceiling doubles
In real life: Each neighbour coming back at their own time
In JavaScript: Jitter: a random part of the wait
In real life: Giving up after three visits
In JavaScript: A limit on tries, then a message

Here is Ravi's function:

getJson: a time limit, and up to three triesJavaScript
const sleep = (ms) => new Promise((done) => setTimeout(done, ms)); async function getJson(url, tries = 3) {  for (let attempt = 1; attempt <= tries; attempt++) {    try {      const response = await fetch(url, { signal: AbortSignal.timeout(5000) });      if (!response.ok) throw new Error(`HTTP ${response.status}`);      return await response.json();    } catch (error) {      if (attempt === tries) throw error;      await sleep(Math.random() * 1000 * 2 ** (attempt - 1));    }  }}
  • Line 1 is a small helper. sleep(ms) waits that many milliseconds.
  • Line 3 starts getJson. It tries up to tries times, 3 unless you say otherwise. Line 4 counts the tries.
  • Line 6 is one try, with a 5-second limit.
  • Line 7 treats an error answer, such as 503, as a failure too. Line 8 reads the JSON and returns it.
  • Line 10: if that was the last try, give up and pass the error on.
  • Line 11 waits before the next try. That wait is the clever part.

The wait has a ceiling. It's 1,000 ms after the first try, then 2,000 ms: it doubles. That's exponential backoff, the same idea as TCP's timer. And the wait is a random part of that ceiling. That's jitter. Marc Brooker showed why it matters, on AWS's blog. When many phones fail at the same moment, jitter spreads their retries out. So the server isn't swamped again.

The waits getJson picksPop out in the code editor (opens in a new tab)JavaScript
// The wait before each new try: a random part of a ceiling that doubles.const randoms = [0.62, 0.15]; // two numbers Math.random() could givefor (let attempt = 1; attempt <= 2; attempt++) {  const ceiling = 1000 * 2 ** (attempt - 1);  const wait = Math.round(randoms[attempt - 1] * ceiling);  console.log(`After try ${attempt}: up to ${ceiling} ms, this time ${wait} ms`);}
  • Line 2 stands in for Math.random(), which gives a number from 0 up to 1.
  • Line 4 is the ceiling: 1,000 ms, doubled for each try after the first.
  • Line 5 takes a random part of it.
  • It prints After try 1: up to 1000 ms, this time 620 ms and After try 2: up to 2000 ms, this time 300 ms.

Is it worth the wait? The course tapped the button on three versions:

What Asha saw after her tapPop out in the code editor (opens in a new tab)JavaScript
// Asha taps "Show 50 reviews". Times in ms after the tap.const taps = [  { version: "No time limit", tries: 1, at: 30000, saw: "Loading…" },  { version: "Time limit and retries", tries: 2, at: 5848, saw: "50 reviews" },  { version: "Shop down, with retries", tries: 3, at: 16351, saw: "a message and Try again" },];for (const { version, tries, at, saw } of taps) {  console.log(`${version}: ${tries} ${tries === 1 ? "try" : "tries"}, at ${at} ms: ${saw}`);}
  • Line 3 is lesson 37.2's page. The shop ignored its only request.
  • Line 4 is getJson. The shop ignored the first request and answered the second.
  • Line 5 is getJson again, while the shop answered nothing.
  • It prints No time limit: 1 try, at 30000 ms: Loading…. Then Time limit and retries: 2 tries, at 5848 ms: 50 reviews. Then Shop down, with retries: 3 tries, at 16351 ms: a message and Try again.
What happened after Asha tapped Show 50 reviews, from 0 to 30 seconds. No time limit: try 1 from 68 ms, never answered; still Loading…. Limit and retries: try 1 from 68 ms to 5,069 ms, no answer; try 2 from 5,247 ms, answered; reviews, 5,848 ms. Shop down: try 1 from 71 ms to 5,072 ms, no answer; try 2 from 5,613 ms to 10,613 ms, no answer; try 3 from 11,350 ms to 16,350 ms, no answer; message, 16,351 ms.No time limitstill Loading…Limit and retriesreviews, 5,848 msShop downmessage, 16,351 ms0 s5 s10 s15 s20 s25 s30 s
Times after the tap, to scale. A shaded bar is a try the shop didn't answer: the time limit ended it after 5 seconds. A plain bar is a try that was answered. The gaps between tries are the random waits.

With no limit, Asha was still looking at Loading… after 30 seconds. With the limit, the first try stopped at 5 seconds. A short wait later, the second try reached the shop. The reviews were on screen at 5,848 ms. When the shop answered nothing, Asha got a clear message at 16,351 ms, with a Try again button. It said: "The shop didn't answer. Check your signal, then try again."

In DevTools, a fetch stopped by its time limit shows as (canceled) in the Network panel's Status column. Why it matters: without a limit, Asha waits for ever. With one, the page can try again, or tell her what went wrong. Pick a version to see each try:

Playground: what happened after Asha's tap
Each try, in order
  1. Try 1 reached the shop at 68 msno answer, still open
  2. What Asha saw after 30,000 msstill "Loading…"
Try it yourself
No time limit

The lighter page from lesson 37.2. The shop never answered the first request, and nothing ever stopped it.

From the course's recording in Chrome 157, on Slow 4G with the CPU 4 times slower. Times are in ms after the tap.

Retry only requests that are safe to send twice, like reading the reviews. The system design lesson Retries, timeouts, and backoff shows which errors are worth a retry, and how to make a payment safe to repeat.

Offline-first: a shop that opens with no signal

Then the train enters a long tunnel. Asha opens Ravi's lighter page again. Chrome shows its error page, with the dinosaur. The shop is gone, though Asha saw it a minute ago. Her phone's HTTP cache still had page.js and the photo. But it had no copy of the page itself, so nothing could start.

What the page can know about the signal

The page can ask. navigator.onLine is false when the phone has no network at all. The offline and online events fire when that changes.

Reading the signalJavaScript
console.log(navigator.onLine); // false: surely no network
addEventListener("offline", () => console.log("The signal is gone."));
addEventListener("online", () => console.log("The signal is back."));
  • Line 1 reads it once.
  • Lines 2 and 3 listen for changes, on the window.

But true doesn't mean the shop will answer. MDN calls the value "inherently unreliable". A Wi-Fi network with no way to the internet still counts as online. So use false as a hint, for a notice. Never treat true as a promise. Try it in your own browser:

Playground: what your browser says about its signal
This browser, live
  1. navigator.onLine right nowreading…
Try it yourself

Open DevTools, pick Offline in the Network panel's throttling menu, then No throttling again. Or turn your Wi-Fi off and on.

This browser says it's online

true only means some network is connected. It doesn't promise that a server will answer.

Read live from this browser. Reset clears the list of changes. The lab reads nothing else and sends nothing.

A service worker that keeps the shop

To open with no signal, the shop needs a copy on the phone. That's what offline-first means. The page answers from what the phone already has, and uses the network to refresh it. Lesson 25.1 met the tool for this: a service worker. It's a script the browser runs between the page and the network.

Real-life analogyA newspaper for the train

You buy a newspaper at the station. In the tunnel, your phone shows nothing new, but you can still read the paper. The date at the top tells you how old it is. At the next station, you buy a fresh one.

In real life: The paper you bought at the station
In JavaScript: The copy the worker kept: the shop and the last reviews
In real life: Reading it in the tunnel
In JavaScript: Opening the shop with no signal
In real life: The date at the top
In JavaScript: The notice: "as it was on your last visit"
In real life: A fresh paper at the next station
In JavaScript: Refreshing the copy when there's a signal

Ravi's worker does three jobs. First, when it installs, it keeps the shop's shell: the files that draw the page, without its data.

sw.js: keep the shellJavaScript
const SHELL = ["./", "page.js", "photo-800.jpg"]; self.addEventListener("install", (event) => {  event.waitUntil(caches.open("shell").then((cache) => cache.addAll(SHELL)));});self.addEventListener("activate", (event) => event.waitUntil(self.clients.claim()));
  • Line 1 lists the shell: the page itself (./), page.js and the photo.
  • Line 4 runs when the worker installs. cache.addAll() fetches all three and stores them in Cache Storage. If one fails, the whole install fails.
  • Line 6: clients.claim() lets the new worker look after the open page at once.

Second, it picks a strategy for each request:

sw.js: one strategy per requestJavaScript
self.addEventListener("fetch", (event) => {  const { request } = event;  if (request.url.endsWith("/reviews.json")) event.respondWith(networkFirst(request));  else if (request.mode === "navigate") event.respondWith(staleWhileRevalidate(event));  else event.respondWith(cacheFirst(request));});
  • Line 3 sends the reviews to networkFirst, below.
  • Line 4 answers the page with stale-while-revalidate: the kept copy now, and a fresh one for next time.
  • Line 5 answers everything else from the cache first.

Lesson 25.1 explained both of those strategies. The third job is new: the reviews.

Asha wants fresh reviews when she can get them. So the worker asks the network first. But web.dev's offline cookbook warns about this. On a slow or patchy connection, people "wait for the network to fail" before they see the copy already on their phone. On the train, that could take for ever. So Ravi gives it the same time limit as before:

sw.js: the network first, for 5 seconds at mostJavaScript
async function networkFirst(request) {  try {    const response = await fetch(request, { signal: AbortSignal.timeout(5000) });    if (response.ok) await (await caches.open("data")).put(request, response.clone());    return response;  } catch {    return (await caches.match(request)) ?? Response.error();  }}
  • Line 3 asks the network, for at most 5 seconds.
  • Line 4 keeps a copy of a good answer in a second cache, called data.
  • Line 7: if the network failed or ran out of time, answer from the copy. With no copy, the page gets an error.

Last, page.js registers the worker, and adds a notice that shows while navigator.onLine is false. It registers after the load event. web.dev advises this, so the worker's downloads don't compete with the first visit.

What Asha saw in the tunnel

Asha opened each version twice with a signal. On her first visit, she tapped the reviews button. Then the signal went:

The third visit, with no signalPop out in the code editor (opens in a new tab)JavaScript
// Asha's third visit, with no signal. Times in ms.const visits = [  { page: "Lighter page", error: "net::ERR_INTERNET_DISCONNECTED" },  { page: "Offline-first page", shopAt: 44, reviewsAfterTap: 71 },];for (const { page, error, shopAt, reviewsAfterTap } of visits) {  if (error) console.log(`${page}: Chrome's error page, ${error}`);  else console.log(`${page}: the shop at ${shopAt} ms, 50 reviews ${reviewsAfterTap} ms after the tap`);}
  • Line 3 is the lighter page. Line 4 is the offline-first page.
  • It prints Lighter page: Chrome's error page, net::ERR_INTERNET_DISCONNECTED and Offline-first page: the shop at 44 ms, 50 reviews 71 ms after the tap.
Ravi's service worker with no signal. The page asks the worker for everything. The page, page.js and the photo come from the shell cache, cache first: the shop was on screen at 44 ms. For reviews.json, the worker tries the network first, which fails with no signal, then answers from the data cache: the reviews were on screen 71 ms after the tap.the pageservice workershell cachepage, page.js, photonetworkno signaldata cachecache firstreviews.json: network,then the copy
With no signal, every request still gets an answer. The shell comes from the cache at once. The reviews try the network, which fails, then come from the copy the worker kept.

The lighter page couldn't open at all. The offline-first page was on screen in 44 ms. That's as fast as its visit before, with a signal: both times, the worker answered from its cache. The notice said "No signal. This is the shop as it was on your last visit." Asha tapped the reviews button. The worker's network try failed at once. So it answered with the reviews from her last visit. No request from the page or its worker reached Ravi's server.

Why it matters: a copy on the phone turns "no signal" from an error page into an older shop. Label old data clearly, so Asha knows what she's looking at.

Sending things later

Reading is the easy half. What if Asha writes a review in the tunnel? The page can keep it, and send it when the online event fires. Chromium browsers also have Background Sync. The page registers a sync, and the worker gets a sync event once the connection is back. Firefox and Safari don't have it, so keep the online way too. The system design lesson Offline-first design shows how to queue changes safely.

What a visit costs on a prepaid plan

One problem is left, and Asha pays for it in money. Her plan is prepaid: she buys her data before she uses it. Every byte Ravi sends uses some of it up.

Real-life analogyTopping up a travel card

Asha tops up her travel card at the start of the month. Every trip takes its fare off. A long trip costs more than a short one. When the card is empty, she walks until she can top it up again.

In real life: The money left on the card
In JavaScript: The data left on Asha's plan
In real life: Each trip's fare
In JavaScript: Each visit's bytes
In real life: A long trip and a short one
In JavaScript: The full page and the lighter page
In real life: Walking when the card is empty
In JavaScript: No web until the next top-up

Start with the bytes. Ravi's server counted every byte it sent for one visit, headers included:

Bytes for one visitPop out in the code editor (opens in a new tab)JavaScript
// Bytes Ravi's server sent for one visit, headers included.const visits = {  "Full page": 346570,  "Lighter page": 15655,  "Offline-first page, first visit": 20304,  "Offline-first page, next visit": 4154,};for (const [visit, bytes] of Object.entries(visits)) {  console.log(`${visit}: ${Math.round(bytes / 1024)} KB`);}
  • Lines 3 and 4 are first visits to the two pages from lesson 37.2.
  • Lines 5 and 6 are the offline-first page's first visit, and its next visit with a signal.
  • Line 9 prints each one in KB. A KB is a kilobyte: 1,024 bytes. It prints Full page: 338 KB, Lighter page: 15 KB, Offline-first page, first visit: 20 KB and Offline-first page, next visit: 4 KB.

The lighter page cost 15 KB to the full page's 338 KB. The offline-first page's first visit cost 5 KB more than the plain lighter page. That's the worker itself, 1,540 bytes, a second copy of the page for the cache, and a few more lines in page.js. Its next visit cost 4 KB: a fresh copy of the page, and sw.js again. The Service Workers spec has the browser check for a new worker on visits like this.

The plain lighter page's next visit cost 3 KB. The HTTP cache (lesson 15.1) already kept page.js and the photo. So the worker doesn't save data on its own. What it adds is a shop that opens with no signal.

Now turn bytes into money. The International Telecommunication Union (ITU) is a United Nations agency. It prices the same mobile plan in every country: 5 GB of data a month, the cheapest from the biggest operator. In low-income countries, the median price is $5.87. Against income, the median is 9.42% of a month's income per person. In high-income countries, those are $15.73 and 0.43%.

Tim Kadlec built a site, What Does My Site Cost?, that works out a page's cost the same way. Take its bytes, multiply by the price of data, and compare that with income. Here is that sum for 1,000 visits:

What 1,000 visits cost in low-income countriesPop out in the code editor (opens in a new tab)JavaScript
// The 5 GB month in low-income countries: the median price, and the median share of a month's income.const plan = { bytes: 5_000_000_000, usd: 5.87, incomeShare: 9.42 };function thousandVisits(pageBytes) {  const plans = (1000 * pageBytes) / plan.bytes;  return `$${(plans * plan.usd).toFixed(2)}, ${(plans * plan.incomeShare).toFixed(2)}% of a month's income`;}console.log(`Median mobile home page: ${thousandVisits(2418688)}`);console.log(`Ravi's full page: ${thousandVisits(346570)}`);console.log(`Ravi's lighter page: ${thousandVisits(15655)}`);
  • Line 2 is the plan: 5 GB, its median price in US dollars, and the median share of a month's income it takes.
  • Line 4 works out how many plans 1,000 visits use up.
  • Line 5 turns that into dollars, and into a share of a month's income.
  • Lines 7 to 9 try three pages. The first is the median mobile home page, which the Web Almanac measured at 2,362 KB.
  • Line 7 prints Median mobile home page: $2.84, 4.56% of a month's income.
  • Line 8 prints Ravi's full page: $0.41, 0.65% of a month's income.
  • Line 9 prints Ravi's lighter page: $0.02, 0.03% of a month's income.

One visit looks cheap. But Asha's month has to cover every page of every site she opens. Here is how far a 5 GB month goes:

Visits a day in a 5 GB monthPop out in the code editor (opens in a new tab)JavaScript
// How many visits a day fit in a 5 GB month?const planBytes = 5_000_000_000;const pages = {  "Median mobile home page": 2418688,  "Ravi's full page": 346570,  "Ravi's lighter page": 15655,};for (const [page, bytes] of Object.entries(pages)) {  console.log(`${page}: ${Math.floor(planBytes / bytes / 30)} visits a day`);}
  • Line 2 is the plan, in bytes.
  • Lines 3 to 7 are the three pages, in bytes.
  • Line 9 divides the plan by one visit, then by 30 days. It prints Median mobile home page: 68 visits a day, Ravi's full page: 480 visits a day and Ravi's lighter page: 10646 visits a day.
Bytes for a first visit, to scale, and how many such visits a day fit in a 5 GB month. Median mobile home page: 2,362 KB, 68 visits a day; Ravi's full page: 338 KB, 480 visits a day; Ravi's lighter page: 15 KB, 10,646 visits a day.Median mobile home page2,362 KB68 visits a dayRavi's full page338 KB480 visits a dayRavi's lighter page15 KB10,646 visits a day
Each bar is a first visit, to scale. After it: its size, and how many such visits a day a 5 GB month holds.

68 pages a day isn't much, for a month of news, shops and messages. Why it matters: page weight decides how much of the web a month of data buys. Measure it the way Asha pays for it: a first visit, with an empty cache. DevTools' Network panel shows the total at the bottom, as transferred. Move the slider to price your own page:

Playground: what 1,000 visits cost
1,000 visits
  1. Low-income countries$0.41, 0.65% of a month's income
  2. Lower-middle-income countries$0.44, 0.21% of a month's income
  3. Upper-middle-income countries$0.60, 0.09% of a month's income
  4. High-income countries$1.09, 0.03% of a month's income
Try it yourself
481 visits a day fit in a 5 GB month

Each row is 1,000 visits on the ITU's 5 GB monthly plan. It shows the median price in that group of countries, and the median share of a month's income per person.

Prices are the ITU's median for its 5 GB data-only plan in each income group. A KB here is 1,024 bytes, and 5 GB is 5,000,000,000 bytes.

Which fix for which problem?

Each problem below has one best first fix. Sort them:

Which fix for which problem?
  • A request for the reviews that never gets an answer
  • A spinner that has said Loading… for a minute
  • A server that misses some requests while it restarts
  • A thousand phones whose requests failed at the same second
  • Asha opens the shop in a tunnel
  • The tea list Asha checks every day on the train
  • A 153 KB video that plays by itself
  • A handwriting font for the headings
Try it yourself
0 of 8 correct

Sort each problem by the fix it needs first.

Choose a category for every card. You can change an answer at any time; Reset clears them all.

Common mix-ups

  • "DevTools' Packet Loss box makes a page load lose packets." No. It only reaches WebRTC calls. The recorded page loaded as fast as on plain Slow 4G.
  • "fetch() gives up by itself after a while." No. It has no time limit of its own. Asha's button still said Loading… after 30 seconds.
  • "If a request fails, try again at once." No. Wait first, longer each time, for a random part of the wait. Then phones that failed together don't all come back together.
  • "navigator.onLine is true, so the internet works." No. It only means some network is connected. Only false is certain.
  • "A service worker saves data on every visit." No. The HTTP cache already keeps files between visits. The worker even fetched sw.js again. What it adds is a shop that opens with no signal.
  • "Background Sync works in every browser." No. Only Chromium browsers have it. Elsewhere, send queued work on the online event.

Practice exercises

Answer first, then use the hints.

Exercise 1 · Warm-upThe ceiling after try 3

Ravi lets getJson try four times. What does this print for the wait after try 3?

Starter codePop out in the code editor (opens in a new tab)JavaScript
const attempt = 3;
const ceiling = 1000 * 2 ** (attempt - 1);
console.log(`After try ${attempt}: up to ${ceiling} ms`);

Answer, then press Check. Spacing and letter case don’t matter.

    Exercise 2 · Warm-upThe lighter page's chain

    On the network with long waits, what does this print for the lighter page?

    Starter codePop out in the code editor (opens in a new tab)JavaScript
    // The lighter page: the photo is in the HTML, so it's asked for as soon as the page arrives.
    const chain = ["the page", "photo-800.jpg"];
    const wait = 1200;
    console.log(`${chain.length} waits in a row: at least ${chain.length * wait} ms`);

    Answer, then press Check. Spacing and letter case don’t matter.

      Exercise 3 · PracticeRetries that never come

      This getJson never retries when the shop is silent. What is its fetch missing?

      Starter codePop out in the code editor (opens in a new tab)JavaScript
      async function getJson(url, tries = 3) {
        for (let attempt = 1; attempt <= tries; attempt++) {
          try {
            const response = await fetch(url);
            return await response.json();
          } catch (error) {
            if (attempt === tries) throw error;
            await sleep(Math.random() * 1000 * 2 ** (attempt - 1));
          }
        }
      }

      Answer, then press Check. Spacing and letter case don’t matter.

        Exercise 4 · PracticeRetries with no signal

        Open Ravi's page with getJson in Chrome. Load it, then switch DevTools to Offline and tap Show 50 reviews. What does the Network panel's Status column say for those requests?

        Answer, then press Check. Spacing and letter case don’t matter.

          Exercise 5 · ChallengeA 1,000 KB page

          A page downloads 1,000 KB. In low-income countries, what share of a month's income do 1,000 visits cost?

          Answer, then press Check. Spacing and letter case don’t matter.

            Exercise 6 · ChallengeThe wait before the second try

            When the shop was down, how long did the page wait before its second try, in ms?

            Answer, then press Check. Spacing and letter case don’t matter.

              Check your understanding

              For each question, ask yourself which problem it is: a slow answer, no answer, no signal, or too many bytes.

              The slow networks quiz · 7 questionsScore: first tries count
              1. Question 1 of 7Ravi sets DevTools' Packet Loss box to 10% and reloads his shop. What changes in the page load?

                Choose an answer to see the explanation.

              2. Question 2 of 7The shop never answers Asha's request for the reviews, and the page has no time limit. What does she see?

                Choose an answer to see the explanation.

              3. Question 3 of 7What does this wait loop print?

                Read the code, then predictPop out in the code editor (opens in a new tab)JavaScript
                const randoms = [0.5, 0.75];
                for (let attempt = 1; attempt <= 2; attempt++) {
                  const ceiling = 1000 * 2 ** (attempt - 1);
                  console.log(Math.round(randoms[attempt - 1] * ceiling));
                }

                Choose an answer to see the explanation.

              4. Question 4 of 7Why does Ravi pick a random part of each wait, not the whole wait?

                Choose an answer to see the explanation.

              5. Question 5 of 7navigator.onLine is true. What does Asha's page know for sure?

                Choose an answer to see the explanation.

              6. Question 6 of 7Ravi's worker asks the network first for the reviews, then falls back to its copy. Why does that fetch have a time limit too?

                Choose an answer to see the explanation.

              7. Question 7 of 7Which change saved Asha the most data on her first visit?

                Choose an answer to see the explanation.

              Key takeaways

              • DevTools copies long waits and no signal well. Its Packet Loss box only reaches WebRTC, so test real loss on a real phone.
              • Long waits hurt chains most. Every file asked for after another pays one more whole wait.
              • fetch() has no time limit. Give it one with AbortSignal.timeout(), and say what went wrong when it runs out.
              • Retry a few times, safe requests only, after a wait whose ceiling doubles and whose length is random.
              • A service worker can keep the shell and the last data, so the page opens with no signal. Give its network tries a time limit too.
              • Every byte costs Asha money. Price your page with the ITU's plans, and send less.

              Remember the one-liner.
              Plan for answers that come late, never, or not at all: a limit, a careful retry, a copy on the phone, and fewer bytes.

              Sources

              The facts on this page come from these specs, docs, data and source files:

              Coming next: Webviews, in-app browsers, and PWAs. How a page behaves inside other apps, and when it's installed on the phone.

              CompleteFrontend Clear concepts. Working examples.