Skip to content

Lesson 3 of 38Building blocks

DNS, CDNs, and Client Caching

Trace a request from domain name to edge server, and use TTLs and cache headers so most requests never reach you.

25 min read0/8 questions

The fastest request is the one that never reaches your servers. Before a single line of your backend runs, DNS has to find you, a CDN may answer from a server a few kilometres from the user, and the browser may already have the file. Getting these three layers right is often the cheapest performance and scaling win you will ever make.

DNS: from a name to an address

Computers connect to IP addresses like 203.0.113.10. People type names like shop.example.com. The Domain Name System (DNS) is the distributed phone book that turns one into the other.

Your laptop does not know every name. It asks a recursive resolver (run by your ISP, or a public one like 1.1.1.1 or 8.8.8.8), which walks the DNS hierarchy on your behalf: the root servers know who runs .com, the TLD servers for .com know who is authoritative for example.com, and the authoritative name server holds the actual records.

Resolving shop.example.com (cold cache)
BrowserResolverRoot.com TLDAuthoritativeshop.example.com?shop.example.com?ask the .com serversshop.example.com?ask ns1.example-dns.netshop.example.com?A 203.0.113.10, TTL 300203.0.113.10

The browser and OS check their own caches first. On a miss, they ask the configured recursive resolver.

1/8

The common record types: A (name to IPv4 address), AAAA (IPv6), CNAME (alias to another name, e.g. www → shop.example.com), MX (mail servers), TXT (verification strings, SPF), and NS (which servers are authoritative).

TTLs are a trade-off

Every record has a TTL (time to live) in seconds. Resolvers and browsers cache the answer for that long. A long TTL (a day) means fewer lookups and faster page loads. A short TTL (60 seconds) means you can move traffic quickly, for example when failing over to a backup region.

Quick check
Your DNS record has a TTL of 86,400 seconds. Tomorrow you are moving the site to new servers with a new IP. What should you do today?
Need a nudge? A hint rules out a wrong answer.

Anycast, in one line: many servers around the world announce the same IP address, and internet routing sends each user to the nearest one. Public resolvers like 1.1.1.1 and most CDNs use it.

CDNs: copies near your users

A CDN (content delivery network) is a fleet of servers in hundreds of cities called edge locations or points of presence (PoPs). Instead of every user fetching your logo from Virginia, they fetch it from a server in their own city. Your own servers are the origin. Examples: CloudFront, Cloudflare, Fastly, Akamai.

Step through what happens on a miss, a hit, and a dynamic request.

CDN edge caching: miss, hit, and pass-through
User in TokyoUser in TokyoUser in LondonUser in LondonEdge: Tokyo: cacheEdge: TokyocacheEdge: London: cacheEdge: LondoncacheOrigin: us-east-1Originus-east-1~5 ms~5 ms~150 ms~75 ms

Cache miss. The first Tokyo user asks for /logo.png. The Tokyo edge does not have it, so it fetches from the origin across the Pacific.

1/5

The cache hit ratio is the share of requests the CDN answers itself. For a site with good headers on static assets it is often above 90%, which means your origin handles a tenth of the traffic.

Static and dynamic content

Static content is the same for every user: images, video, CSS, JavaScript bundles, fonts, downloadable files. It is perfect for CDNs and can be cached for a year if the filename includes a content hash (app.3f9a1c.js), because a new deploy produces a new filename.

Dynamic content depends on who asks or changes constantly: a cart, a feed, an account page, search results. You usually do not cache it at the CDN, or you cache it for seconds (a public homepage cached for 30 seconds still cuts origin load enormously during a traffic spike).

Quick check
A news site's homepage gets 50,000 requests per second during a big story, and the origin is falling over. The page is the same for every visitor. What is the fastest fix?
Need a nudge? A hint rules out a wrong answer.

How a CDN routes you to the nearest edge

The diagram above assumed the Tokyo user lands on the Tokyo edge. Something has to make that happen, and CDNs use one of two mechanisms (often both).

DNS-based steering (GeoDNS). The CDN runs the authoritative DNS for your hostname. When a resolver asks for cdn.example.com, the CDN looks at where the question came from and returns the IP of a nearby PoP. A resolver in Tokyo gets a Tokyo address; one in Frankfurt gets a Frankfurt address. The weakness is that the CDN sees the resolver's location, not the user's. A user in Sydney using a public resolver whose nearest instance happened to be in Singapore gets steered to Singapore. The EDNS Client Subnet extension lets resolvers pass along part of the user's IP to fix this, but not every resolver sends it. Steering also moves only as fast as the TTL: if a PoP fails, clients keep its address until their cache expires.

Anycast. Every PoP announces the same IP prefix to the internet over BGP, the protocol routers use to exchange routes. Each router on the way picks what it sees as the shortest path, so packets for that one address flow to a nearby PoP without DNS doing anything clever. "Nearby" means nearest in network terms (fewest hops between networks, and the operators' own routing policies), which is usually but not always the closest city.

Anycast's big win is failure handling. When a PoP goes down, it stops announcing the prefix, routers recompute, and traffic shifts to the next nearest PoP. There is no DNS TTL to wait out. It also absorbs DDoS floods well: an attack aimed at one IP is split across every PoP in the world instead of hitting one site. Cloudflare's network is built on anycast; many other CDNs combine anycast for DNS with DNS-based steering for content.

GeoDNS steeringAnycast
How the user is routedDNS answer differs by resolver locationSame IP everywhere; BGP picks the path
Failover speedLimited by DNS TTL cachingSeconds, as routes are withdrawn
AccuracyResolver location, not user locationNetwork distance, not geography
Fine-grained controlEasy: send 10% of a country elsewhereCoarse: you shape routes, not users
DDoS absorptionAttack hits whichever PoP the name points toAttack is spread across all PoPs

Origin shield: one more layer of cache

Each edge has its own cache, so a file that is popular worldwide causes one origin miss per PoP. With hundreds of PoPs, a new release can send hundreds of simultaneous misses to your origin. Most CDNs offer a tiered cache or origin shield: edges that miss ask a regional mid-tier cache first, and only that tier asks the origin. Origin traffic drops from "one per PoP" to "one per shield", and the hit ratio as your origin sees it goes up. The cost is a slightly longer path on a full miss.

Quick check
A CDN PoP in Frankfurt loses power. Users near Frankfurt were reaching it by anycast. What happens to their next requests?
Need a nudge? A hint rules out a wrong answer.

Client-side caching with HTTP headers

The browser has its own cache, controlled by response headers you send. The same headers also tell CDNs what they may store.

HeaderWhat it meansUse it for
Cache-Control: public, max-age=31536000, immutableAnyone may cache it for a year and never re-checkHashed assets like app.3f9a1c.js
Cache-Control: no-cacheYou may store it, but must revalidate with the server before each useHTML pages that change on deploy
Cache-Control: no-storeNever store it anywhereBank statements, anything sensitive
Cache-Control: private, max-age=60Only the user's browser may cache it, not a CDNPer-user data
Cache-Control: s-maxage=30How long shared caches (CDNs) may keep itPublic pages at the edge
stale-while-revalidate=60Serve the old copy instantly while fetching a fresh one in the backgroundFeeds, homepages
ETag: "v7"A version fingerprint of this responseCheap revalidation

Note the confusing name: no-cache does not mean "do not cache". It means "always check first". The one that forbids storage is no-store.

Revalidation with ETags

When a cached copy is stale, the browser does not have to download the whole thing again. It sends the ETag it has, and the server answers 304 Not Modified with an empty body if nothing changed.

Conditional request with ETag
BrowserServerGET /products.json200 OK, ETag: "v7", 480 KBGET, If-None-Match: "v7"304 Not Modified (0 bytes)

GET /products.json

1/4
Match the pairs0/4 matched

Match each situation to the right header.

Choose an item, then its match on the other side.

Cache keys and Vary

A cache is a map from a cache key to a stored response. Every hit ratio problem and most CDN security incidents come down to getting that key wrong.

By default a CDN builds the key from the scheme, host, path and full query string. That default goes wrong in two opposite directions.

The key is too specific. Marketing links add ?utm_source=newsletter&utm_campaign=oct, ad clicks add ?gclid=... or ?fbclid=..., and each unique value creates a new key for what is the same page. Two requests for ?a=1&b=2 and ?b=2&a=1 are also different keys. Your hit ratio quietly falls and the origin takes load it should never see. The fix is to normalize the key: drop tracking parameters, sort the rest, and include only the parameters the page actually uses. CDNs let you configure this as a cache key or cache policy.

Pythoncache_key.py
import randomfrom urllib.parse import urlsplit, parse_qsl, urlencode random.seed(7)TRACKING = {"utm_source", "utm_medium", "utm_campaign", "gclid", "fbclid"} def raw_key(url: str) -> str: return url def normalized_key(url: str) -> str: parts = urlsplit(url) kept = sorted((k, v) for k, v in parse_qsl(parts.query) if k not in TRACKING) return parts.path + ("?" + urlencode(kept) if kept else "") def make_request() -> str: url = f"/products/{random.randint(1, 50)}" params = [] if random.random() < 0.3: params.append(("color", random.choice(["red", "blue"]))) if random.random() < 0.6: params.append(("utm_campaign", f"c{random.randint(1, 300)}")) if random.random() < 0.2: params.append(("fbclid", str(random.randint(10**6, 10**7)))) random.shuffle(params) return url + ("?" + urlencode(params) if params else "") requests = [make_request() for _ in range(20_000)] for name, key_fn in [("raw", raw_key), ("normalized", normalized_key)]: seen, hits = set(), 0 for url in requests: key = key_fn(url) if key in seen: hits += 1 seen.add(key) print(f"{name:<11} distinct keys {len(seen):>6} hit ratio {hits / len(requests):.1%}")
Output
Press Run (⌘ Enter) to see what happens.

Same 20,000 requests, same 150 real pages. The raw key turns them into thousands of entries and most requests miss. The normalized key collapses them back to the real pages.

The key is not specific enough. This one is worse, because it leaks data. If a response depends on something that is not in the key, the cache will hand one user's version to another. The classic incident: an account page is cached by path alone, so the first user to load /account after a deploy has their name and address served to everyone who visits for the next ten minutes. Every input that changes the response must either be in the key or the response must be marked private or no-store.

That is what the Vary response header is for. Vary: Accept-Encoding tells caches to store separate copies for gzip, Brotli and uncompressed clients, which is correct and cheap (a handful of variants). Vary: Accept-Language is reasonable if you serve a few languages. Vary: User-Agent or Vary: Cookie is a trap: there are thousands of user agent strings and every session cookie is unique, so the cache effectively stores one copy per user and your hit ratio goes to zero. Many CDNs treat Vary: Cookie as "do not cache" for that reason. If you need a few variants by device or by A/B bucket, compute a small value (mobile or desktop, bucket A or B) and put that in the key.

Predict the outputPython

Five requests reach the edge. After stripping utm_* parameters and sorting the rest, how many distinct cache keys remain?

from urllib.parse import urlsplit, parse_qsl, urlencode
def norm(u):
  p = urlsplit(u)
  q = sorted((k, v) for k, v in parse_qsl(p.query) if not k.startswith("utm_"))
  return p.path + ("?" + urlencode(q) if q else "")
urls = ["/p/42?utm_source=x", "/p/42?utm_source=y", "/p/42",
      "/p/42?color=red&size=m", "/p/42?size=m&color=red"]
print(len({norm(u) for u in urls}))
Need a nudge? Hints walk you through it.

Serving stale on purpose

When a cached copy expires, the naive behavior is: the next request waits while the edge fetches a fresh one from the origin. Two Cache-Control extensions (defined in RFC 5861) let you do better.

  • stale-while-revalidate=N: for N seconds after expiry, serve the stale copy immediately and refresh it in the background. Users never wait on the origin for a cached page, and the origin still gets one refresh per edge.
  • stale-if-error=N: if the origin is down or returns a 5xx, keep serving the stale copy for up to N seconds instead of showing an error. Your origin can be on fire for an hour and readers still see the homepage.

A typical header for a public page that changes often:

Cache-Control: public, max-age=0, s-maxage=60, stale-while-revalidate=300, stale-if-error=86400

Browsers always revalidate (max-age=0), the CDN keeps it for 60 seconds, serves it stale for 5 more minutes while refreshing, and falls back to a copy up to a day old if the origin fails. Support differs: modern browsers and most CDNs honor stale-while-revalidate, while stale-if-error is mainly a CDN feature, and some CDNs use their own settings instead of these directives. Check your provider's docs.

The related edge feature is request collapsing (also called coalescing). When 5,000 users ask for the same expired page in the same second, a good CDN sends one request to the origin and makes the other 4,999 wait for it, instead of forwarding all 5,000. Without it, every cache expiry on a hot page becomes a small stampede on your origin, the same thundering herd problem you saw in the caching lesson.

Purging vs versioned URLs

Sooner or later something wrong is cached: a price typo on a product page, an image a user deleted, a broken JavaScript bundle. You have two ways out.

Purge (invalidate) tells the CDN to drop entries. You can purge one URL, a path prefix, everything, or, on CDNs that support it, every response carrying a tag you attached when it was served (Fastly calls these surrogate keys; Cloudflare and others call them cache tags). Tags are the senior move: tag every page that shows product 42 with product-42, and when the price changes you purge that one tag instead of guessing which URLs show it. Purges take time to reach every PoP (often seconds, sometimes longer), some providers limit or bill them, and a purge does nothing to copies already sitting in browser caches. A file you sent with max-age=31536000 is in that browser for a year no matter what you purge.

Versioned URLs sidestep the problem: change the content, change the name. This is the hashed filename pattern from earlier (app.3f9a1c.js becomes app.7b20de.js), and it works for user content too: a replaced avatar gets a new object key, and the database row points to the new key. Nothing needs purging because nothing old is ever requested again.

The rule of thumb: version everything you can, purge only what you cannot version. Assets and media get versioned names and year-long cache lifetimes. HTML and API responses, whose URLs must stay stable, get short TTLs and tag-based purges for urgent fixes.

Quick check
You shipped logo.png (no hash in the name) with Cache-Control: max-age=31536000. It has a typo. You purge it from the CDN. Who still sees the old logo?
Need a nudge? A hint rules out a wrong answer.

Edge compute: code at the PoP

CDNs now run your code inside their PoPs, on every request, before the cache. Cloudflare Workers run JavaScript or WebAssembly in lightweight isolates at every Cloudflare location. AWS offers two tiers: CloudFront Functions, tiny and very fast JavaScript for rewriting requests and responses, with no network access; and Lambda@Edge, heavier functions that run at regional edge locations and can make network calls. Fastly Compute runs WebAssembly. The limits on runtime, memory and allowed APIs differ a lot between them and change over time, so check the docs before you rely on one.

Step through a request that edge code handles before the cache.

An edge function in front of the cache
BrowserEdge functionEdge cacheOriginGET /docs/pricing?utm_source=adverify JWT, pick A/B bucketkey: /docs/pricing + bucket=BHIT200 OK (8 ms)GET /old-pricing301 to /docs/pricing

The function runs at the PoP the user reached, a few milliseconds away.

1/7

What belongs at the edge is work that needs only the request itself plus small, slowly changing data: redirects and rewrites, header changes, cache key normalization, verifying a signed token, A/B bucketing, geo-based routing ("send EU users to the EU origin"), blocking obvious bots, and serving a maintenance page when the origin is down.

What does not belong there is anything that needs your primary database on every request. The edge is close to the user and far from your database. A function in Sydney that runs three queries against a database in Virginia makes three trips across the Pacific, which is far slower than one trip to an origin server sitting next to the database. Edge key-value stores help for read-mostly data like feature flags or redirect tables, but most are eventually consistent across PoPs, so they are a poor fit for anything like an account balance.

Quick check
Which of these is the best fit for an edge function?
Need a nudge? A hint rules out a wrong answer.
Put it in order5 steps

A user types a URL for the first time. Put these in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.
Key terms
DNS resolver
The server that walks root, TLD, and authoritative servers to answer a lookup, caching as it goes.
TTL
How many seconds a DNS answer or cached response may be reused before asking again.
CDN edge
A server near users that caches content from your origin and answers hits in a few milliseconds.
cache hit ratio
The share of requests answered from cache. 90%+ means the origin sees a tenth of the traffic.
Cache-Control
The HTTP header that tells browsers and CDNs whether and how long to store a response.
ETag
A version fingerprint. The client sends it back with If-None-Match and gets a cheap 304 if nothing changed.
anycast
Many PoPs announce the same IP over BGP, so routers send each user to a nearby one and failover needs no DNS change.
cache key
What a cache uses to decide two requests are the same. Too specific kills the hit ratio; too loose leaks data.
stale-while-revalidate
Serve an expired copy instantly while fetching a fresh one in the background.
edge compute
Your code running inside CDN PoPs, best for request-only logic like redirects, auth checks and cache key rules.