Black Sheep Code
rss_feed

Two caching strategies

Published:

There are two general approaches to caching.

Approach 1 - Require server revalidation

In this approach the cache will will store the data, but go back to the server for revalidation. If the data is still valid, then the server will either return fresh data, or respond with a 304 header, indicating that the stored data can be used.

A common mechanism for checking if the data is still valid, is the use of Etag headers. When the server first responds with the data, an ETag header is attached. The client, when re-requesting the data will attach the Etag as request header (browsers do this automatically), and the server can compare the Etag with a local in memory store to check if it's the most recent Etag for that resource.

This approach has two optimisations over no cache at all:

  1. The server typically does not need to go all the way to database to return data/check for its freshness. Some kind of local store can be used.
  2. The response body does not need to be streamed again.

☝️ Interactive demo

data: (not set)
  1. Open dev tools to network tab, make sure 'disable cache' is off.
  2. Click 'Click Me!' and see you get a 200 response with some random data.
    • if you have already done the exercise, then you can click 'Force Fresh Response' for a new 200 response.
    • Note the `Cache-Control` response header.
    • Note the `ETag` response header.
  3. Click 'Click Me!' again, and note that you get a 304.
    • Note the `If-None-Match` request header

Approach 2 - Trust the data you have

In this approach, the cache will use the data it already has, without requiring server validation.

A common scenario where this strategy is appropriate is for static resources like bundled and minified javascript files.

When the file is created, the tooling will usually include a hash of the file content as part of the file name. Eg. index.js becomes index-ac23a1.js. Because the hash is a deterministic result of the content, we can safely assume that if the file name hasn't changed, then neither has the content.

In this scenario we can use the immutable cache directive.

☝️ Interactive demo

data: (not set)
  1. Open dev tools to network tab, make sure 'disable cache' is off.
  2. Click 'Click Me!' and see you get a 200 response with some random data.
    • If you have already done the exercise, then you can click 'Force Fresh Response' for a new 200 response.
    • Note the `Cache-Control: public, max-age=604800, immutable` response header.
    • Note no `ETag` header
  3. Click 'Click Me!' again, and note that you get a greyed-out 200 (disk cache) response.


Questions? Comments? Criticisms? Get in the comments! 👇

Spotted an error? Edit this page with Github