Cache (HTTP)

Page content

What is the Cache

Cache is temporarily stored data. This is a general concept, and I think this is why many developers struggle with it a lot.

Because Cache is temporary data, we should think where and how long to store the data.

Where are the data stored

There are several locations where we can save cache data. The most common place is the browser in a client. Not only client sides but also server sides (origin servers) can hold a cache. Other examples are CDN, load-balancers, etc….

Purposes

There are several purposes for using Cache.

  • A browser in a client: If the data user-requested are in a browser cache, the user doesn’t need to fetch the data through the internet.
  • CDN: Because CDN has data which user requests, servers (in origin) don’t need to respond to the client. It decreases loads and traffics of the server.
  • Load-balancers: Reduce requests to the origin servers.
  • CPU cache: Reduce the average cost.

Basically, Cache reduce requests to

  • access rapidly, and
  • reduce the load of origins.

How to control HTTP cache

Cache is just temporary data, so it can be stored in any storage. In RAM, SSD, HDD, and so on. In this post, I call Cache in means of “HTTP cache”.

HTTP Cache controll commands

HTTP Headers Cache-Control can control HTTP cache. Both requests and responses can contain these headers.

Mozilla developer documents: https://developer.mozilla.org/de/docs/Web/HTTP/Headers/Cache-Control

Requests

Cache-Control: max-age=<seconds>
Cache-Control: max-stale[=<seconds>]
Cache-Control: min-fresh=<seconds>
Cache-Control: no-cache 
Cache-Control: no-store
Cache-Control: no-transform
Cache-Control: only-if-cached

Responses

Cache-Control: must-revalidate
Cache-Control: no-cache
Cache-Control: no-store
Cache-Control: no-transform
Cache-Control: public
Cache-Control: private
Cache-Control: proxy-revalidate
Cache-Control: max-age=<seconds>
Cache-Control: s-maxage=<seconds>

Nginx cache parameters