Cache Layers That Never Need a CDN Purge
Every small site eventually has the same conversation: "I replaced the logo, but the browser still shows the old one."
The usual answers are "wait a day", "add ?v=2 by hand", or "purge the CDN". All three are symptoms of the same mistake - treating every static file as one caching problem. They are not.
A site has at least three kinds of static content, and each needs a different contract:
- HTML must reflect a deploy immediately.
- Build assets (JS, CSS) can be cached forever if their URL changes when their content changes.
- Images uploaded or replaced by a human have no content hash, so they must be revalidated - and that is cheaper than it sounds.
When those three are separated, the CDN panel stops being part of your deploy process.
The cost of getting it wrong, in both directions
The naive setups fail in opposite ways:
Cache everything briefly. max-age=3600 on JS and HTML means a user can run yesterday's code against today's API for an hour. On a page that fetches data with a versioned response shape, that is not a performance issue; it is a correctness issue. It also means every deploy has a one-hour blast radius that no amount of testing removes.
Cache everything forever. immutable on files whose names never change pins a bug in place for a year. I have seen this happen with a one-character CSS fix that was invisible to half the users and required a support script to clear. The fix is not "remember to purge"; it is to make the filename change.
Disable caching entirely. no-store everywhere is the safest-looking option and the most expensive: a 1 MB charting library re-downloaded on every navigation, no 304s, and mobile users paying for bytes they already have. It also makes every page load slower than the deploy that follows it.
The goal is not "maximum cache" or "zero cache". It is: the URL identifies the bytes.
Layer 1 - HTML revalidates, always
HTML is the entry point and the thing most likely to change on deploy. It should never be served from cache without asking the origin:
location ~* \.html$ {
add_header Cache-Control "no-cache, must-revalidate" always;
etag on;
if_modified_since exact;
}
no-cache does not mean "do not store"; it means "store, but revalidate before use." With ETag, the revalidation is a conditional request that usually costs a 304 Not Modified with no body. The user gets the new page on the deploy that changes it, and an empty response on every navigation in between.
if_modified_since exact prevents a subtle bug: some proxies and clients send a truncated or rounded timestamp, and a lenient comparison can return 304 for a file that did change. Exact matching avoids serving a stale page because two timestamps landed in the same second.
For the JSON that feeds a dashboard, the same policy applies. A data.json with a one-hour TTL is a dashboard that lies for an hour after a deploy. no-cache plus ETag costs one conditional request and removes an entire class of "why is the number different on my phone" reports.
Layer 2 - hashed filenames, cached forever
For JS and CSS, the URL should contain the content hash:
<link rel="stylesheet" href="/css/site.css?v=a1b2c3d4">
<script src="/js/app.js?v=a1b2c3d4"></script>
Then the header can be absolute:
location ~* \.(css|js)$ {
add_header Cache-Control "public, max-age=31536000, immutable" always;
}
immutable tells the browser not to revalidate even on reload, which is the correct promise because the URL cannot change while the bytes stay the same. A new deploy produces a new hash, a new URL, and a cache miss - automatically, for every client, with no purge.
The non-negotiable rule is that the version bump and the long cache must ship in the same commit. Turning on immutable while HTML still references app.js without a version is worse than the original problem: you have now frozen the old file for a year with no way to invalidate it except renaming.
Two guardrails make that rule enforceable:
- Generate the version, do not type it. A script hashes each referenced file and rewrites the query string in every HTML page. It also handles
<link href>for CSS, not just<script src>- the common half-implementation only versions JavaScript and then wonders why a CSS fix does not appear. - Make the script idempotent and fail the build when it is not. Running it twice must produce zero changes; a non-empty diff on the second run means the rewrite is unstable, and an unstable rewrite produces churn in every commit.
A minimal version of the rewrite step:
const crypto = require('crypto');
function hashOf(file) {
return crypto.createHash('sha1').update(fs.readFileSync(file)).digest('hex').slice(0, 8);
}
// for every *.html, rewrite src/href that point at local css/js
html = html.replace(/(src|href)="((?:js|css)\/[^"?]+)(\?v=[^"]*)?"/g, (m, attr, file) => {
if (!fs.existsSync(file)) return m;
return `${attr}="${file}?v=${hashOf(file)}"`;
});
Two details worth copying:
- Whitelist third-party bundles. A vendored
echarts.min.jsshould keep a semantic version (?v=5.4.3), not a content hash that changes whenever a bundler touches whitespace. Otherwise every rebuild invalidates a 1 MB download for no functional change. - Skip external URLs and data URIs. Rewriting
https://...or//cdn...produces broken links that only appear in production.
Layer 3 - images revalidate instead of expiring
Images are the awkward case. A logo replaced by a human has no content hash in its URL, and adding one by hand is exactly the manual step we are trying to eliminate. Three strategies exist:
- Long TTL (
max-age=604800): Stale up to seven days, then correct. Old logo for a week, or a purge. - Short TTL (
max-age=300): Correct within five minutes. Revalidation traffic all day, cache churn. no-cache+ETag: Correct on the next request, no purge. One conditional request per image per session.
The third is usually the right answer for a small site's brand assets:
location /images/ {
root /var/www/app;
add_header Cache-Control "no-cache" always;
etag on;
if_modified_since exact;
access_log /var/log/nginx/static.log combined if=$log_static_problem;
}
The objection is always "but that's a request per image." It is - and it is a 304 with no body, typically a few dozen bytes, sent after the browser has already cached the bytes. For a page with six icons, that is six tiny conditional requests, versus the alternative of either serving the wrong logo or opening the CDN dashboard after every design tweak.
The calculus changes when the asset set is large (a product gallery, user avatars, a photo feed). There, no-cache per image becomes real traffic, and the right answer is content-addressed filenames or an image CDN. The mistake is applying the gallery answer to six brand files, or applying the brand-file answer to ten thousand photos.
One more nginx detail: do not let a static location inherit expires from a broader block. If the server block has expires 7d, a nested location with its own add_header may end up with both headers, and the browser will pick the more permissive one. Set the header explicitly at the narrowest location and verify with curl -I.
Prove it with headers, not with feelings
Caching bugs are invisible in a browser until they are not. The verification is three curls:
curl -sI https://example.com/index.html | grep -i -E 'cache-control|etag|last-modified'
curl -sI https://example.com/css/site.css?v=a1b2c3d4 | grep -i cache-control
curl -sI https://example.com/images/logo.png | grep -i -E 'cache-control|etag'
Expected:
cache-control: no-cache, must-revalidate
etag: "6f2..."
cache-control: public, max-age=31536000, immutable
cache-control: no-cache
etag: "9c1..."
Then the second request, with the ETag echoed back:
curl -sI -H 'If-None-Match: "9c1..."' https://example.com/images/logo.png
# HTTP/1.1 304 Not Modified
If the CDN sits in front, add one more check - the CDN's own cache status header:
curl -sI https://example.com/images/logo.png | grep -i cf-cache-status
MISS then HIT is fine; the thing to watch is a HIT that outlives your origin header change. When that happens, the edge is caching by its own rules, which usually means the origin is not sending the header you think it is, or a page rule overrides it. Check the origin response first, then the edge - in that order.
Compression belongs in the same conversation
Serving 1 MB of charting library with correct cache headers still means the first visitor downloads 1 MB. The same static locations should be compressed:
gzip on;
gzip_comp_level 5;
gzip_min_length 1024;
gzip_vary on;
gzip_types text/css application/javascript application/json image/svg+xml text/plain application/xml;
gzip_vary is not optional: without it, a shared cache can serve the gzipped variant to a client that did not ask for it. And gzip_types needs application/xml explicitly - it is not in the default list, which is a fun surprise when your sitemap is served uncompressed.
For files served directly from disk, three server-level settings remove most of the per-request overhead:
sendfile on;
tcp_nopush on;
open_file_cache max=2000 inactive=60s;
open_file_cache_valid 30s;
open_file_cache_min_uses 1;
None of these change cache semantics. They reduce the cost of the requests that still reach the origin, which is what makes the revalidate-always policy affordable.
Logging only the requests that matter
Once static files are served directly by nginx, the access log fills with 200s and 304s that tell you nothing. A tiny map keeps the signal:
map $status $log_static_problem {
~^[23] 0;
default 1;
}
location /images/ {
access_log /var/log/nginx/static.log combined if=$log_static_problem;
}
Now the static log contains only 4xx/5xx - missing files, permission errors, broken rewrites. A normal week produces an empty file, which makes the one day it is not empty worth reading.
The deploy checklist this produces
- HTML:
no-cache,ETag, exact If-Modified-Since. - JS/CSS: content hash in the URL,
immutablefor a year. Version bump runs before commit, and a second run is a no-op. - Images:
no-cache+ETag; a replaced file is live on the next request. expiresfrom parent blocks does not leak into narrow locations.gzip_varyon,application/xmlincluded.- Verify with
curl -I, both at the origin and through the CDN.
The payoff is not a faster first paint. It is that publishing stops requiring a second, manual step in someone else's dashboard. A deploy is a deploy; a logo replacement is a file copy. Neither needs a purge button.
The same reasoning, applied to a content site's HTML-only purge problem, is written up at wuhuajin.com. Originally published on wuhuajin.com.
Comments
No comments yet. Start the discussion.