Skip to content
Visual explainer 1h 30m to learn 3 steps

CDNs & anycast

Explain how CDNs and anycast bring content closer to users and absorb attacks.

By Invicly Tech, , in Computer Networking. About 11 minutes to read.

Topic 46 of 51

In short

A content delivery network caches content at many edge locations close to users, cutting latency and offloading the origin server. Many CDNs use anycast, announcing the same IP address from every location so routing sends each user to a nearby edge. The same spread-out capacity absorbs large DDoS attacks.

Explained simply

A CDN (content delivery network) is a large set of servers spread around the world. It keeps copies of your website's files close to your users. A visitor in Tokyo gets images from a server in Tokyo instead of from your one server in Frankfurt, so pages load much faster.

These copies are called the cache. The first visitor in a city causes a cache miss: the CDN fetches the file from your server (the origin) and keeps it. Later visitors get a cache hit: the file comes straight from the nearby CDN server, called an edge.

How long the CDN keeps a file is mostly up to you. Your server sends a Cache-Control header with each file, for example "keep this for one day". Get these headers right and most requests never reach your origin at all.

Many CDNs also use anycast: the same IP address is announced from every location, and the internet's routing sends each user to a nearby one. This spreads traffic out naturally, which also helps the CDN absorb huge attacks.

Press Play on a diagram to walk through it one step at a time.

FlowServing a request through a CDN
  1. Step 1
    DNS

    Name resolves to the CDN's anycast IP.

  2. Step 2
    Nearest edge

    BGP routes the user to a nearby location.

  3. Step 3
    Cache hit?

    Serve immediately from the edge.

  4. Step 4
    Cache miss

    Fetch from origin and store per Cache-Control.

MapCaching rules by type of content
What should the CDN do?
  • Hashed assets (app.3f9a.js)
    • max-age=31536000, immutable
    • Never purge, just change the name
  • HTML pages
    • s-maxage=60 or no-cache
    • Revalidate with ETag
  • Public API responses
    • s-maxage=30, stale-while-revalidate=60
    • Key on the query string
  • Personal pages
    • private, no-store at the CDN
    • Contains user data
  • Login and payment
    • no-store
    • Bypass cache entirely

In depth

Edge caching and the cache key

When a request arrives at an edge, the CDN builds a cache key and looks it up. By default the key is usually the scheme, host, path and query string. Two URLs that differ only in their query string, such as ?utm_source=mail, are then two separate cache entries, which lowers the hit ratio, so CDNs let you ignore or sort query parameters in the key.

The Vary response header adds request headers to the key. Vary: Accept-Encoding is normal and keeps gzip and Brotli versions apart. Vary: User-Agent or Vary: Cookie can create thousands of variants and make caching almost useless. Large CDNs also use tiered caching or an origin shield: edges that miss ask a regional mid-tier cache first, so your origin sees one request per region instead of one per edge. Check what happened with response headers such as Age (seconds the object has been cached) and the CDN's own status header, for example cf-cache-status on Cloudflare or X-Cache on several others.

FlowA cache miss with an origin shield
  1. 1
    Edge lookup

    Build the cache key; not found: MISS

  2. 2
    Shield lookup

    Regional tier checks its cache

  3. 3
    Origin fetch

    Only if the shield misses too

  4. 4
    Store

    Shield and edge keep it per Cache-Control

  5. 5
    Next user nearby

    Served from the edge: HIT, Age grows

Reading Cache-Control

Cache-Control is the main header that tells caches what to do. max-age=N means the response is fresh for N seconds. s-maxage=N applies only to shared caches such as CDNs and overrides max-age there, so you can let the CDN keep a page for an hour while browsers keep it for one minute. public allows shared caches to store it; private means only the user's browser may store it, which is right for personal pages.

no-cache does not mean "do not cache": it means "store, but check with the origin before every use". That check is a conditional request with If-None-Match (using the ETag) or If-Modified-Since, and an unchanged file returns a small 304 Not Modified. no-store means do not store at all, for sensitive data. stale-while-revalidate=N lets a cache serve a slightly old copy while it fetches a fresh one in the background. For files with a version or hash in the name, like app.3f9a1c.js, use max-age=31536000, immutable so they are cached for a year and never rechecked.

  • max-age: freshness for all caches
  • s-maxage: freshness for CDNs only
  • no-cache: revalidate before use
  • no-store: never store
  • immutable: never revalidate while fresh

How anycast routing works

With normal unicast, one IP address belongs to one place. With anycast, the CDN announces the same IP prefix through BGP from every one of its locations. Each network on the internet picks its best BGP path to that prefix, usually the one with the shortest AS path or the cheapest peering, and so users end up at a nearby location, though not always the closest in kilometres.

Anycast fits DNS perfectly, because most DNS queries are a single UDP packet and answer. For TCP, it works because routes change rarely, so a connection's packets keep reaching the same location; when a route does change mid-connection, the new location does not know the connection and resets it, so CDNs engineer routes to stay stable. If one location fails, it stops announcing the prefix and traffic flows to the next-best location within the time BGP takes to converge, which is a simple, automatic failover.

SequenceAnycast sends each user to a nearby site
User in Paris
Paris edge
Tokyo edge
User in Osaka
  1. 1Paris announces 198.51.100.0/24 by BGP
    Paris edge to User in Paris: Paris announces 198.51.100.0/24 by BGP
  2. 2Tokyo announces the same prefix
    Tokyo edge to User in Osaka: Tokyo announces the same prefix
  3. 3Paris user connects to 198.51.100.7
    User in Paris to Paris edge: Paris user connects to 198.51.100.7
  4. 4Osaka user connects to 198.51.100.7
    User in Osaka to Tokyo edge: Osaka user connects to 198.51.100.7
  5. 5Each served by its nearest edge
    Tokyo edge to User in Osaka: Each served by its nearest edge

Absorbing attacks and updating content

Because anycast spreads traffic across all locations, a DDoS attack from bots worldwide is split into many smaller pieces, each handled by local capacity. Large CDNs have total network capacity in the hundreds of terabits per second, far more than any single origin. Edges also drop malformed packets and SYN floods, apply rate limits and web application firewall rules, and the origin's real IP stays hidden. Make sure the origin firewall accepts traffic only from the CDN's IP ranges, otherwise attackers can bypass it.

Updating cached content has two approaches. Purging tells the CDN to drop an object (or everything with a tag) so the next request fetches it fresh; it is fast on modern CDNs but is an extra step that can be forgotten. Versioned URLs change the file name whenever the content changes, so old and new never conflict and nothing needs purging. The usual pattern: short caching or no-cache for HTML, versioned names with long max-age for CSS, JS and images.

  • Restrict the origin to CDN IP ranges
  • Purge by URL or by cache tag when needed
  • Versioned asset names avoid purges entirely
  • Short TTL for HTML, long TTL for hashed assets

Learn it in 3 short steps

About 30m each. Track them with a timer in your plan.

  1. 1
    Explain edge caching and cache keys~30m
  2. 2
    Explain anycast routing~30m
  3. 3
    Read cache-control headers~30m

Key points

  • Cache-Control max-age and s-maxage decide how long edges keep content.
  • The cache key is usually the URL plus selected headers.
  • Purge or version URLs to update cached assets.

Key terms

Tap a card to flip it. 0/4 known

Examples

bash
curl -sI https://www.cloudflare.com | grep -iE 'cache-control|cf-cache-status|age'
dig +short www.cloudflare.com

Why is the hit ratio only 20 percent?

A news site behind a CDN still loads its origin heavily. Step 1: check headers on an article; it returns Cache-Control: private, so the CDN never stores it. Step 2: change the origin to send public, s-maxage=120 for articles. Step 3: the hit ratio rises but stays low; logs show many URLs with ?utm_ and ?fbclid parameters, each a different cache key. Step 4: configure the CDN to ignore those parameters in the cache key. The hit ratio climbs above 90 percent.

bash
curl -sI https://news.example.com/story/42 | grep -iE 'cache-control|age|cache-status|x-cache'
# Before: cache-control: private
# After:  cache-control: public, s-maxage=120, max-age=30
#         age: 47
#         x-cache: HIT

Shipping a new CSS file without stale pages

After a deploy, some users see the new HTML with the old CSS, so the layout breaks. Step 1: the CSS is called style.css with max-age=86400, so edges and browsers keep the old file for a day. Step 2: change the build to name files by content hash, such as style.8c1e2a.css, and reference that name in the HTML. Step 3: serve hashed files with max-age=31536000, immutable and HTML with no-cache. Step 4: each deploy now produces new names, and the HTML, revalidated on every visit, always points to the matching CSS.

text
# nginx at the origin
location ~* \.[0-9a-f]{6,}\.(css|js|png|svg|woff2)$ {
    add_header Cache-Control "public, max-age=31536000, immutable";
}
location / {
    add_header Cache-Control "no-cache";
}

Quick reference

  • Cache key: usually scheme + host + path + query; strip tracking parameters
  • s-maxage controls CDN caching; max-age controls browsers (and CDNs if no s-maxage)
  • no-cache = store but revalidate; no-store = never store
  • Hashed file names + max-age=31536000, immutable: cache forever, no purges
  • Age header shows how long the object has been in the cache
  • Vary: Accept-Encoding is fine; Vary: Cookie or User-Agent kills hit ratio
  • Anycast: same prefix announced by BGP from every site; nearest by routing wins
  • Lock the origin firewall to CDN IP ranges so attackers cannot bypass the CDN

Quick quiz

Pick an answer to see if you're right and why.

Question 1

1A response has Cache-Control: public, max-age=60, s-maxage=3600. How long may a CDN cache it?

Question 2

2What does Cache-Control: no-cache mean?

Question 3

3How does anycast send a user to a nearby CDN location?

Question 4

4Which change most improves the hit ratio when URLs carry many tracking parameters?

0/4 answered

Practice exercises

Try each one yourself first. Use the hint if you get stuck, then compare with the solution.

  1. Exercise 1easy

    Use curl to check whether a page on a CDN-backed site was served from cache, and how old the cached copy is.

  2. Exercise 2medium

    Write Cache-Control values for: a hashed JS bundle, a public product page that changes hourly, a user's account page, and a JSON price feed that may be 30 s stale.

  3. Exercise 3hard

    Explain, step by step, what happens to a long TCP download from an anycast address when a BGP route change sends the user's packets to a different CDN location mid-transfer, and how CDNs reduce the impact.

Check yourself

Answer in your head, reveal, then be honest with yourself.

Feel confident about this topic?

Frequently asked questions

Does a CDN help a dynamic website?
Yes. Even uncached pages benefit from TLS ending close to the user, reused connections to the origin and optimised routing. Static assets on the same site are fully cached.
How do I clear the CDN cache?
Use the CDN's purge feature, by URL, by tag or for everything. For assets, versioned file names avoid the need to purge at all.
Does using a CDN hurt SEO?
No. Faster pages generally help. Just make sure the CDN serves the same content and status codes as your origin and that redirects and canonical URLs are correct.
What is the difference between anycast and DNS-based load balancing?
Anycast uses one IP everywhere and lets BGP routing choose the site. DNS-based balancing returns different IPs to different users based on their resolver's location.

Go deeper

ShareXLinkedInWhatsApp