Sub topic 11
Delivering through a CDN with immutable, cacheable URLs
This chapter assumes you know HTTP caching basics (headers, status codes), have uploaded files to object storage such as Amazon S3, and have a pipeline that produces final files, such as image variants. It covers how to serve those files through a CDN so most requests never reach your storage.
What a CDN does for media
A CDN (content delivery network) is a set of servers called edge locations, spread across many regions. A viewer's request goes to a nearby edge. If the edge has a stored copy (a cache hit), it answers immediately. If not (a cache miss), it fetches the file from your origin, which is your object storage bucket or a server in front of it. The edge then keeps a copy for the next viewer.
For media this brings three benefits:
- Latency: the bytes travel a shorter distance.
- Origin load: one origin fetch can serve thousands of viewers.
- Cost: CDN egress is often cheaper than egress straight from storage, and origin requests drop sharply.
The benefit depends on the cache hit ratio, the share of requests answered from the edge. Everything below aims to raise that ratio without serving stale files.
The caching problem: staleness versus invalidation
Caching creates a conflict. A long lifetime gives a high hit ratio, but if the file changes, viewers keep seeing the old one. You have two ways to deal with that.
- Invalidation: ask the CDN to drop cached copies of a path. This works, but it is slow to propagate, often limited or billed by volume, and it doesn't clear copies in browsers or in other caches between you and the viewer.
- Versioned URLs: never change a file at a given URL. A changed file gets a new URL, and the old URL keeps pointing at the old bytes.
Versioned URLs are the better default for media. The URL is then an identifier of the exact content, so a cache can keep the file for as long as it likes without risk of being wrong.
Content-addressed keys
The most reliable versioning scheme puts a hash of the file content in the key. If the bytes change, the hash changes, so the URL changes. If two uploads have identical bytes, they get the same key, which also removes duplicates.
import hashlib
import boto3
s3 = boto3.client("s3")
CACHE_CONTROL = "public, max-age=31536000, immutable"
def publish_variant(path: str, bucket: str, width: int) -> str:
"""Store a processed WebP variant under a content-addressed key."""
with open(path, "rb") as f:
data = f.read()
digest = hashlib.sha256(data).hexdigest()[:16]
key = f"media/{digest}/w{width}.webp"
s3.put_object(
Bucket=bucket,
Key=key,
Body=data,
ContentType="image/webp",
CacheControl=CACHE_CONTROL,
)
return keyThis code hashes the output bytes of the variant. Your database stores the key (or the hash), and your application builds URLs like https://cdn.example.com/media/9b1c4e.../w800.webp. When a user replaces their avatar, the new file gets a new key and the database row points to it. The old file remains until a cleanup job removes it, which the lifecycle chapter covers.
If you can't hash the output, you can hash the source file plus the transform parameters (width, format, quality). This works if the pipeline is deterministic. A hash of the output is the safer choice.
Setting Cache-Control
The Cache-Control response header tells caches how long they may reuse a response. For a content-addressed file the response looks like this:
GET /media/9b1c4e/w800.webp HTTP/1.1
Host: cdn.example.com
HTTP/1.1 200 OK
Content-Type: image/webp
Cache-Control: public, max-age=31536000, immutable
ETag: "9b1c4e"Each directive does a specific job:
| Directive | Meaning |
|---|---|
| `public` | Shared caches such as the CDN may store the response, even if the request carried credentials. |
| `max-age=31536000` | The response is fresh for 31,536,000 seconds, which is one year. |
| `immutable` | The content will not change while it is fresh, so a browser should not revalidate it, even on a reload. |
| `s-maxage=N` | Like `max-age`, but only for shared caches. It overrides `max-age` there. |
| `no-cache` | A cache may store the response but must revalidate it before each reuse. |
| `no-store` | Do not store the response anywhere. |
| `private` | Only the viewer's own browser may store it, not shared caches. |
One year is the practical ceiling. The HTTP specification doesn't forbid larger values, but caches commonly treat anything above a year as a year.
Set the header at the origin
Store the Cache-Control value as object metadata, as the code above does. The CDN then passes it to browsers, and every layer sees the same policy. If you set it only in a CDN rule, the browser may get a different value than the edge uses, and your behavior becomes harder to reason about.
Don't give the same policy to mutable URLs
Not every URL can be immutable. An HTML page or a JSON manifest that points at hashed assets must be fetched fresh, or viewers will never learn about new versions. Use a short lifetime or revalidation for those:
Cache-Control: public, max-age=0, must-revalidateWith this policy the cache may keep a copy, but it must check with the origin before every reuse. Because of the ETag, that check is a cheap conditional request that returns 304 Not Modified with no body when nothing changed. The next chapter covers conditional requests in detail.
The cache key
The CDN decides whether two requests want the same file by building a cache key from parts of the request. By default this is usually the host and path. Query strings, headers, and cookies are included only if you configure the CDN to include them.
Every extra part you add to the key splits the cache into more copies and lowers the hit ratio. For media, keep the key small:
- Ignore cookies for public media. If cookies are in the key, each logged-in user gets a separate cached copy of the same image.
- Ignore or allowlist query strings. A tracking parameter like
?utm_source=xshould not create a new cache entry. If you resize with?w=800, include onlywin the key. - Be careful with
Vary. AVary: Acceptheader lets you serve WebP or AVIF depending on the browser, but the cache then stores one copy per distinctAcceptvalue. Normalize the header at the CDN, for example to "supports AVIF", "supports WebP", "neither", or put the format in the URL and avoidVaryentirely. Putting the format in the path is simpler and easier to debug.
Origin protection
Without care, a burst of misses can hit your origin hard. Several features reduce that:
- Request collapsing: when many viewers ask for the same uncached file at once, the edge sends one request to the origin and shares the response. Check that your CDN has this enabled.
- Origin shield: an extra caching layer between the edges and the origin. Misses from all edges go through one regional cache first, which lowers the number of origin fetches.
- Restricting direct access to the bucket: configure the bucket so only the CDN can read it, for example with an origin access control. Then viewers can't bypass the cache or your access rules by going to the bucket URL.
Common errors
- Long cache lifetimes on non-hashed URLs. If
/avatars/42.jpghasmax-age=31536000, you can't change it. Either hash the URL or use a short lifetime. - Hashing the input but changing the pipeline. If you fix a resize bug but the key is derived only from the source file, the new output has the old key. Include the transform parameters or a pipeline version in the hash, or hash the output.
- Caching error responses. A
404or403from the origin may be cached by the CDN for some time. If you upload a file after a viewer requested the key, that viewer can keep seeing the error. Keep the error cache time short, and don't hand out URLs before the upload completes. - Missing
Content-Type. Objects stored without a type may be served asbinary/octet-stream, so browsers download them instead of displaying them. - Trusting
immutablefor private content. Immutable only controls freshness. It does not control who may fetch a file. Access control for private media is a separate topic, covered in a later chapter.
Summary of the design
- The pipeline writes each final file under a key containing a content hash.
- The file is stored with
Content-TypeandCache-Control: public, max-age=31536000, immutable. - The database stores the key. Pages and API responses, which have short lifetimes, reference the CDN URL.
- The CDN uses a minimal cache key, fetches from the origin only on misses, and collapses concurrent misses.
- Changing content means writing a new key and updating the reference. Nothing is invalidated.
Exercise
A team serves profile photos at https://cdn.example.com/avatars/{user_id}.jpg with Cache-Control: public, max-age=31536000, immutable. Users complain that after uploading a new photo they still see the old one for weeks. Explain why this happens, and describe a fix that does not rely on CDN invalidation.
Show answer
The URL stays the same while the bytes change. Because the old response was marked immutable with a one-year lifetime, browsers and the CDN keep reusing their stored copy and never ask the origin for the new file. The fix is to make the URL change when the content changes. Store each upload under a content-addressed key, such as avatars/{sha256-prefix}/w256.jpg, save that key in the user's database row, and build the URL from it. A new photo then has a new URL that no cache has seen, so it is fetched fresh. The old file can be removed later by a cleanup job.
Exercise
Your CDN cache key includes all cookies and all query parameters, and your hit ratio for public images is low. Name two changes that would raise it, and say why each works.
Show answer
First, remove cookies from the cache key for public media. Otherwise every user's session cookie creates a separate cached copy of the same image. Second, ignore query parameters, or allowlist only the ones that change the output (such as a width parameter). Tracking parameters like utm_source otherwise make the same file look like many different ones. In both cases, requests for the same file now map to one cache entry, so more requests are hits.