Skip to main content

Advantages and disadvantages of using different or consistent expiration logic in the service worker cache and HTTP cache layers.

It appears in:
Network reliability

While service workers and PWAs are becoming the standard for modern web applications, resource caching has become more complex than ever. This article covers the overview of browser caching, including:

  • The use cases and differences between service worker caching and HTTP caching.
  • Advantages and disadvantages of different service worker caching expiration strategies compared to typical HTTP caching strategies

Caching flow overview

At a high level, a browser follows the following caching order when requesting a resource:

  1. Service worker cache: The service worker checks if the resource is in its cache and decides whether to return the resource itself based on its scheduled caching strategies. Please note that this does not happen automatically. You must create a recovery event handler on your service worker and intercept network requests so that requests are served from the service worker cache instead of the network.
  2. HTTP cache (also known as browser cache): If the resource is in the HTTP cache and has not yet expired, the browser automatically uses the resource from the HTTP cache.
  3. Server side: If nothing is found in the service worker's cache or the HTTP cache, the browser goes to the network to request the resource. If the resource is not cached on a CDN, the request must go back to the origin server.

caching-flow-2211747

Note that some browsers like Chrome have a Cache layer in front of the service worker cache. The details of the cache depend on the implementation of each browser. Unfortunately, there is still no clear specification for this part.

Caching layers

Service worker caching

A service worker intercepts network type HTTP requests and uses a
caching strategy
to determine what resources should be returned to the browser. The service worker cache and the HTTP cache serve the same general purpose, but the service worker cache offers more caching capabilities, such as granular control over exactly what is cached and how caching is done. cache.

Control the service worker cache

A service worker intercepts HTTP requests with event listeners (generally the fetch event). This
code snippet demonstrates the logic of a
Cache first
caching strategy.

workbox-4152333

It is highly recommended to use Workbox to avoid reinventing the wheel. For example, you can
register resource url paths with a single line of regex code.

import { registerRoute } from 'workbox-routing' ;

registerRoute ( new RegExp ( 'styles /.*. css' ) , callbackHandler ) ;

Caching Strategies and Service Worker Use Cases

The following table describes common service worker caching strategies and when each strategy is useful.

Strategies Justification of freshness Use cases
Network only The content has to be updated at all times.
  • Payments and payments
  • Balance statements
Network resorting to cache It is preferable to serve the fresh content. However, if the network is down or unstable, it is acceptable to offer slightly old content.
  • Timely data
  • Prices and fees (requires disclaimer)
  • Order statuses
Passed while being revalidated It's okay to post cached content right away, but updated cached content should be used in the future.
  • News
  • Product listing pages
  • Messages
Cache first, go to the net The content is not critical and can be served from cache to improve performance, but the service worker should occasionally check for updates.
  • Application shell
  • Common resources
Cache only The content rarely changes.

Additional benefits of service worker caching

In addition to granular control of caching logic, service worker caching also provides:

  • More memory and storage space for your source: The browser allocates HTTP cache resources by origin. In other words, if you have multiple subdomains, they all share the same HTTP cache. There is no guarantee that content from your origin / domain will stay in the HTTP cache for a long time. For example, a user can purge the cache by manually clearing from a browser's configuration user interface or by triggering a full reload on a page. With a service worker cache, you have a much higher chance that your cached content will remain cached. Watch Persistent storage Learn more.
  • Greater flexibility with unstable networks or offline experiences: With HTTP cache you only have one binary option: the resource is cached or not. With service worker caching, you can mitigate small "hiccups" much more easily (with the "deprecated while revalidating" strategy), provide a full offline experience (with the "Cache Only" strategy), or even something. intermediate, such as custom UIs with parts of the page coming from the service worker cache and some parts excluded (using the "Set Capture Handler" strategy) where applicable.

HTTP caching

The first time a browser loads a web page and related resources, it stores these resources in its HTTP cache. The HTTP cache is generally automatically enabled by browsers, unless the end user has explicitly disabled it.

Using HTTP caching means relying on the server to determine when to cache a resource and for how long.

When a server responds to a browser request for a resource, the server uses HTTP response headers to tell the browser how long to cache the resource. See Response headers: configure your web server for more information.

HTTP caching strategies and use cases

HTTP caching is much simpler than service worker caching, because HTTP caching only deals with time-based resource expiration (TTL) logic. See What response header values should I use? and Summary for more information on HTTP caching strategies.

Designing your cache expiration logic

This section explains the pros and cons of using consistent expiration logic in the service worker cache and HTTP cache layers, as well as the pros and cons of separate expiration logic in these layers.

The following error demonstrates how service worker caching and HTTP caching work in action in different scenarios:

Consistent expiration logic for all cache layers

To demonstrate the pros and cons, we will look at 3 scenarios: long-term, medium-term, and short-term.

Scenarios Long-term caching Medium-term caching Short-term caching
Service worker caching strategy Cache, turning to the network Passed while being revalidated Network resorting to cache
Service worker cache TTL 30 days 1 day 10 minutes
HTTP cache maximum age 30 days 1 day 10 minutes

Scenario: long-term caching (cache, go to the network)

  • When a cached resource is valid (<= 30 días): el trabajador del servicio devuelve el recurso almacenado en caché inmediatamente sin ir a la red.
  • When a cached resource expires (> 30 days): The service worker goes to the network to find the resource. The browser does not have a copy of the resource in its HTTP cache, so it passes to the server side for the resource.

Con: In this scenario, HTTP caching provides less value because the browser will always pass the request to the server side when the cache expires on the service worker.

Scenario: medium-term caching (stale while revalidating)

  • When a cached resource is valid (<= 1 día): el trabajador del servicio devuelve el recurso en caché inmediatamente y va a la red para buscar el recurso. El navegador tiene una copia del recurso en su caché HTTP, por lo que devuelve esa copia al trabajador del servicio.
  • When a cached resource expires (> 1 day): The service worker returns the cached resource immediately and goes to the network to find the resource. The browser does not have a copy of the resource in its HTTP cache, so it goes server-side to find the resource.

Disadvantage: The service worker requires additional cache clearing to override the HTTP cache in order to take full advantage of the "revalidation" step.

Scenario: short-term caching (network uses cache)

  • When a cached resource is valid (<= 10 minutos): el trabajador del servicio va a la red para buscar el recurso. El navegador tiene una copia del recurso en su caché HTTP, por lo que se lo devuelve al trabajador del servicio sin pasar al lado del servidor.
  • When a cached resource expires (> 10 minutes): The service worker returns the cached resource immediately and goes to the network to find the resource. The browser does not have a copy of the resource in its HTTP cache, so it goes server-side to find the resource.

Disadvantage: Similar to the medium-term caching scenario, the service worker requires additional cache clearing logic to override the HTTP cache in order to get the last resort from the server side.

Service worker in all scenarios

In all scenarios, the service worker cache can still return cached resources when the network is unstable. On the other hand, the HTTP cache is unreliable when the network is unstable or down.

Different cache expiration logic in service worker cache and HTTP layers

To demonstrate the pros and cons, we will take another look at the long, medium, and short-term scenarios.

Scenarios Long-term caching Medium-term caching Short-term caching
Service worker caching strategy Cache, turning to the network Passed while being revalidated Network resorting to cache
Service worker cache TTL 90 days 30 days 1 day
HTTP cache maximum age 30 days 1 day 10 minutes

Scenario: long-term caching (cache, go to the network)

  • When a cached resource is valid in the service worker cache (<= 90 días): el trabajador del servicio devuelve el recurso almacenado en caché inmediatamente.
  • When a cached resource expires in the service worker cache (> 90 days): The service worker goes to the network to find the resource. The browser does not have a copy of the resource in its HTTP cache, so it passes to the server side.

Pros and cons:

  • Advantage: Users experience an instant response as the service worker returns cached resources immediately.
  • Advantage: The service worker has more granular control of when to use their cache and when to request new versions of resources.
  • Disadvantage: A well-defined service worker caching strategy is required.

Scenario: medium-term caching (stale while revalidating)

  • When a cached resource is valid in the service worker cache (<= 30 días): el trabajador del servicio devuelve el recurso almacenado en caché inmediatamente.
  • When a cached resource expires in the service worker cache (> 30 days): The service worker goes to the network for the resource. The browser does not have a copy of the resource in its HTTP cache, so it passes to the server side.

Pros and cons:

  • Advantage: Users experience an instant response as the service worker returns cached resources immediately.
  • Advantage: The service worker can make sure that following The request for a given URL uses a new response from the network, thanks to the revalidation that occurs "in the background".
  • Disadvantage: A well-defined service worker caching strategy is required.

Scenario: short-term caching (network resorting to caching)

  • When a cached resource is valid in the service worker cache (<= 1 día): el trabajador del servicio va a la red en busca del recurso. El navegador devuelve el recurso de la caché HTTP si está allí. Si la red no funciona, el trabajador del servicio devuelve el recurso de la caché del trabajador del servicio.
  • When a cached resource expires in the service worker cache (> 1 day): The service worker goes to the network to find the resource. The browser retrieves resources over the network when the version cached in its HTTP cache has expired.

Pros and cons:

  • Advantage: When the network is unstable or down, the service worker returns the cached resources immediately.
  • Disadvantage: The service worker requires additional cache clearing to override the HTTP cache and make "Network First" requests.

conclusion

Given the complexity of combining caching scenarios, it is not possible to design one rule that covers all cases. However, based on the results of the previous sections, there are a few tips to keep in mind when designing your caching strategies:

  • The service worker caching logic does not need to be consistent with the HTTP caching expiration logic. If possible, use longer expiration logic on the service worker to give the service worker more control.
  • HTTP caching still plays a role, but it is unreliable when the network is unstable or down.
  • Review your caching strategies for each resource to ensure that your service worker caching strategy provides its value, without conflicting with the HTTP cache.

Learn more

error: Attention: Protected content.