v140 · service worker routing

Racing them

A path routed with race-network-and-fetch-handler, where the network side is a deliberately slow stream and the worker side answers after a delay you choose. Sweep the delay and find the point where the winner changes — because the answer is a property of your application, not of the API.

Run the race

Every race run
# network delay handler delay headers at complete at winner
Nothing raced yet.
Press a button.

The winner is read from a response header, not inferred from the timing. A response carrying x-served-by: fetch-handler came from the worker; one without it came from the network. Guessing from the duration would be circular — the duration is what is being explained.

Where the winner changes

Run the sweep to fill this in.

Racing is not free advice. It doubles the requests for every path it applies to — the network side runs whether or not it wins — so it is a good trade where the worker might be slow and a bad one where the worker is reliably fast and the network is metered. And the thing being raced is time-to-first-byte on both sides, which on localhost is a millisecond and on a mobile network is not.

What this maps onto

The worker side here waits a chosen number of milliseconds. In a real application that delay is the sum of things you do not control precisely: starting the worker if it is asleep, evaluating its script, running whatever else is queued on it, and only then your handler's own work. The point of sweeping the delay is that you can find your own crossover by measuring, rather than choosing a source from intuition.

The browser-side auto-preload mode makes the same trade without asking, for requests where it judges the worker unlikely to be needed. The router is the same decision made explicitly, per URL pattern, by someone who knows what the worker does.

see also