HTTP caching basics

It’s important to understand HTTP caching because at some point an HTTP cache will protect your web platform from going down. Whether this HTTP cache is a reverse caching proxy like Varnish or a full-blown CDN, you need to understand the rules of the game, and you need to understand the basics of HTTP caching.

Luckily there are conventions for this. There are even standardized headers that are part of HTTP’s specification that will allow you to control the behavior of a web cache.

What is HTTP caching?#

HTTP has caching capabilities built into the protocol to ensure that clients or proxies can store the HTTP response in the cache for a certain amount of time. By caching the response, clients don’t have to connect to the web server every time they want to access that content.

HTTP caching reduces network traffic and server load, which results in lower response times.

Browser cache versus caching proxies#

Historically HTTP responses were cached by the web browser to reduce network traffic. In the early days of the web, bandwidth was limited. Being able to cache HTTP responses in the browser avoided expensive HTTP roundtrips.

Unfortunately browser cache is not reliable: users can flush the cache at any time, and they can even disable the cache. Another disadvantage is the fact that the cache is hosted locally, which means there is a cache per user.

By installing proxy servers closer to the user, either in the office or at the internet provider’s data center, clients can retrieve centrally cached copies of the requested content and act on behalf of the origin web server.

As broadband internet became more common, local caching proxy servers were no longer crucial. Instead the increase of bandwidth shifted the pressure from the client to the server: traffic spikes started jeopardizing the stability of servers. As a consequence, caching proxies also shifted.

Nowadays reverse caching proxies are put in front of the origin web platform to protect it against traffic spikes and prevent the platform from caving in under pressure.

HTTP’s caching policies allow HTTP responses to be cached by both clients and proxies using the same syntax. However, there are also specific instructions that only apply to proxies.

HTTP caching concepts#

Cacheability#

Not all HTTP responses can or should be cached: if the content is private, it should not be stored in the cache. If the type of request (for example an HTTP POST request) implies a change of the resource, it shouldn’t be cached either. If the returned response uses a Set-Cookie header to change state, the response shouldn’t be cached.

On the one hand you can decide whether or not to store a response in the cache. On the other hand, you can decide whether or not to serve a cached response from the cache.

These rules can be specifically enforced in the implementation or configuration of the cache. However, the HTTP protocol allows you to control the cacheability under the form of specific header syntax.

The Cache-Control: no-cache, no-store header is the perfect example of enforcing cacheability. The no-cache part instructs the cache not to serve any cached responses for this resource and instead fetch the corresponding content from the origin web server. The no-store part prevents the HTTP response from being stored in the cache.

Public versus private content#

The scope of cacheable content is either public or private.

  • Publicly cacheable content can be cached by both the requesting client as well as reverse caching proxies.
  • Privately cacheable content can only be cached by the requesting client and not by reverse caching proxies.

The Cache-Control: public and Cache-Control: private response headers are used to set the caching scope.

Cache lifetime#

Cached objects are only valid for a limited amount of time. The time to live of a cached object can be defined in the implementation or configuration of the cache. But as expected, the HTTP protocol has ways to enforce the time to live through specific cache header syntax.

The Cache-Control: max-age=3600 header is an example of setting the lifetime of cached object to an hour. The HTTP protocol has more directives to set the time to live and these will be covered in the HTTP caching headers section of the tutorial.

Revalidation#

As long as the time to live of a cached object has not expired, the content is considered fresh. This means it can be served from the cache to requesting clients.

The remaining lifetime of an object is a value that changes every second. Once it hits zero, the content is no longer fresh. Instead it is considered stale and in need of revalidation.

Cache revalidation is the process of connecting back to the origin web server and fetching potentially updated content. As soon as the revalidation is finished, the object is considered fresh again for as long as the time to live allows.

Caches are also allowed to serve stale content while revalidation takes place. This is discussed in the cache revalidation part of the HTTP caching flow section.

Conditional revalidation#

Revalidation can also be done conditionally. This means that the origin web server will only send the payload if the requested resource has changed. If the resource hasn’t changed, a 304 Not Modified status code will be returned without a response body.

This reduces the amount of data sent over the wire, and it can also result in a lower server resource consumption at the origin level.

When the cache receives an 304 Not Modified response, the time to live that is defined by the Cache-Control or Expires header will be used to set the lifetime of the object after revalidation.

HTTP response headers like Etag and Last-Modified allow web servers to identify when a resource has last changed. These values can be presented by the client or a reverse caching proxy under the form of If-None-Match and If-Modified-Since request headers to compare versions. If these versions differ, a regular 200 OK response will be sent, otherwise the 304 Not Modified status is returned.

The conditional revalidation part of the HTTP caching flow section describes this in more detail, whereas headers like Etag, Last-Modified, If-None-Match and If-Modified-Since are covered in the HTTP caching headers section of this tutorial.

Identifiying cached objects#

Objects in the cache are generally identified by their URI and Host header values. These values are part of the HTTP request, as illustrated below:

GET /about HTTP/1.1
Host: example.com

This example is a request to http://example.com/about and /about and example.com are used to create a hash that identifies the object in the cache.

Cache variations#

Sometimes, an HTTP resource can have multiple versions that depend on values coming from request headers. One example of this is a multilingual website that uses the Accept-Language response header to present the resource in multiple languages.

If a resource has multiple versions, knowing that it is identified by its URI , the cached output can be inconsistent. Only using the URI and Host header will not suffice and that’s where cache variations come into play.

A cache varation will extend the hash that is used to identify an object in the cache by adding the value of a request header. Per version of the resource, a variation is added to the cache.

The origin web server can issue a Vary header to tell the cache what request header it should use to base its variations on. In the case of the multilingual website, Vary: Accept-Language is the logical choice.

The goal is to store enough cache variations to cover the available versions of a resource. But if a resource has too many variations, caching all variations will have a detrimental effect on the hit rate and will fill up the cache.

Make sure you have your variations under control, otherwise you’re better off not caching the response at all.

HTTP caching headers#

Here’s an overview of HTTP caching headers that you can leverage to control the cache from your origin web platform.

Cache-Control#

The Cache-Control header is probably the most common HTTP caching header. Its syntax is quite extensive and has directives to control the following aspects of HTTP caching:

  • Time To Live
  • Cacheability
  • Scope (public or private)
  • Revalidation

Public and private#

The public keyword is used to announce that the resource can be cached by both web clients and caching proxies. If private is used instead, a caching proxy will not store the object in cache whereas a web client will.

Here’s an example where a public resource is announced through the Cache-Control header:

Cache-Control: public

Here’s the equivalent for private content :

Cache-Control: private

Max-age and s-maxage#

The max-age directive is used to set the lifetime of an object in the cache. Here’s an example:

Cache-Control: public, max-age=3600

This header instructs the cache to store the object for 3600 seconds , which corresponds to an hour.

The s-maxage directive does the same as max-age, but it is intended for caching proxies rather than for web clients.

Here’s an example where a caching proxy is instructed to cache the object for a day:

Cache-Control: public, s-maxage=86400

It is also possible to combine these directives:

Cache-Control: public, max-age=3600, s-maxage=86400

This will result in the web client caching the resource for an hour and the caching proxy applying a time to live of a day.

Stale-while-revalidate#

The stale-while-revalidate directive sets the allowed staleness of a cached object, allowing expired content that has passed its expiration time to be served from the cache.

The stale-while-revalidate value sets the amount of seconds past the expiration time that stale content can be served while the cache is revalidating the content.

Here’s an example:

Cache-Control: public, max-age=900, stale-while-revalidate=100

In this example the cached object is considered fresh for 900 seconds. After that revalidation needs to take place. But because of the stale-while-revalidate=100 directive, the object can be served from the cache for another 100 seconds while the cache is asynchronously revalidating with the origin web server.