In this lesson · topic 5 of 7
Topic 5
Cache keys and purging
4 min read
Choosing what is in the key
A good key holds what changes the response and nothing else. The path usually belongs. A language header belongs if the server picks the language from it. A tracking parameter does not belong, because it never changes the body.
The Vary header in RFC 9111 lets a server name request headers that must be part of the key. Use it sparingly. Every header you add multiplies the entries for the same object. Many CDNs let you list the query parameters that count and ignore the rest, which is the safer way to strip noise.
Purge on change
When an object changes, you can tell the CDN to delete its copies. The next request misses and fetches the new version.
With a TTL of 300 ticks and no purge, 40 percentmeasured of responses were out of date. With purge on, the stale share was 0 percentmeasured. Origin requests were 749measured against 591measured without it, and still well below the 1385measured that a TTL of 60 needs. You keep most of the long TTL’s savings and give up the staleness.
Versioned names
A second approach avoids purging. Put a hash or version in the file name, such as app.4f2a.js. A changed file has a new name, so it is a new key, and the old copy can be cached for a very long time. This works for files that a page references. It does not work for the page itself, which needs a fixed address.