Cache vs CDN: How Browser, Server and CDN Caching Work Together
In this article
Cache versus CDN is not a choice between two things. A cache is any stored copy of something that was expensive to fetch or build, kept so the next request for it is cheaper. A CDN is a network of servers spread around the world whose main job is to hold a cache close to your visitors. So a CDN is one place a cache lives. A fast website uses three such places: the visitor's browser, the CDN's edge servers, and the memory of your own server.
Each layer answers a different question. The browser asks whether it has downloaded this file before. The CDN asks whether anyone near this visitor has fetched it recently. The server asks whether it has built this page or run this query recently. Set up well, most requests are answered at the first layer that can. The expensive work of building a page from the database happens once rather than once per visitor.
Layer 1: the browser cache and what a cache header says
When a browser downloads a file it can keep a copy on the device. Whether it does, and for how long, is decided by the Cache-Control header the server sends with the file. The header is a short list of instructions:
| Directive | What it tells the browser | Use it for |
|---|---|---|
| max-age=31536000 | Keep this copy and reuse it for a year without asking | Files whose name changes when the content changes |
| immutable | Do not even check for a new version while the copy is fresh | The same hashed files |
| no-cache | You may keep a copy, but check with the server before using it | HTML pages that change but can be revalidated |
| no-store | Do not keep a copy at all | Pages with personal data, baskets, account pages |
| private | Only the browser may cache this, not a shared cache or CDN | Anything personalised |
| public | Shared caches may keep this too | Static files and anonymous pages |
| stale-while-revalidate=60 | Serve the old copy now and fetch a fresh one in the background | Content where a minute of staleness is fine |
Checking with the server is cheap when it is done properly. The server sends an ETag, a fingerprint of the file, or a Last-Modified date with the first copy. The browser sends it back on the next request, and if nothing has changed the server answers 304 Not Modified with no body. The exchange is a few hundred bytes instead of the whole file.
The risk with long lifetimes is that a visitor keeps an old stylesheet after you have changed it. The standard answer is to put a hash of the file's content in its name. A stylesheet becomes main.3f2a9c.css and the HTML points to the new name the moment the content changes. Django's ManifestStaticFilesStorage does this at deploy time, and WhiteNoise or the web server sends those hashed files with a year-long, immutable header. Un-hashed files get a short lifetime instead.
Cache-Control: public, max-age=31536000, immutable # hashed CSS, JavaScript, fonts
Cache-Control: no-cache # HTML pages
Cache-Control: private, no-store # account pages, baskets
Layer 2: the CDN cache at the edge
A CDN sits between your visitors and your server. Your domain points at the CDN; when a visitor in Glasgow or Melbourne requests a file, the request goes to the nearest CDN server, called an edge. If the edge has a fresh copy it answers immediately, which is a cache hit. If not, it fetches the file from your server, the origin, keeps a copy and passes it on, which is a miss. The next visitor near that edge gets the hit.
The edge follows the same Cache-Control header the browser does, with one addition: s-maxage sets a lifetime for shared caches that can differ from the browser's. Most CDNs cache images, CSS, scripts and fonts by default, identified by file extension, and do not cache HTML unless you ask. That default is sensible, because HTML is where personalisation lives. Whether you need a CDN at all depends on where your visitors are and what you serve. Our post on whether a small business needs a CDN goes through the decision.
Caching HTML at the edge is where the big wins and the big mistakes both are. An anonymous category page can safely be cached for a few minutes, which takes nearly all the load off the origin during a busy period. A page that includes the visitor's name, basket or a CSRF token cannot be, or one shopper is shown another's page. The usual rule is to bypass the edge cache whenever the request carries a session cookie and to cache for a short time when it does not.
Layer 3: server-side caching in Django
The server cache stores the results of work rather than files: a rendered page, a fragment of a template, or the answer to an expensive query. It lives in memory, usually Redis, which Django has supported as a cache backend since version 4.0, and it is shared by every worker process on the server. Django gives you three levels.
Whole pages
The cache_page decorator stores the full response for a view and serves it from Redis for the lifetime you set. It is only for pages that are identical for every visitor, so Django varies the cached copy on cookies and headers where the response depends on them.
from django.views.decorators.cache import cache_page
@cache_page(60 * 5)
def course_list(request):
...
Template fragments
Most pages are mostly the same for everyone with one personal corner. The cache template tag caches the expensive part, such as a menu built from the database or a list of recent products, and leaves the rest to render normally.
{% load cache %}
{% cache 600 product_sidebar category.slug %}
... the expensive queries ...
{% endcache %}
Single values
The low-level API caches anything: a count that needs a slow query, the result of a call to a payment provider, a currency rate. The get_or_set call runs the function only when the value is missing or has expired.
from django.core.cache import cache
total = cache.get_or_set("orders:total", Order.objects.count, 300)
What to cache where
| Content | Browser | CDN | Server |
|---|---|---|---|
| Hashed CSS, JavaScript, fonts | One year, immutable | Yes, long | Not needed |
| Product and page images | Long, with a version in the name | Yes, long | Not needed |
| Anonymous HTML (home, category, article) | no-cache, revalidate with ETag | A few minutes, bypassed when a session cookie is present | Per-view cache for a few minutes |
| Logged-in page, basket, checkout | private, no-store | Never | Fragments and query results only, keyed by user |
| Search results, filtered listings | no-cache | Short, if cookie-free | Query results keyed by the filter |
| API responses used by your own pages | Short max-age | Depends on the endpoint | Low-level cache per key |
Invalidation, and the mistakes we see
A cache is only useful if stale data leaves it when the real data changes. There are three honest strategies. The first is short lifetimes, so nothing is wrong for long. The second is keys that include a version or timestamp, so a change makes a new key and the old entry is simply never read again. The third is explicit deletion, where saving a product also deletes its cache entries, usually from a Django signal. We lean on the first two, because explicit deletion is the one that gets forgotten.
The mistakes are familiar:
- Caching a page that contains a session, a CSRF token or a visitor's name, so people see each other's data. Vary on the cookie, or bypass the cache when one is present.
- A year-long max-age on a file whose name never changes, so a fix to the stylesheet does not reach visitors until next year.
- Caching error responses and redirects, so a brief outage is replayed from the cache long after the server recovered.
- Forgetting Vary: Accept-Encoding, so a compressed copy is handed to a client that asked for an uncompressed one.
- Putting no-store on everything out of caution, which switches off the browser cache for the logo and the stylesheet too.
- Using Django's local-memory cache on a site with several worker processes or several servers, so each has its own cache and most requests miss. On anything behind a load balancer the cache has to be shared, which in practice means Redis.
How we set this up on our builds
On most of the sites we build, Django hashes the static files at deploy time and WhiteNoise sends them with a long cache lifetime. On the shop we built, product photos are resized into smaller copies when they are uploaded. On UK Name Change and UK Prenup, public pages such as the home page are cached on the server for between half an hour and a day.
On the web platforms we build, where nearly every page is behind a login, the whole-page cache is off. The work goes into fragment and query caches keyed by the user, which is where a dashboard that aggregates thousands of rows gets its speed. We fix a slow query before caching it, as our post on server response time and TTFB describes. A cache in front of a slow query still runs it on every miss.
Questions people ask
Is a CDN a cache?
A CDN contains one. Its edge servers hold cached copies of your files near your visitors, and most CDNs also handle TLS, compression and traffic filtering. The browser cache and the server cache are separate layers that work alongside it, not alternatives to it.
What is the difference between no-cache and no-store?
no-cache allows a copy to be kept but requires the browser to check with the server before using it. That usually ends in a cheap 304. no-store forbids keeping a copy at all. Use no-cache for ordinary pages and no-store only where the content is private.
How do I clear a cache?
Browser caches cannot be cleared remotely, which is why hashed filenames exist. CDN caches have a purge control in the provider's dashboard or API, for one URL or for everything. The Django cache can be emptied with cache.clear() or one key at a time with cache.delete(), and a deploy usually clears it.
Where to start
Open your home page with the Network panel in DevTools and look at the response headers on the stylesheet, a product image and the HTML itself. If the stylesheet has no Cache-Control header, or a short one, and its name has no hash in it, start there. Hashed names and a year-long header are an afternoon's work and every return visit gets faster. Then measure the server's first byte on your busiest anonymous page and, if it is slow, add a per-view cache of a few minutes. Our seven-day page speed plan puts these steps on day five.