Part 1 · Choosing a channel: polling, long polling, server-sent events and WebSockets
Four ways to hear about a change
A field health worker in a district records household surveys on a tablet, and a kabaddi league's page shows a score that changes every few seconds. Both screens need data that changes on the server without the user asking for it.
The browser starts every HTTP exchange, so a server cannot simply call a page. There are four common ways around that. Polling means the page asks again and again on a timer. Long polling means the page asks, and the server holds the request open until it has something to say or a time limit passes, after which the page asks again. Server-sent events, usually shortened to SSE, keep one HTTP response open and let the server write events into it as they happen. A WebSocket upgrades one HTTP request into a two-way connection that stays open and carries messages in both directions.
Polling
Long polling
SSE
WebSocket
Who starts a message
client
client
server
either side
Connection
a new request each time
one request held open, then a new one
one long response
one long-lived connection
Browser API
fetch
fetch
EventSource
WebSocket
Reconnects by itself
not needed
you write it
yes, built in
no, you write it
Data format
anything
anything
text events
text or binary
Who starts a message
Pollingclient
Long pollingclient
SSEserver
WebSocketeither side
Connection
Pollinga new request each time
Long pollingone request held open, then a new one
SSEone long response
WebSocketone long-lived connection
Browser API
Pollingfetch
Long pollingfetch
SSEEventSource
WebSocketWebSocket
Reconnects by itself
Pollingnot needed
Long pollingyou write it
SSEyes, built in
WebSocketno, you write it
Data format
Pollinganything
Long pollinganything
SSEtext events
WebSockettext or binary
The reconnection row of that table is tested by runs in the next two lessons. The point for now is the shape of the choice: the cheaper the channel is to build, the more work it makes the server do per update, and the richer the channel is, the more state you must manage yourself.
Polling and its overlap problem
Polling is the right first answer when updates are not urgent and the server can answer quickly. A health supervisor's dashboard that refreshes every 30 seconds needs nothing more. The common way to write it is setInterval, and it has a flaw that shows up when the server slows down.
setInterval fires on the clock. It does not wait for the previous request to finish. If the endpoint takes 2,500 ms to answer and the timer fires every 1,000 ms, new requests pile up behind the old ones. The test below uses fake timers and an endpoint that answers after 2,500 ms, and it counts how many requests are in flight at once.
setInterval every 1000 ms, answer takes 2500 ms, 10 s: 10 requests
started, up to 3 in flight at once
Output of a real run in jsdom with fake timers. First line. Long lines are wrapped for the page.
Ten requests started in ten seconds, and at one moment three were still waiting for an answer. On a slow day the server is already struggling, and this loop sends it more work, because the page cannot tell the difference between slow and gone. Requests can also finish out of order, so an old answer may overwrite a newer one.
Wait for the answer, then wait
The fix is to schedule the next request only after the previous one has finished. Use setTimeout instead of setInterval, and start the timer inside the code that handles the answer. The hook below also stops cleanly, and it backs off when requests fail: after each failure the wait doubles, up to eight times the base delay.
ts
exportfunction usePolling<T>(
fetcher: (signal: AbortSignal) => Promise<T>,
ms: number,
) {
const [data, setData] = useState<T | null>(null)
const load = useEffectEvent(fetcher)
useEffect(() => {
const ctl = new AbortController()
let timer: ReturnType<typeof setTimeout> | undefinedlet failures = 0asyncfunction tick() {
try {
setData(await load(ctl.signal))
failures = 0
} catch {
failures += 1
}
if (ctl.signal.aborted) return// wait for the answer, then wait; back off after failures
timer = setTimeout(tick, ms * 2 ** Math.min(failures, 3))
}
void tick()
return () => {
ctl.abort()
clearTimeout(timer)
}
}, [ms])
return data
}
The hook reads the latest fetcher through useEffectEvent, so a new function from the caller does not restart the loop. Only a change in ms does. The cleanup aborts the signal and clears the pending timer, so an unmounted component sends nothing more.
text
chained timeout, same endpoint, 10 s: 3 requests started at 0, 3500,
7000 ms, up to 1 in flight
after unmount, 10 s more: 0 new requests
first three answers fail: request starts at 0, 4500, 11000, 21500,
25000, 28500 ms
The rest of the same run. Long lines are wrapped for the page.
With the same slow endpoint, the chained version started three requests in ten seconds, one at a time. After unmount, no new request started in the next ten seconds. In the third run the first three answers failed. The gaps between starts were 4,500, 6,500 and 10,500 ms: the 2,500 ms the failed call took, plus a wait of 2,000, 4,000 and 8,000 ms that doubles with each failure. The fourth call succeeded, so the wait dropped back to 1,000 ms.
Pause when nobody is looking
A hidden tab does not need a fresh survey count every few seconds. The visibilitychange event on document and its document.hidden flag let a polling loop pause itself. Add that before reaching for a heavier channel.
Choosing between the four
Choose by what the screen needs, not by what is newest.
Updates every 30 seconds or slower, any number of users: polling. It is plain HTTP and works with caches, proxies and logs you already have.
Updates should arrive within a second or two but only flow server to client, such as a score, a progress bar or a notification count: server-sent events.
Messages flow both ways with low delay, such as chat, shared editing or a game: a WebSocket.
You are on infrastructure that cannot hold connections open: long polling is the fallback that works anywhere, at the cost of more requests.
A live kabaddi score is one-way, so SSE would do, and the lessons that follow still build a WebSocket store for it. The reason is that the same store shape, a connection held outside React and read through one subscription, also covers the harder cases. The advanced hooks chapter introduced the hook that reads such a store.
Whatever the channel, treat the connection as something that will drop. Phones switch networks, devices sleep and servers restart. A real-time feature is finished only when it has a plan for that, and the plan is what the rest of this chapter builds.
Check your understanding
In the run, how many requests were in flight at the same time with setInterval, and how many with the chained timeout?
Up to three with setInterval every 1,000 ms against a 2,500 ms endpoint, and one with the chained timeout.
Why does the hook read fetcher through useEffectEvent?
So that a new function from the caller does not restart the polling loop. Only a change in the delay restarts it.
A page shows a live score and never sends anything to the server. Which channel fits best, and why?
Server-sent events: the data flows one way, the browser reconnects by itself and it is plain HTTP. A WebSocket would also work but adds a protocol you do not need.
Part 2 · Server-sent events: EventSource and automatic reconnection
One response that never ends
Server-sent events turn an ordinary HTTP response into a stream. The server answers with the content type text/event-stream and keeps writing. The browser's EventSource object opens the request, parses the stream and calls your handlers for each event. It is one-way: data flows from the server to the page only.
The stream is plain text. Each event is a block of lines ended by a blank line. The data: line carries the payload, event: names the event type, id: sets the event's identifier, and retry: tells the browser how many milliseconds to wait before reconnecting. This is what the lab server sent when curl read it for under a second.
Output of a real run: the raw stream from the lab server, read with curl. Each event is a few lines and a blank line.
An event with no event: line is delivered to the message handler. A named event, like score here, is delivered only to a listener added with addEventListener for that name, which the MDN page on EventSource also notes.
The server side
The server needs no library. It writes the headers, then writes events on its own schedule. This lab server sends three score events 150 ms apart and then ends the response on purpose, to show what the browser does next.
js
function sse(req, res) {
const last = req.headers['last-event-id']
log(`SSE connect, Last-Event-ID: ${last ?? '(none)'}`)
res.writeHead(200, {
'content-type': 'text/event-stream',
'cache-control': 'no-cache',
connection: 'keep-alive',
})
res.write('retry: 300\n\n')
let id = last ? Number(last) : 0const stop = id + 3// three events per connectionconst t = setInterval(() => {
id += 1const data = JSON.stringify({ seq: id, home: id * 2, away: id })
res.write(`id: ${id}\nevent: score\ndata: ${data}\n\n`)
if (id >= stop) {
clearInterval(t)
log(`SSE ending the stream after id ${id}`)
res.end()
}
}, 150)
req.on('close', () => clearInterval(t))
}
last-event-id is an HTTP header the browser adds when it reconnects, once it has seen an id:. The server above reads it and carries on counting from there. A server that ignores it will start the stream again from the beginning, which is why the store in the next lesson also checks sequence numbers on the client.
The React side, and what the browser did
The component opens the connection in an effect and closes it in the cleanup. That is the whole contract: EventSource is an external system, so an effect is the right place for it. The HTML standard says that when the connection is lost the browser sets readyState to CONNECTING, fires error, waits the reconnection time and requests the stream again. MDN says close() is what ends the connection for good.
The test page was served from the lab server and driven by headless Chrome. The server ended each connection after three events. This is what the page logged, with the browser's own messages about a missing icon file removed.
Output of a real run in headless Chrome 157, page side, first 15 lines.
Each time the stream ended, the page saw error with readyState 0, which is CONNECTING, and then open again with the event ids carrying on from 4, 7 and 10. Nobody wrote reconnection code. The server's log shows why the numbers did not restart: the browser sent the last id back.
text
-- server log
server: listening 56110
server: SSE connect, Last-Event-ID: (none)
server: SSE ending the stream after id 3
server: SSE connect, Last-Event-ID: 3
server: SSE ending the stream after id 6
server: SSE connect, Last-Event-ID: 6
server: SSE ending the stream after id 9
server: SSE connect, Last-Event-ID: 9
The server side of the same run.
Limits to know before you choose it
One direction only. If the page must send messages, it sends them with ordinary requests, and that is often fine.
The EventSource constructor takes a URL and a withCredentials option, so you cannot set an Authorization header. Cookies, or a token in the query string, are the usual workarounds.
Without HTTP/2 a browser allows only 6 SSE connections per domain across all of its tabs. With HTTP/2 the limit is the number of concurrent streams the two sides agree on, 100 by default.
Reconnection is not unconditional. The HTML standard says a response with a status other than 200, or a content type other than text/event-stream, fails the connection and the browser does not retry. A server can answer 204 to tell the browser to stop reconnecting.
Text only. Binary data has to be encoded, for example as base64.
The connection limits come from MDN's EventSource page and the retry rules from the HTML standard's section on server-sent events. A health worker's supervisor opening ten tabs of the same dashboard without HTTP/2 is exactly the case that hits the limit of six, so a shared connection or HTTP/2 matters. The next lesson shows how to share one connection among many components.
Server-sent events need no library on the server, the browser reconnects by itself, and for a one-way feed they ask for less code than a WebSocket.
Check your understanding
What does the browser send when EventSource reconnects, and what did the server do with it?
It sends a Last-Event-ID header with the last id it saw. In the run the server read 3 and carried on from event 4.
What did the page log between two connections, and what does readyState 0 mean?
It logged error, readyState 0, then open, readyState 1. State 0 is CONNECTING, so the browser was already trying again.
Why can an EventSource not carry an Authorization header?
The constructor accepts only a URL and withCredentials, so there is no place to set request headers. Use cookies or a token in the URL.
Part 3 · A WebSocket store that survives dropped connections
One connection, many readers
A WebSocket is the right tool when both sides talk. For a live kabaddi score the page also tells the server which match it follows. The browser's WebSocket object never reconnects: once it closes it stays closed, and the store below creates a new one. Its API also has no way to apply backpressure, the ability of a receiver to tell a sender to slow down, as MDN states. A real feature adds what it needs itself.
The pattern is a small store outside React. It owns the one connection, keeps the latest state, and lets any number of components subscribe. React reads it with useSyncExternalStore, from the advanced hooks chapter. The store opens the socket when the first component subscribes and closes it when the last one leaves.
The snapshot is replaced as a whole when something changes, and never mutated, so getSnapshot returns the same object until the next change.
Reconnecting with backoff and jitter
When the connection closes, the store waits and tries again, with the exponential backoff and jitter from the data fetching chapter: the wait doubles after each failed attempt, and a random amount is added so that clients drift apart. Immediate retries from every client would hit a restarted server all at once. Here the delay is the base times two to the power of the attempt number, plus up to the jitter value.
The backoff counter is reset only when a real message arrives, not when the connection opens. A server that accepts the upgrade and then closes at once would otherwise keep the delay at its smallest value forever.
In the next test the store has a base delay of 1,000 ms and a jitter of up to 250 ms. A seeded function supplies the random numbers; the timers are real. The server drops the connection and then closes the next two attempts at once with the code 1013, which means try again later.
The run
text
7 ms open
215 ms page: open: 2-1 (seq 1)
216 ms server drops the connection, refuses the next two
220 ms closed, retry 1 in 1078 ms
1318 ms open
1320 ms closed, retry 2 in 2155 ms
3486 ms open
3487 ms closed, retry 3 in 4043 ms
7544 ms open
7557 ms page: open: 4-1 (seq 2)
server saw subscribe messages: {"type":"subscribe","match":12}
{"type":"subscribe","match":12}
Output of a real run in jsdom against a real `ws` server. Times are from the start of the test. Long lines are wrapped for the page.
After the drop, the store waited 1,078 ms, then 2,155 ms, then 4,043 ms. Those are 1,000, 2,000 and 4,000 plus 78, 155 and 43 of jitter. The first two attempts connected and were closed again by the server, so the backoff was not reset. The third attempt connected and received a message, and the page showed seq 2. The server received subscribe again from the connection that stayed open, which is how the store restates which match it follows.
The store gives up after a fixed number of retries. Another test ran a server that always refuses.
text
open
closed, retry 1 in 50 ms
open
closed, retry 2 in 100 ms
open
closed, retry 3 in 200 ms
open
giving up
page shows: gave-up: no score yet (connections made: 4)
A second test: a server that always refuses. The base delay was 50 ms here, not 1,000 ms.
The delays doubled, and after the third retry the store reached gave-up.
Duplicate and out-of-order messages
A score message carries a sequence number, seq, and the store applies a message only if its number is higher than the last one it applied. A network can deliver a message twice, or after a newer one. The test sends the numbers 1, 2, 2, 4 and 3, in that order, to two components sharing one store.
ts
ws.onmessage = (e) => {
let msg: Score
try {
msg = JSON.parse(String(e.data))
} catch {
return log('ignored a message that is not JSON')
}
if (!Number.isInteger(msg?.seq))
return log('ignored a message with no seq')
if (msg.seq <= lastSeq)
return log(`ignored seq ${msg.seq} (already at ${lastSeq})`)
if (msg.seq > lastSeq + 1)
log(`gap: expected ${lastSeq + 1}, got ${msg.seq}`)
lastSeq = msg.seq
set({ status: 'open', score: msg, attempt: 0 })
}
text
messages sent by the server in this order: seq 1, 2, 2, 4, 3
store: open
store: ignored seq 2 (already at 2)
store: gap: expected 3, got 4
store: ignored seq 3 (already at 4)
page shows: open: 8-3 (seq 4)
server connections for two components: 1
server received:
Output of a real run in jsdom against a real `ws` server.
The duplicate seq 2 was ignored. seq 4 was applied with a note about the gap, and the late seq 3 was ignored, so the page ended on seq 4. The last output line is empty because the store sent nothing to the server in this probe. This works because each score message is a full snapshot of the match. If a message were only a change, a missing one would corrupt the total, and the store would have to ask for a fresh snapshot after a gap.
Two components subscribed to the store, and the server saw one connection. Under StrictMode, React's development check, a component subscribes, unsubscribes and subscribes again, and the server still saw one connection, because the first socket was closed before it finished connecting. Closing a socket that is still connecting raises an error event in this test environment, so the store has an onerror handler.
text
one component under StrictMode: server saw 1 connection(s), 1 still open
The StrictMode test of the same file.
A server can also send something that is not a score. A handler that calls JSON.parse with no guard throws on not json at all, and the probe saw an uncaught SyntaxError in Node. A message such as {"hello":1} has no seq and would be applied as if it had one. The handler above parses inside a try and requires an integer seq.
text
server sends four messages: not json at all | {"hello":1} | null |
{"seq":1,"home":2,"away":1}
store without the checks: uncaught SyntaxError, status connecting, no
score
store with the checks: status open, score seq 1
log: open | ignored a message that is not JSON | ignored a message
with no seq | ignored a message with no seq
A probe in Node against a real `ws` server, before and after the guards. Long lines are wrapped for the page.
What the connection does not do for you
send always accepts the data and queues it, and nothing tells the sender to wait. The probe below runs in Node, whose WebSocket follows the same API, so the figure is Node's and a browser may differ. It sends 2,000 messages of 64 KiB without waiting.
text
sent 2000 messages of 64 KiB without waiting; bufferedAmount right after
the loop: 125 MiB
Output of a real run in Node 24. First line. Long lines are wrapped for the page.
bufferedAmount is the number of bytes queued and not yet sent, and here it held 125 MiB straight after the loop. A page that sends faster than the network drains would grow its memory the same way. MDN names WebSocketStream as the alternative that applies backpressure. With the plain API the defences are to send less often, to merge updates, and to drop an update when a newer one supersedes it.
Animated sceneA dropped score socket0:19
Watch for the wait growing between attempts
Read it as steps
The store waits longer after each refusal and recovers on the third retry
The reset on a real message makes the next drop start from a short wait again.
The states, as a machine
Drawn as a machine, the refused retries show as a loop on reconnecting, and there is no way out of gave-up except a new store.
Animated sceneConnection states0:16
Watch for the loop on Reconnecting before the store is open again
Read it as steps
A drop, two refused retries, recovery, then a second drop that exhausts the retries
A component reads status from the snapshot and chooses what to show: the score, a quiet notice while reconnecting, or a retry button.
Check your understanding
What delays did the run show after the drop, and why were they not exactly 1,000, 2,000 and 4,000 ms?
1,078, 2,155 and 4,043 ms. The base delay doubled each time and the jitter, a random amount up to 250 ms, was added on top.
Why does the store reset its attempt counter on a message and not on open?
In the run the server accepted two connections and closed them at once. Resetting on open would have kept the wait at its smallest value, so it waits for a real message.
What happened to the messages with seq 2 (the second copy) and seq 3 in the out-of-order test?
Both were ignored because their numbers were not higher than the last one applied, and the page ended on seq 4.
Part 4 · Web Workers: moving heavy work off the main thread
Why the main thread matters
A page runs its scripts, handles clicks and paints on one thread, the main thread. While a long calculation holds it, taps are not handled and updates are not drawn. A health department's survey screen that totals 30 lakh household records on the main thread freezes for as long as the sum takes.
A Web Worker is a second thread that runs a script of its own. It has no access to the DOM. The page and the worker talk by messages: worker.postMessage(data) on one side and an onmessage handler on the other. Data in a message is copied, not shared, by an algorithm called structured clone, except for a few objects that can be moved. MDN documents all of this on its page on using web workers.
A worker suits work that takes more than a few tens of milliseconds and needs only data you can send it: parsing a large file, filtering or grouping many records, image processing, hashing. It does not suit work that touches the DOM, or tiny jobs where the cost of sending data outweighs the saving.
The analysis and the worker
The survey analysis groups 30 lakh records by district and finds the median income per district. It works on one flat Float64Array of district and income pairs, which becomes important in a moment.
ts
exportfunction analyse(rows: Float64Array) {
const byDistrict = new Map<number, number[]>()
for (let i = 0; i < rows.length; i += 2) {
const list = byDistrict.get(rows[i])
if (list) list.push(rows[i + 1])
else byDistrict.set(rows[i], [rows[i + 1]])
}
return [...byDistrict].map(([district, xs]) => {
const sorted = Float64Array.from(xs).sort()
return {
district,
n: xs.length,
median: sorted[Math.floor(sorted.length / 2)],
}
})
}
The worker file is three lines. It receives the array, runs the same function and posts the answer back.
The page creates it with new Worker(new URL('./analysis.worker.ts', import.meta.url), { type: 'module' }), a form that Vite recognises and bundles. MDN shows the new URL(..., import.meta.url) form for bundlers.
Measuring the difference in a real browser
A timer that ticks every 10 ms runs on the main thread, and the measurement records the longest gap between two ticks. A gap far above 10 ms means the thread was busy and the page could not respond. Each variant ran five times per run, in four runs, in headless Chrome 157 on this machine. The block shows the last run.
text
main thread, 3000000 rows, five runs (took ms / longest timer gap ms):
390/396377/385401/401368/368335/335
worker thread, 3000000 rows, five runs (took ms / longest timer gap ms):
358/11371/11362/11410/12433/11
Output of the last of four real runs. Each pair is the time the analysis took in ms, then the longest timer gap in ms. Long lines are wrapped for the page.
Across all four runs the analysis took 335 to 427 ms on the main thread, and the longest gap was the same or a few milliseconds more, so the page was frozen for the whole calculation. In the worker the analysis took 358 to 467 ms, but the longest gap was 11 or 12 ms every time. The work was not faster. The page stayed responsive while it ran. These numbers vary from run to run and from machine to machine.
The worker call above transferred the array. That detail decides whether the worker helps at all.
What structured clone costs
Posting a message serialises the data on the sending thread. The sender pays for that before the worker starts. The probe posted 4,00,000 small objects, then the same amount of data as a Float64Array whose buffer was transferred.
text
postMessage of 400,000 objects: 79 ms; of the same count of numbers as a
transferred Float64Array: 0 ms
The first line of the same run. The other runs gave 76, 82 and 97 ms for the objects. Long lines are wrapped for the page.
Posting the objects blocked the main thread for 76 to 97 ms across the four runs, and posting the transferred array took under a millisecond each time. A transferable object, such as an ArrayBuffer, is moved to the other thread instead of copied. The sender can no longer use it. MDN describes this as a zero-copy operation. When you design a worker, shape the data as flat typed arrays so that the hand-over is cheap.
text
Date came back as Date, Map as Map
posting a function: DataCloneError
after transferring 8 MB, the sender's byteLength is 0
The last three lines of the same run: what survives cloning.
A Date and a Map arrived as a Date and a Map, so cloning handles more than JSON does. A function cannot be cloned: posting one threw a DataCloneError in the sender. And after the 8 MB buffer was transferred, its length in the sender was 0.
Using a worker from React
A worker is an external resource, so a component or a hook creates it in an effect and calls terminate() in the cleanup. Create one worker per feature and reuse it, not one per message. A message can carry an id so that the replies of overlapping jobs can be matched to their requests, as in the data fetching chapter's request race.
Create the worker in useEffect and terminate it in the cleanup.
Show a pending state while a job runs. The answer arrives in onmessage, which calls a state setter.
Terminate the worker, or ignore the reply, when a newer job makes the old one obsolete.
Transfer large buffers, and copy small messages.
A worker cannot update the page itself. It sends a message, and the page makes the change, which keeps all rendering in React's hands.
Check your understanding
In the run, did the worker make the analysis faster?
No. It took about the same time, 358 to 467 ms against 335 to 427 ms on the main thread. What changed was the longest timer gap, which fell from the length of the whole calculation to 11 or 12 ms, so the page stayed responsive.
Why did posting 4,00,000 objects block the page when posting the typed array did not?
Posting objects serialises them by structured clone on the sending thread, which took 76 to 97 ms in the runs. Transferring the buffer moves it without copying.
What happened when the probe posted a function?
It threw a DataCloneError, because functions cannot be cloned.
Part 5 · Online and offline: queueing writes and replaying them safely
What offline means to a survey app
A field health worker often has no signal at a household. The app should still let her save a survey, and send it later. That asks for three things: knowing that the network is gone, keeping the writes, and sending them again when it returns without creating duplicates.
navigator.onLine reports whether the browser thinks it has a network connection, and the online and offline events fire when that changes. The advanced hooks chapter used it for a badge. MDN calls the property inherently unreliable: a connection to a local network counts as online even when it has no internet. The page advises giving hints and not disabling features because of it.
So the queue below does not trust the flag. It tries to send, and a failed request tells it the truth. The online event is used only as a good moment to try again.
A queue that sends in order
The hook keeps the pending surveys in a ref, since the queue is not something to render, and a count in state for the screen. Each survey gets an idempotency key when it is created. The flush loop sends the first item and removes it only after the server accepts it. A network failure or a server error stops the loop and keeps the item, and a 4xx answer means the server will never accept that survey, so it is dropped with a log line instead of blocking every item behind it.
The key is sent in an Idempotency-Key header. A request is idempotent when sending it twice has the same effect as sending it once. A POST is not idempotent on its own, so the server stores the key with the record and ignores a repeat. The lab server does exactly that.
Offline, then online, in a real browser
Chrome can be told to behave as if the network is gone, and Playwright exposes that as context.setOffline(true). It is an emulation, not a cable pulled out, and the runs below say so. The test saved three households while offline and then switched the network back on. The three flush stopped lines are the failed attempts made while it was offline.
text
A. browser offline (emulated), three saves
navigator.onLine: false
waiting: 3 waiting
after going online, waiting: 0 waiting
page: flush stopped at H-101: Failed to fetch
page: flush stopped at H-101: Failed to fetch
page: flush stopped at H-101: Failed to fetch
Output of a real run in headless Chrome 157, network emulated offline. The page side.
text
-- server log A
server: listening 56110
server: POST survey H-101 key=4205eb9a-9b64-4630-a6c0-d8757a4156c0
stored
server: POST survey H-102 key=b61f5e8a-5c35-4d6d-bdc6-76acd0a7ca6d
stored
server: POST survey H-103 key=e9a95d8f-52ac-4417-939e-2abedf065cde
stored
The server log of the same run. Long lines are wrapped for the page.
While offline, navigator.onLine was false and the three surveys waited. When the emulated network came back, the online event fired, the queue emptied, and the server stored the three households in the order they were saved, H-101, H-102, H-103.
When the flag lies, and when the response is lost
The second run keeps the network on and takes the server down. The browser still reports onLine as true, because a connection exists, but every request fails with a 503. A queue built on the flag would think it had succeeded. The queue here saw the failure and kept the survey.
Then the server is brought back and told to save H-102 and break the connection in the middle of its answer. The page cannot know whether the survey was saved. It saw a failed request, so the survey stayed in the queue, and the next flush sent it again with the same key.
text
B. online, but the server is down, then a lost response
navigator.onLine: true, waiting: 1 waiting
after the connection dropped on H-102, waiting: 1 waiting
after a second flush, waiting: 0 waiting
page: flush stopped at H-101: HTTP 503
page: flush stopped at H-102: Failed to fetch
-- server log B
server: POST survey H-101 key=f013ace7-7689-4b6e-985d-d9bee39fb302
stored
server: POST survey H-102 key=3799e81f-ecc2-4158-9164-ffadb34810f7
stored
server: dropping the response for H-102
server: POST survey H-102 key=3799e81f-ecc2-4158-9164-ffadb34810f7
DUPLICATE ignored
records stored on the server: H-101, H-102
The second run in the same file, headless Chrome 157. Long lines are wrapped for the page.
The server stored H-102 on the first attempt and logged the second as a duplicate and ignored it. The records on the server are two, H-101 and H-102, with no repeat. Without the key, a lost answer would have turned into a double entry, which is the usual bug in offline queues.
A rejected survey must not block the line, and memory is not storage
The third case sends a survey with zero household members, which the server answers with a 422. The queue logged it as rejected for good, removed it, and sent the next survey.
text
C. a survey the server rejects, then a good one
page: H-201 rejected for good: HTTP 422
waiting: 0 waiting
D. reload while the server is down
before reload, waiting: 1 waiting
after reload, waiting: 0 waiting
The third and fourth runs of the same file.
A queue that retried a 422 forever would hold every later survey behind it. In a real app the rejected survey would go to a list that the worker can see and correct.
The fourth run exposes the weakness of this version. A survey was waiting, the page was reloaded, and the count came back as zero. The queue lived in a useRef, and a reload, a closed tab or a crashed browser empties memory, so the survey was lost. For field work that is unacceptable, and the last lesson of this chapter stores the queue on the device. Before that, the next lesson makes the page itself load when the network is gone.
Check your understanding
When the server was down and the browser still online, what did navigator.onLine report and what did the queue do?
It reported true. The queue saw the 503, kept the survey and tried again later, because it relies on failed requests and not on the flag.
What stopped H-102 from being stored twice after its response was lost?
Its idempotency key. The second request carried the same key and the server logged it as a duplicate and ignored it.
What did the reload in the last run show about an in-memory queue?
The count went from 1 waiting to 0 waiting. A queue held in memory does not survive a reload, so the survey was lost.
Part 6 · Service workers and the Cache API: a page that loads offline
A script between the page and the network
Queued surveys help only if the app opens. A worker who opens the tablet without signal sees a browser error, and the offline queue never starts. A service worker fixes that. It is a script the browser runs in the background, registered for an origin, that can intercept every request the page makes and answer from a cache.
Three browser features cooperate. The service worker receives fetch events for requests from pages it controls. The Cache API, caches, stores Request and Response pairs under names you choose. And the install and activate events let the worker prepare a cache and clean up old ones. Service workers need a secure context, which means HTTPS, and MDN notes that localhost counts as secure, so everything here runs on localhost.
The lifecycle
A new worker goes through three steps. The install event fires once, right after registration, and is where a worker usually fills a cache. A new version that installs while an old one is still controlling open pages waits. The activate event fires when the old version is gone, and is where old caches are deleted. A page that was open when the worker first activated is not controlled by it until it is reloaded, because a document starts life with or without a service worker and keeps that for its lifetime. MDN's page on using service workers describes the same sequence, and the run below shows it.
The lab worker keeps a cache named for its version. It stores /api/clinics.json, the list of clinics, on install, and it deletes every cache but its own on activate.
A strategy is the rule a worker follows for a request. Cache first looks in the cache and goes to the network only on a miss. It is quick and works offline, and it can serve old data for as long as the cache lives. Nothing in the Cache API expires an entry, as MDN notes, so the worker must delete old ones. Network first tries the network and falls back to the cache when the network fails, so the data is fresh when online and still available when not. The lab worker uses cache first for the clinic list and the bundled assets, and network first for page navigations.
js
asyncfunction cacheFirst(request) {
const hit = await caches.match(request)
if (hit) return hit
const res = await fetch(request)
if (res.ok) (await caches.open(CACHE)).put(request, res.clone())
return res
}
js
asyncfunction networkFirst(request) {
try {
const res = await fetch(request)
if (res.ok) (await caches.open(CACHE)).put(request, res.clone())
return res
} catch {
const hit = await caches.match(request, { ignoreSearch: true })
return hit ?? new Response('offline', { status: 503 })
}
}
A response body can be read only once, so the worker stores res.clone() and returns the original. The clone goes into the cache and the original goes to the page.
Offline, in a real browser
The run loads the page, reloads it so the worker controls it, switches the emulated network off and reloads again. It then changes the clinic list on the server and shows what cache first does with a fresh answer.
text
first load, controlled: false
worker: v1 install
worker: v1 activate
after reload, controlled: true
page shows: clinics v1
offline reload, page shows: clinics v1
server now serves clinics v2; online reload with the cache-first worker
page shows: clinics v1
deploy worker v2, reload while the old page is open
Output of a real run in headless Chrome 157, network emulated offline. First nine lines.
The first load was not controlled, since the worker had only just installed. After a reload it was controlled. With the network off the page still loaded and still showed clinics v1, from the cache. Then the server changed its list to v2, and an online reload still showed v1. That is cache first doing its job and its harm at once.
Updating the worker without stale data
The fix for stale data is a new version of the worker. The run changes the worker file on the server, asks the browser to check for an update, and prints the registration while the old tab is still open.
text
deploy worker v2, reload while the old page is open
worker: v2 install
registration: active true, waiting true, installing false
cache names: survey-v1, survey-v2
worker: v2 activate
in a fresh tab, registration: active true, waiting false
cache names: survey-v2
page shows: clinics v2
cache names after it: survey-v2
The rest of the same run.
The new worker installed and then waited, and the log shows v2 install but no v2 activate. The registration had an active worker and a waiting one, and both caches existed. The old page kept its old worker. Only after the old tab was closed and a new tab was opened did v2 activate appear, with the old cache deleted. The next load showed clinics v2.
A worker can call skipWaiting() to activate at once, and clients.claim() to take control of open pages. Both can change the rules under a page that is half way through a form, so most apps tell the user that an update is ready and let them choose.
Cache first and API data
Do not cache first any data that changes and that people act on, such as stock, prices or appointment slots. The lab uses it for a clinic list that changes rarely, and the run shows the price of that choice.
Check your understanding
Why was the first page load in the run not controlled by the service worker?
The worker installed and activated after the page had started. A document is controlled only if the worker was in place when it loaded, so a reload was needed.
The server changed the clinic list to v2, and an online reload still showed v1. Why?
The worker answers /api/clinics.json cache first, so it kept returning the stored copy and never asked the network.
What did the registration look like after the new worker version installed while the old tab was open?
It had an active worker and a waiting one. The new worker activated only after the old tab was closed and a new tab opened.
Part 7 · Storing data on the device: IndexedDB, drafts and BroadcastChannel
Why memory and localStorage are not enough
The previous lessons ended with a queue that vanished on reload. The browser has a database for this, IndexedDB: a transactional store of JavaScript objects, kept on the device, that survives reloads and restarts and is available in workers too. MDN describes it as designed for large amounts of data for offline use. It stores structured objects, and its API is asynchronous. The cost is an old, event-based API that is easiest to use behind a small wrapper.
This lesson stores the survey outbox and a draft of the household form (a copy of its values saved on the device as the person types), and uses BroadcastChannel to tell other open tabs when they change.
A small wrapper
An IndexedDB database has a name and a version number. The upgradeneeded event is the only place where object stores can be created, and it fires when the database is new or the requested version is higher than the stored one. An object store holds records under a key. If another tab still holds the database open when a newer version is requested, the upgrade waits, as the last page of this lesson shows. The outbox store below uses a keyPath of seq with autoIncrement, so that the database assigns increasing numbers.
Writes happen inside a transaction, which succeeds or fails as a whole. The helper below wraps one in a promise that resolves on the complete event, and the transaction is complete only after the data is committed.
The outbox now keeps its items in IndexedDB. The seq key keeps them in insertion order, and the flush loop reads them in that order and deletes each one after the server accepts it. A BroadcastChannel named survey lets one tab say that the outbox changed, so another open tab can refresh its count.
asyncfunction flush() {
const db = await dbp
const rows = await getAll<Row>(db, 'outbox')
for (const row of rows) {
try {
await sendSurvey(row.key, row)
} catch (err) {
if (!(err instanceof PermanentError))
return`stopped at ${row.household}: ${(err as Error).message}`
}
await remove(db, 'outbox', row.seq!)
}
channel.postMessage({ type: 'outbox-changed' })
return'flushed'
}
BroadcastChannel lets pages, workers and frames of the same origin send each other messages. Anything that structured clone accepts can be sent, and close() releases the channel. MDN does not say whether the sender hears its own message. The run answers it for this case: it does not.
The run: reload, two tabs and a draft
Two tabs of the app were opened in one browser context. The server was down, and three surveys were queued in the first tab.
text
A. durable outbox, server down
flush: stopped at H-101: HTTP 503
outbox in tab 1: 1:H-101, 2:H-102, 3:H-103
outbox in tab 2: 1:H-101, 2:H-102, 3:H-103
messages tab 2 got: {"type":"outbox-changed"} {"type":"outbox-changed"}
{"type":"outbox-changed"}
messages tab 1 got: []
after reloading tab 1: 1:H-101, 2:H-102, 3:H-103
flush: flushed
Output of a real run in headless Chrome 157, two tabs in one context. First eight lines. Long lines are wrapped for the page.
The flush stopped at H-101 with a 503, and all three surveys stayed in the outbox, numbered 1 to 3. The second tab saw the same three, because both tabs read the same database, and it received three outbox-changed messages on the channel. The first tab, which sent them, received none of its own. After it was reloaded, nothing had been lost. When the server came back, the flush sent them and the outbox was empty. The server log records the arrivals in the order they were saved.
text
-- server log
server: listening 56110
server: POST survey H-101 key=e4a426a9-1a13-4fa7-9264-5efb532011e8
stored
server: POST survey H-102 key=54a3ab68-49e2-4e33-b1c1-4157ec63916b
stored
server: POST survey H-103 key=05fac187-2013-4125-8420-9d6aa851e112
stored
B. draft
tab 2 messages: {"type":"draft","text":"H-110, 6 members, half filled"}
tab 2 reads draft: H-110, 6 members, half filled
The server log and the draft test. Long lines are wrapped for the page.
A draft of the form was saved in the first tab, a draft message reached the second, and the second tab read the same text back from the database. Autosaving a draft as the worker types protects her from a dead battery in the same way the outbox protects a finished survey.
Two mistakes the run provokes
The first mistake is ordering. A key made from a random id sorts by that id, and not by arrival. The probe inserted three records with keys ending in f3, a9 and c1.
text
C. pitfalls
inserted f3, a9, c1; getAll gives a9, c1, f3
write after an await fetch inside a transaction:
TransactionInactiveError
The pitfalls, same run. Long lines are wrapped for the page.
The records came back as a9, c1, f3, sorted by key, not in the order inserted. That is why the outbox uses an auto-incremented seq. The second mistake is waiting for something else in the middle of a transaction. A transaction stays active only while requests on it are pending, and returning to the event loop for anything else lets it become inactive. After an await fetch, a put on the same transaction threw TransactionInactiveError. Fetch first, then open the transaction and write.
Animated sceneThe outbox keeps order0:17
Watch for the outbox surviving a reload
Read it as steps
Surveys saved with the server down are sent in the order they were saved
The server stays the source of truth, and the device holds what has not yet been sent.
When the database says no
Two failures are worth provoking before they happen in the field. The first is a blocked upgrade. When a page asks for a higher version while another tab still holds the database open, the request fires blocked and waits until the other connection closes. The holder can listen for versionchange and close its connection, as MDN's guide recommends. The openDb wrapper above has neither handler, so an upgrade would hang with no message.
The second is storage running out. MDN says that storing more than the origin's quota in IndexedDB, Cache or the origin private file system fails with QuotaExceededError, and that storage is best-effort by default, so the browser may delete it under pressure. The probe set a one megabyte quota for the origin through the Chrome DevTools Protocol, and wrote five megabytes. The transaction aborted, and the finish helper above turns that into a rejected promise, so the outbox can tell the person that the survey was not saved.
text
tab 2 asks for version 2 while tab 1 holds version 1 and ignores
versionchange:
blocked after 1 ms, still waiting after 1500 ms
tab 1 closes its connection on versionchange: tab 2 open of version 2
succeeds
5 MB write with the origin quota set to 1 MB: tx.onabort:
QuotaExceededError
Output of a real run in headless Chrome 157. The quota was set by the script and is an emulation. Long lines are wrapped for the page.
Treat the copy on the device as temporary. navigator.storage.persist() asks the browser to keep the data, and browsers decide whether to grant it.
Check your understanding
Why does the outbox use an auto-incremented seq key and not a random id?
Records come back sorted by key. The probe inserted f3, a9 and c1 and got a9, c1, f3 back, so a random key would lose the order of saving.
What error did a write after await fetch inside a transaction produce?
TransactionInactiveError. The transaction became inactive when control returned to the event loop for something other than a request on that transaction.
After the first tab was reloaded with the server still down, what was in the outbox?
The same three surveys, numbered 1 to 3, because IndexedDB keeps them across a reload.