Caching

To avoid generating the same data with every request, there is a technique called caching that is used to store the data either on the client's or the server's side. This cached data may be used for further reference whenever it is required.

When using caching, it is important that you manage it properly. The reason for this is simple. We are storing data that won't be replaced by fresh data from the server. While this is an advantage that increases the performance of the service, at the same time, if we are not careful as to what to cache and configure during its lifetime, we might end up seeing outdated data. For example, suppose we are showing the live price of gold on our website and we cached this figure. The next time the price changes, it won't be reflected unless we expire the cache that was previously stored.

Let's look at the different kinds of HTTP headers and how to configure caches:

Header

Application

Date

Date and time of the generation of the representation.

Last modified

Date and time when this representation was last modified by the server.

Cache-control

The HTTP 1.1 header used to control caching. We will look at this in more detail after this table.

Expires

This header helps to tag an expiration date and time for this representation.

Age

Denotes the time in seconds since the representation was fetched from the server.

 

The configuration of the preceding five headers depends upon the nature of the service. Take the example of the service that provides the live price of gold—ideally, it would have the cache age limit as low as possible, or even have caching turned off, because users should see the latest results every time they refer to the site.

However, a site that contains many images would hardly change or update them. In that case, the cache can be configured to store them for a longer duration.

These header values are consulted in accordance with the cache-control header to check whether the cached results are still valid or not.

The following are the most common values for the cache-control header:

Directive

Application

Public

This is the default directive. This allows every component to cache the representation.

Private

Only the client or server can cache the representation. However, intermediary components are restricted.

no-cache/no-store

With this value, we can turn off caching.

max-age

This value is the time in seconds after the date and time is mentioned in the Date header, which denotes the validity of the representation.

s-maxage

This does the same as max-age, but only targets intermediary caching.

must-revalidate

This states that the representation must be revalidated if the max-age has passed.

proxy-validate

This does the same as max-revalidate, but only targets intermediary caching.