HTTP Caching
HTTP caching helps reduce the burden on your server. If you use caching properly, your server load could be reduced by 30–40%. It depends on the scenario, though; it could be more or less.
Let me share what I implemented in one of my projects.
My infrastructure
First, my infrastructure looks like this:
- A single VPS.
- Kubernetes running on that VPS.
- Ingress Nginx.
- Node.js application.
- MongoDB.
- Cloudflare as a proxy.
Initially, without caching, every user request came to my server through Cloudflare.
For each request, my server had to perform I/O operations. If the page was dynamic, Node.js generated the page and returned it. If the requested resource was static, the web server directly returned it.
Notice that for every request reaching my server, resources were consumed to process the request and return the response. This increased CPU consumption, server bandwidth usage, and response time.
1. Implementing caching for static assets using Cloudflare
The first thing I did was implement a cache rule inside Cloudflare, but only for static assets.
For example, I created a cache rule for /assets/* with a TTL of one hour.
Now, whenever a request comes for an asset file, Cloudflare doesn't need to call my server if the requested resource is already available in its cache. It simply serves the cached resource.
But note that creating a cache rule is not always enough. You should also configure the appropriate HTTP Cache-Control headers on your origin server because Cloudflare can respect the origin's caching instructions, depending on your cache configuration.
I used:
Cache-Control: public, max-age=8600, immutableNow, everything was working very well for static assets.
2. The problem with dynamic HTML pages
But there was still one issue.
What about dynamic pages?
Eventually, a dynamic page is also HTML, but its content is generated dynamically. I wasn't caching those pages yet.
So, what I did was create a second cache rule inside Cloudflare for dynamic HTML pages.
I used:
Cache-Control: public, max-age=300Why did I use a shorter TTL here?
Because dynamic pages could change within a shorter duration. That's why I decided to use a TTL of only five minutes.
But you all know Cloudflare does some stuff according to how you configure it.
What happened was that Cloudflare modified or removed my ETag under certain circumstances.
Now, one more issue occurred.
My VPS was getting less burden, but whenever a user reloaded the page, the browser could still download the HTML again, even though it might already have the same content in its cache.
There were two issues:
- If the page data changed within those five minutes, Cloudflare could still serve the older version because its cached response was fresh, not stale.
- The browser could download the HTML again instead of reusing its existing cached representation.
3. Understanding ETag and no-transform
So, what I did was add one more directive in my Nginx configuration:
Cache-Control: public, max-age=300, no-transformBasically, no-transform tells intermediaries not to transform the response body.
I added this while troubleshooting the ETag issue because intermediary transformations can affect ETag handling.
Now, let's understand how ETag helps.
If the ETag reaches the browser, the browser can use it when revalidating a cached response.
For example, the server initially returns:
HTTP/2 200 OK
ETag: "sfdksfk234324"
Cache-Control: public, max-age=300Now, when the browser needs to revalidate the response, it sends a special request header:
If-None-Match: "sfdksfk234324"Notice that If-None-Match is a separate HTTP request header, not a Cache-Control directive.
The browser sends this request to Cloudflare.
Cloudflare receives it and checks its cache. If Cloudflare needs to revalidate its cached response, it can forward a conditional request to my origin.
My server checks whether the representation has changed.
If it hasn't changed, the server returns:
HTTP/2 304 Not ModifiedThe browser can reuse its existing response body instead of downloading the HTML again.
If the content has changed, the server returns a new 200 OK response with the updated representation.
But remember, Cloudflare can also handle browser revalidation using its own fresh cache. Every browser revalidation doesn't necessarily mean a request will reach my VPS.
Now, the second issue was resolved, but the first issue still existed.
If the page data changed within those five minutes, Cloudflare could still serve the older version because the cached response was fresh.
4. Understanding proxy-revalidate
Now, if you can tolerate that eventual consistency, it's good. You don't need to do anything else; just stay with your TTL.
But if you cannot tolerate serving stale content after the origin data changes, you need another approach.
I found another HTTP directive called proxy-revalidate.
I added:
Cache-Control: public, max-age=300, proxy-revalidateBasically, proxy-revalidate is built for shared caches.
It tells shared caches that once their cached response becomes stale, they must revalidate it with the origin before using it again.
But note one important thing: proxy-revalidate does not force revalidation while the response is still fresh.
For example:
- At 10:00, Cloudflare caches the HTML.
- At 10:02, the page data changes.
- At 10:03, Cloudflare can still serve its fresh cached HTML.
- At 10:05, the cached response becomes stale.
- Now Cloudflare must revalidate with the origin before using that stale response.
So, this directive helps prevent shared caches from serving stale responses after their freshness lifetime expires.
If you want a cache to revalidate before every reuse, even while the response is fresh, you should use no-cache instead.
5. Implementing Nginx caching
Now, there was another thing I hadn't implemented yet.
I hadn't configured caching inside my Nginx.
So, I used this configuration:
proxy_cache_path /var/cache/nginx
levels=1:2
keys_zone=cache_path:100m
max_size=2g
inactive=60m
use_temp_path=off;
location /blog {
proxy_cache cache_path;
proxy_cache_valid 200 60m;
proxy_pass http://node-app;
}Let's understand this.
First, proxy_cache_path defines the physical path where Nginx stores cached responses.
It also defines a shared-memory cache zone called cache_path.
For example:
keys_zone=cache_path:100mHere, cache_path is the name of the cache zone, and 100m is the shared-memory size.
Second:
proxy_cache cache_path;This tells Nginx to use the previously defined cache zone.
And:
proxy_cache_valid 200 60m;Here, 200 is the HTTP status code, and 60m means 60 minutes.
Now, what happens?
Nginx caches the eligible responses for requests handled by the location where I configured caching.
For example, if I declare /blog, requests such as:
- /blog
- /blog/1
- /blog/anything
can match this location, depending on the location matching rules.
One important thing: proxy_cache_valid does not override every upstream caching instruction. Nginx also considers headers such as Cache-Control, Expires, and X-Accel-Expires.
6. Understanding the complete caching flow
Now, let's understand what happens when a user requests a dynamic page.
Let's say the user requests:
https://imprakash.dev/blog/1The request flow looks like this:
- The browser sends the request to Cloudflare.
- Cloudflare receives the request.
- If Cloudflare has a usable cached response, it can serve it directly.
- Otherwise, Cloudflare sends the request to my VPS.
- Ingress Nginx receives the request and forwards it to Node.js.
- Node.js generates the dynamic HTML page and returns it.
- Nginx receives the response and stores an eligible response in its cache.
- Cloudflare receives the response and stores it according to its caching rules.
- Finally, Cloudflare returns the response to the browser.
Now, the browser can also store the response according to its HTTP caching policy.
So, we have three caching layers:
- Browser cache.
- Cloudflare cache.
- Nginx cache.
Now, what happens when the user reloads the page?
If the browser's cached response is fresh, it can reuse it without making a network request.
If the browser needs to revalidate its cached response, it sends a request with a special header called:
If-None-Match: "sfdksfk234324"Cloudflare receives the request and checks its own cache.
If Cloudflare needs to revalidate with the origin, it sends a conditional request to Nginx.
Now, Nginx checks its cache.
If the Nginx cached response is still fresh, Nginx can serve it without calling Node.js.
If its cached response has expired and proxy_cache_revalidate on is configured, Nginx can revalidate it with the upstream server using ETag or Last-Modified validators, when available.
If the response hasn't changed, Nginx can receive a 304 Not Modified response.
Cloudflare can then update its cache metadata and respond to the browser appropriately.
Notice that a 304 Not Modified response doesn't contain the original HTML body. The existing cached body is reused.
This way, we can reduce unnecessary data transfers and avoid repeatedly generating the same HTML.
7. One more issue: Cache invalidation
Now, there is still one issue.
Let's say an administrator updates a blog post.
Its data is stored in MongoDB.
Now, even though MongoDB contains the latest data, Nginx might still have the older HTML in its cache.
And even if Cloudflare revalidates its cache, Nginx might return its own cached HTML instead of requesting fresh content from Node.js.
So, Cloudflare revalidation doesn't automatically invalidate Nginx's cache.
Here, you have two options.
Option 1: Accept eventual consistency
If you can tolerate serving older content for a certain duration, just use TTL-based caching.
Option 2: Cache purging
If you want updated content to become available immediately, you should implement cache invalidation.
For example:
- Administrator updates the blog.
- Node.js updates MongoDB.
- Invalidate the corresponding Nginx cache entry.
- Purge the corresponding Cloudflare cache entry.
- The next request generates fresh HTML and stores it in the caching layers again.
This is particularly useful when you have an admin panel where users frequently update content.
8. Cloudflare-CDN-Cache-Control
Now, there was one more thing I discovered.
I found that proxy-revalidate is a standard HTTP directive for shared caches, but I wanted to control Cloudflare's caching behaviour specifically.
So, I added another header in my Nginx configuration:
add_header Cloudflare-CDN-Cache-Control "no-cache" always;Basically, Cloudflare-CDN-Cache-Control is a Cloudflare-specific response header.
By using:
Cloudflare-CDN-Cache-Control: no-cacheI'm telling Cloudflare that it can store the response, but it must revalidate the cached response before using it again.
This is different from no-store.
no-store tells the cache not to store the response, whereas no-cache allows storage but requires revalidation before reuse.
So, if I want Cloudflare to revalidate on every reuse, I can use this header.
If I want Cloudflare to cache the response for five minutes, I can instead use:
Cloudflare-CDN-Cache-Control: public, max-age=300And if I want browser caching and Cloudflare caching to behave independently, I can configure their respective headers separately.
In my opinion, you should understand both standard HTTP caching directives and CDN-specific caching headers because you might introduce another proxy or CDN in the future.
That's it. This is how I implemented HTTP caching in my infrastructure, from static assets to dynamic HTML pages, using browser caching, Cloudflare, and Nginx.
This is one of my article is related to caching, here i tell how inproper use of caching could cause a error and broke something