This article is a part of the series "Optimising frontend applications"
Two caching strategies
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:
- 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.
- The response body does not need to be streamed again.
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.
Questions? Comments? Criticisms? Get in the comments! 👇
Spotted an error? Edit this page with Github