Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Concept · 15 min · revision 1

Invalidation, versioned assets and signed URLs

Plan how cached content changes: what a purge can and cannot reach, why versioned asset URLs beat purges, how an origin shield softens the refill, and how an edge can check an expiring HMAC-signed URL without calling your application.

Contentsand lesson path

What you will learn

  • Plan invalidation, versioned asset URLs, origin shielding and signed URLs for protected content.

Prerequisites: Caching Strategies

01. Why it matters

Once a response sits in hundreds of edge caches, in browsers and in office proxies, "changing the file" really means making every copy stop being used. You have three tools: wait for copies to expire, tell the CDN to drop them (a purge), or never change what a URL returns and publish new content under a new URL (versioning).

Some content must not reach everyone at all, such as a paid download or a private report. The edge has to decide who may fetch it without calling your application on every request, and without giving up caching. Signed URLs do that, as a small HMAC example in Python shows.

02. What a purge reaches, and what it does not

A purge is an API call (or dashboard action) that tells the CDN to stop serving stored copies. Providers offer several scopes. Cloudflare can purge by URL, by cache tag, by hostname, by URL prefix or everything; Fastly by URL, by surrogate key (a tag the origin attaches to responses, so that one call can clear every page showing, say, one product) or everything. CloudFront calls the same idea an invalidation and takes paths with wildcards. Four limits shape how you use them:

  • A purge reaches only the CDN. Browsers and corporate proxies keep their copies until their own lifetime ends. A file served with max-age=86400 can stay on a laptop for a day after you purge it.
  • A purge by URL removes one cache key. If the CDN stores /report.pdf and /report.pdf?ref=mail as separate entries, purging one leaves the other.
  • Purges are rate-limited and take time to spread. For example, Cloudflare's free plan allows 5 tag, prefix, hostname or purge-everything requests per minute, and Fastly limits URL and surrogate-key purges to an average of 100,000 an hour per customer. Purging is a tool for occasional changes, not a substitute for correct lifetimes.
  • After a purge, every location misses. The refill traffic lands on your origin unless an upper tier absorbs it. Plan an origin shield for this (lesson 1, Edge tiers and the origin shield): place it where its link to the origin is best, so that the refill after a purge or a release reaches the origin about once per object (CloudFront consolidates concurrent requests for one object at Origin Shield), and budget for its per-request fee. Some providers offer a softer option that marks copies as stale instead of deleting them: Cloudflare's invalidation revalidates and reuses content that has not changed, and Fastly's soft purge serves the stale copy to the next request while it fetches the new one.

HTTP has its own invalidation rule: a cache that sees a 2xx or 3xx response to a POST, PUT or DELETE for a URL must invalidate what it stored for that URL (RFC 9111 section 4.4). The RFC notes that this only affects caches the request passes through, so it never clears the other edges of a CDN. A common pattern combines the pieces: give the CDN a long lifetime (s-maxage or CDN-Cache-Control), give browsers a short one, and purge from your publishing system when content changes.

03. Versioned asset URLs

For files that your build produces, such as JavaScript, CSS and images, there is a better option than purging: put a content hash in the file name, as in app.3f9a2c1e.js. When the content changes, the name changes, so no cache anywhere can hold a stale copy of the new URL. Such a file can be served with Cache-Control: public, max-age=31536000, immutable. The HTML that names the files is the only thing that has to update quickly, so it gets no-cache and an ETag, or a short lifetime. CloudFront's documentation recommends versioned names over invalidation for files that change often, partly because versioning also works for copies held in browsers and proxies, where an invalidation never arrives.

Versioning needs three details:

  1. The version must be part of the cache key. A hash in the path is always in the key. A version in the query string, such as ?v=42, works only while the CDN keys on that query parameter.
  2. Deploy assets before the HTML that uses them, and keep the previous assets for a while. Pages loaded before a release still ask for the old file names, and they should not get errors.
  3. Some URLs cannot be versioned, because other people link to them: page URLs, API endpoints, a logo embedded in sent emails. These need a short lifetime, a purge, or both.

04. Signed URLs for protected content

A signed URL carries its own permission. Your application decides that a user may download a file, then builds a link that contains an expiry time and a message authentication code (MAC): a short value computed from the URL parts and a secret key. The edge holds the same key, recomputes the MAC, compares, and checks the time. In practice, nobody without the key can change the path or the expiry and still produce a valid MAC. The example uses HMAC-SHA256 from the Python 3.12 standard library, with fixed keys and time so the output repeats.

Python · signed_url.py
"""signed_url.py: expiring download links signed with HMAC-SHA256 (stdlib only)."""

import base64
import hashlib
import hmac
from urllib.parse import parse_qs, urlsplit

# Key id -> secret. Real secrets live in a secret store, never in source code.
KEYS = {"k1": b"lesson-demo-key-1", "k2": b"lesson-demo-key-2"}
CURRENT = "k2"  # new links use k2; links signed with k1 still verify
LEEWAY = 30  # seconds of clock difference tolerated between signer and edge


def mac(path: str, expires: int, kid: str) -> str:
    message = f"{path}\n{expires}\n{kid}".encode()
    digest = hmac.new(KEYS[kid], message, hashlib.sha256).digest()
    return base64.urlsafe_b64encode(digest).rstrip(b"=").decode()


def sign(path: str, now: int, ttl: int, kid: str = CURRENT) -> str:
    expires = now + ttl
    return f"{path}?exp={expires}&kid={kid}&sig={mac(path, expires, kid)}"


def check(url: str, now: int) -> str:
    parts = urlsplit(url)
    q = {name: values[0] for name, values in parse_qs(parts.query).items()}
    exp = q.get("exp", "")
    # Fail closed: "²".isdigit() is True but int("²") raises, so require ASCII.
    if q.get("kid") not in KEYS or not (exp.isascii() and exp.isdigit()):
        return "403 malformed link or unknown key"
    good = mac(parts.path, int(exp), q["kid"])
    # Compare bytes: compare_digest raises on non-ASCII str, never on bytes.
    if not hmac.compare_digest(q.get("sig", "").encode(), good.encode()):
        return "403 bad signature"
    if now > int(exp) + LEEWAY:
        return "403 expired"
    return "200 allowed"


NOW = 1_800_000_000  # 2027-01-15 08:00:00 UTC, fixed so the output repeats
url = sign("/files/q4.pdf", NOW, ttl=300)
print(url)
print("after 60 s:        ", check(url, NOW + 60))
print("after 320 s:       ", check(url, NOW + 320))  # 20 s late, inside LEEWAY
print("after 340 s:       ", check(url, NOW + 340))
print("other file:        ", check(url.replace("q4", "q3"), NOW + 60))
print("expiry edited:     ", check(url.replace("exp=1800000300", "exp=1900000000"),
                                   NOW + 60))
print("old key k1:        ", check(sign("/files/q4.pdf", NOW, 300, "k1"), NOW + 60))
print("crafted expiry:    ", check("/files/q4.pdf?exp=%C2%B2&kid=k2&sig=x", NOW))
print("crafted signature: ", check(url.split("&sig=")[0] + "&sig=%C3%A9", NOW))
Terminal
python3 signed_url.py
Expected output
/files/q4.pdf?exp=1800000300&kid=k2&sig=KjTPUUMosG62zc9LsDgOiI0fd_9hJeHI6ElEUFZy200
after 60 s:         200 allowed
after 320 s:        200 allowed
after 340 s:        403 expired
other file:         403 bad signature
expiry edited:      403 bad signature
old key k1:         200 allowed
crafted expiry:     403 malformed link or unknown key
crafted signature:  403 bad signature

Read the checks in order:

  • What is signed. The MAC covers the path, the expiry and the key id, so a link for q4.pdf cannot be reused for q3.pdf, and nobody can push the expiry later. Anything that limits access, such as an allowed path prefix or client network, must be inside the signed message too.
  • Constant-time comparison, failing closed. hmac.compare_digest takes the same time whether the first or the last character differs, so an attacker cannot guess a valid signature one character at a time by measuring responses. The check compares bytes and accepts only ASCII digits as an expiry, so a crafted link gets a 403 instead of crashing the checker.
  • Key rotation. The kid (key id) says which secret signed the link. New links use k2, while links signed earlier with k1 keep working until you remove k1.
  • Expiry and clock skew. The signer and the edge read different clocks, and the expiry is an absolute time. If the signer's clock runs behind, its links arrive already closer to expiry, or past it. The 30-second LEEWAY absorbs small differences; keeping clocks synchronised with the Network Time Protocol (NTP) and choosing lifetimes much longer than any plausible skew does the rest. CloudFront checks expiry when a request starts, so a download that began in time may finish, but a resumed download or a later range request after the expiry fails.

A signed URL is a bearer credential: whoever holds it can use it until it expires, so keep lifetimes short, serve it only over HTTPS, and keep full URLs out of logs. Keep the signature parameters out of the cache key, or every user's link becomes a separate cache entry, but only when the edge itself checks the signature before it looks in the cache. If only the origin checks it (for example a storage service's presigned URL behind a CDN), a cached copy would be served to anyone, so keep the signature in the key and the CDN's lifetime no longer than the link's, move the check to the edge, or do not cache the file. Video adds one more problem: a player fetches a playlist and then hundreds of segment URLs, so providers offer signed cookies or tokens that cover a path prefix.

There is no universal format. CloudFront verifies RSA 2048 or ECDSA 256 signatures over a policy statement and reads parameters such as Expires, Signature and Key-Pair-Id. Cloudflare's token authentication rule, which needs a paid plan (Pro or above), checks an HMAC token that carries the time it was issued, with the allowed lifetime set in the rule. Build links in exactly the format your CDN verifies; this script only models the idea.

05. Check your understanding

Practice check · 3 questions

Purges, versions and signatures

Pick the best answer for each situation.

Q1. A CDN zone has "ignore query string" turned on to raise its hit ratio. A release changes a page's script link from `/app.js?v=41` to `/app.js?v=42`, with new content at the same path. Both are served with `max-age=31536000`. What do users get?
Q2. An app server's clock runs two minutes behind. It signs download links with `expires = now + 60` seconds; the edge checks expiry against its own correct clock and allows 30 s of leeway. What happens?
Q3. A team computes the HMAC over the expiry time only, then appends `?exp=...&sig=...` to the file path. A customer receives a valid link for `/invoices/1001.pdf`. What can the customer do?
Practice only: not graded, not saved, not evidence.

06. Apply it

For the practice project, write a one-page change plan:

  1. List every URL type on your site and mark it versioned, short lifetime, purge on change or never cached.
  2. For the protected media file, find a signed URL or token feature that your plan includes, and write down its exact format, its key type, and when it checks expiry.
  3. Adapt signed_url.py to produce that format, issue a link that expires in two minutes, and confirm with curl -s -o /dev/null -w "%{http_code}\n" <url> that it returns 200 before expiry and 403 after.
  4. If the edge verifies the signature, check that the signature parameters are not part of the cache key: two different valid links should both be hits after the first download, and a link with a wrong signature should get 403.

07. Review prompt

Without looking back, answer in your own words:

  1. Name four limits of a CDN purge.
  2. Why do fingerprinted file names make purges unnecessary for build assets, and which URLs still need a purge or a short lifetime?
  3. What must a signed URL's MAC cover, and why does the comparison need to take constant time?
  4. How do clock skew and key rotation affect signed links, and how does the example handle each?

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check