How-To Guide

How to Implement Prefetching Strategies

Prefetch before the user asks: predict the next request, warm the cache and connections, and avoid wasted work for predictions that miss.

On this page

  1. Introduction
  2. Choose a signal the predicts the next request
  3. Prefetch into a reusable cache
  4. Cap the spend so misses are cheap
  5. Measure the hit rate
  6. Test the hit rate and the safety
  7. Common pitfalls
  8. Conclusion

Introduction

A user experience has predictable moments: hovering a link before clicking it, an element entering the viewport, a sequence of pages people usually visit in order. Prefetching uses those moments to fetch what the user is about to need, so the data is ready when they ask. Done with a good predictor and a cheap fetch, it removes a wait the user would otherwise feel. Done with a bad predictor or an expensive fetch, it wastes bandwidth and competes with the resource the user actually needs.

This tutorial covers choosing a prefetch signal, fetching into a reusable cache, capping the spend so misses are cheap, and measuring the hit rate to keep prefetching only where it works. The examples use HTTP prefetch hints and an application prefetch into a cache.

Choose a signal the predicts the next request

A prefetch is worth it when the next request is likely, so the signal matters more than the fetch. Hovering a link, with a small delay so a passing cursor does not trigger it, predicts a click. An element entering the viewport predicts that mousing oved or scrolled to it will be used. A known navigation path, such as step two after step one, predicts the next page. Choose the signal with the highest precision for your users.

Avoid prefetching on signals that fire for everyone or for nothing. Prefetching every link on a page as soon as it loads spends bandwidth on links most users will not click. Gate the prefetch on an intent signal, such as a hover of a few hundred milliseconds, so the set of prefetches is small and the hit rate is high.

// prefetch on a hover with a small delay, not on page load
const prefetched = new Set();
function onHover(link, href) {
  const timer = setTimeout(() => {
    if (prefetched.has(href)) return;
    prefetched.add(href);
    fetch(href, { priority: 'low' });   // low priority: it must not block the page
  }, 150);
  link.addEventListener('mouseleave', () => clearTimeout(timer), { once: true });
}

Prefetch into a reusable cache

A prefetch should land somewhere the real request will reuse, not in a one-off response. If the application fetches JSON into a client cache, prefetch into that cache so the later navigation is a cache hit. If the browser fetches a document, use a resource hint such as rel=prefetch or a preload, so the browser stores it and reuses it on navigation.

For a document prefetch, mark it low priority so it does not delay the critical path. For an application cache, key the prefetched value the same way the live request does, so the hit is automatic. A prefetch that lands in a different cache, or under a different key, is wasted work even if the prediction was correct.

class QueryCache {
  private map = new Map<string, unknown>();
  async prefetch(key: string, url: string) {
    if (this.map.has(key)) return;
    const value = await fetch(url).then((r) => r.json());
    this.map.set(key, value);     // same key the live query uses -> a real hit
  }
  get(key: string) { return this.map.get(key); }
}

Cap the spend so misses are cheap

Every prefetch is a bet, and a miss is wasted bytes and possibly wasted server work. Cap the number of concurrent prefetches, the total bytes, and the priority so a wrong prediction cannot crowd out what the user needs. Low priority is essential: a prefetch competing with the render-critical resource makes the page slower, the opposite of the intent.

Do not prefetch expensive or side-effecting requests. A prefetch should be a safe read that is cheap enough to discard. Never prefetch a POST, an action, or anything that changes state, because a prefetch that happens to run is a side effect the user did not ask for. Restrict prefetching to idempotent reads, and let the real action happen on the real interaction.

Measure the hit rate

A prefetch is only worth it if it is used. Track how often a prefetched resource is later requested within its usefulness window, and set a threshold below which the prefetch is disabled. A hit rate that is high justifies the bandwidth and the server load; a hit rate that is low means the spend is waste, and the signal or the target should change.

Measure the cost too: the bytes prefetched per navigation, and the wasted bytes from misses. A prefetch that saves a hundred milliseconds but transfers a megabyte the user does not need is not a net win on a metered connection. Tune the signal and the target on the data, and remove the prefetch where the numbers do not support it.

metrics.incr('prefetch.attempt');
onNavigation((url) => {
  if (prefetched.has(url)) metrics.incr('prefetch.hit');   // used within the window
  else metrics.incr('prefetch.miss');
});
// alert if hit / (hit + miss) drops below the threshold that justified prefetching

Test the hit rate and the safety

Test that a prefetched key is served from the cache on the real navigation, proving the prefetch lands where the live request reads. Test that the prefetch is low priority and capped, so it cannot crowd out a critical resource. Test that no side-effecting request is ever prefetched, by asserting the prefetch list contains only idempotent reads. Test the hit rate in an integration test where a hover is followed by a click.

# hover then click: the click should be a cache hit, not a fresh network fetch
curl -s -o /dev/null -H 'Purpose: prefetch' http://localhost:3000/page/2   # the prefetch
curl -sD - -o /dev/null http://localhost:3000/page/2 | grep -i 'x-cache'    # HIT

Common pitfalls

Prefetching every link on load so most is wasted, a prefetch landing in a different cache or under a different key so it never hits, a prefetch at high priority that delays the critical path, prefetching an expensive or side-effecting request, and no hit-rate measurement so a wasteful prefetch stays are the recurring mistakes. An intent signal, a shared cache key, low priority and caps, idempotent reads only, and a hit-rate metric address them.

Conclusion

Prefetching removes a wait when the next request is predictable and the fetch is cheap. Choose an intent signal with high precision, fetch into the cache the live request reads, keep the prefetch low priority and capped, restrict it to idempotent reads, and measure the hit rate. Self-check by asserting a hover-then-click is a cache hit and that the hit rate stays above the threshold. Then prefetching is a real gain, not a guess that spends bandwidth.

Sources: MDN: rel=prefetch and resource hints, web.dev: Prefetch, preload, and preconnect, MDN: Resource hints.

FAQ

When does prefetching help?
When the next request is predictable and the fetch is cheap relative to the delay it removes. Hovering a link, entering the viewport of an element, or a common navigation path are good signals. Random clicks or expensive fetches make prefetching wasteful.
Does prefetching waste bandwidth?
It does for predictions that miss. Cap the prefetch by size and count, prefetch only assets the user is likely to need, and measure the hit rate so you can disable it where it is wrong. A prefetch that is used most of the time is a benefit; one that rarely is becomes waste.

Related Examples