This blog is part of our Rails 5 series.
Rails 5 allows
cache HTTP responses forever
Sometimes, we have static pages that never/rarely change.
Let’s see log for the above action.
There is no change in the response and still we are rendering same thing again and again and again.
Rails 5 introduces http_cache_forever
When response does not change then we want browsers and proxies to cache it for a long time.
allows us to set response headers
to tell browsers and proxies that
response has not modified.
Now let’s look at the log for the modified code.
On first hit, we serve the request normally but, then on each subsequent request cache is revalidated and a “304 Not Modified” response is sent to the browser.
Options with http_cache_forever
By default, HTTP responses are cached only on the
user’s web browser.
To allow proxies to cache the response,
we can set public to
true to indicate that they can serve the cached response.
Use http_cache_forever with caution
By using this method,
Cache-Control: max-age=3155760000 is set as response header
and browser/proxy won’t revalidate the resource
back to the server unless force reload is done.
In case force reload is done,
Cache-Control: max-age=0 is set as request header.
In this case, browser will receive the changed resource whether ETag is changed or not.
http_cache_forever is literally going to set the headers to cache it for 100 years
and developers would have to take extra steps to revalidate it.
So, this should be used with extra care.