Course contentsShow
← Web Development
Lesson 2393 of 2,98243. Service Workers Deep DiveFree lesson

Race Strategy Pattern

Racing cache and network requests simultaneously, using whichever responds first for optimal performance.

Race Strategy Pattern

What you'll learn: How to race your service worker cache against the network and deliver whichever response arrives first for maximum speed.

The Core Idea

The Race Strategy Pattern fires off both a cache lookup and a network request simultaneously, then uses whichever one responds first. Think of it like sending two delivery drivers to fetch your pizza—whoever arrives at your door first wins, and you don't wait for the slower one.

This pattern is ideal for resources where:

  • Speed is critical
  • You have a cached version but want fresh data if the network is fast
  • Network performance is unpredictable

How It Works

In your service worker's fetch event handler, you initiate both caches.match() and fetch() at the same time. Using Promise.race(), you take the first settled promise and return that response to the page.

self.addEventListener('fetch', event => {
  event.respondWith(
    Promise.race([
      caches.match(event.request),
      fetch(event.request)
    ]).then(response => {
      // First one to respond wins
      return response || fetch(event.request);
    }).catch(() => {
      // Fallback if both fail
      return caches.match('/offline.html');
    })
  );
});

When to Use

This strategy works well for assets like avatars, thumbnails, or API responses where slightly stale data is acceptable but fresh data is preferable when available quickly. The cache provides instant gratification while the network can still win if it's speedy.

Key Takeaway: The Race Strategy Pattern maximizes perceived performance by competing cache and network simultaneously, delivering the fastest response regardless of source.