AlgoViz

Cloudflare CDN

medium 24 min

Cloudflare is a reverse proxy that runs in hundreds of cities behind the same anycast addresses.

Video lesson · Chapter 1 of 5

The same album cover in two cities

0:00 / 3:40

Cloudflare CDN in 75 seconds

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

Cloudflare CDN is a network of data centres that stands between visitors and your server. When you proxy a hostname through Cloudflare, its DNS name points at Cloudflare addresses, and every visitor talks to Cloudflare instead of to you. Cloudflare answers from its cache when it can and asks your server, the origin, when it cannot.

Two design choices make it different from many other networks. The same addresses are announced from every city, which is called anycast, so the internet's own routing brings each visitor to a nearby data centre. And every data centre runs every service: DNS, TLS, attack filtering, the cache, and your own code.

Why it exists

A page served from another continent spends most of its time travelling. A copy in a nearby city removes that journey and removes work from the origin at the same time. The general idea belongs to CDN; this page is about the product.

Because all traffic already passes through, it is also a natural place for security. An attack is spread over many data centres and dropped there, and the origin only sees requests that passed the checks.

A short history

  1. 2009

    Cloudflare is founded. The idea grew out of Project Honey Pot, which the founders had used to study the source of email spam since 2004.

  2. 27 September 2010

    Cloudflare launches in public at the TechCrunch Disrupt conference.

  3. 2024

    Cloudflare announces Instant Purge: tags, hostnames and prefixes are cleared worldwide in under 150 ms at the median, and promises those methods to every plan.

  4. 18 November 2025

    A configuration file used by Bot Management doubles in size and the proxy software fails on it. Customer sites show errors until core traffic recovers at 14:30 UTC.

Words to know

Origin
Your own server or bucket: the source of truth.
Data centre, or PoP
One Cloudflare site. It terminates TLS, filters, caches and runs code.
Anycast
One address announced from many places. Routing picks the place.
Zone
One domain and its settings in a Cloudflare account.
Cache key
What decides whether two requests get the same copy.
Edge TTL
How long Cloudflare keeps a copy. Browser TTL is a separate setting.
Upper tier
A data centre that others ask before anyone asks the origin.
Worker
Your JavaScript or WebAssembly code, run in every data centre.

How it works

Step through the idea, or press Play.

Step 1 of 3

Anycast brings the visitor. Every data centre announces the same addresses

Understand it

Start here

Stand number 7 in every town

A company lends umbrellas. Every town has one stand, and every stand has the same number: 7. Nobody looks up which town is closest. You open your umbrella, and the wind carries you to the nearest stand 7.

The umbrella stands
777Every stand has number 7

The wind follows the routes of the internet, which are usually but not always the shortest line on the map.

Why

What you get

  • Reach

    Cloudflare's network page lists 348 cities, and it reported passing 500 Tbps of external capacity.

  • Anycast routing

    One address everywhere. If a data centre leaves, routing moves visitors without a DNS change.

  • Security in the path

    DDoS protection at layers 3, 4 and 7 is unmetered on all plans. WAF and rate limiting rules run before the cache.

  • Low starting cost

    A free plan includes the CDN, DNS, certificates and DDoS protection. Add-ons such as Argo are metered.

  • Simple operations

    Most settings are a dashboard switch or an API call, and Terraform covers them all as code.

  • Code at the edge

    Workers run in every data centre, with KV, D1 and R2 for data.

Capacity figures are the total of all ports, not normal traffic. They matter because an attack has to be larger than what the network can absorb before it can reach you.

Path

The path of one request

Two cities, one upper tier, one origin

Users in Paris and Tokyo reach the Paris and Tokyo data centres inside the Cloudflare boundary over the same anycast address. Both ask one upper tier on a miss. The upper tier fetches from your origin server, which is outside Cloudflare.
Everything inside the dashed line is Cloudflare. Only the upper tier contacts the origin.
  1. 1

    Resolve the name

    A proxied DNS record returns Cloudflare's anycast addresses, not your server's address.

  2. 2

    Arrive

    BGP routes the packets to a nearby data centre. If that site disappears, the same address leads to another.

  3. 3

    Terminate TLS

    The data centre holds your certificate. Visitors can use TLS 1.3, HTTP/2 or HTTP/3. Free certificates are issued automatically.

  4. 4

    Filter

    DDoS rules, custom rules, rate limits and managed WAF rules run in that order. A blocked request never reaches the cache or the origin.

  5. 5

    Run your code

    A Worker on the route sits in front of the cache and may answer, rewrite or pass the request on.

  6. 6

    Look in the cache

    A hit is returned at once. A miss takes a lock, so one data centre sends one request per asset.

  7. 7

    Ask the upper tier, then the origin

    With Tiered Cache on, only an upper tier contacts the origin. Connections to the origin are kept open and reused.

  8. 8

    Store and deliver

    The response is cached on the way back, compressed if useful, and can be changed by rules or a Worker.

A miss, then a hit

Cache

What is cached, and for how long

Cloudflare decides by file extension, not by MIME type. Images, fonts, CSS, JavaScript, archives and similar files are eligible. HTML and JSON are not cached by default; add a cache rule for them. The origin's headers are respected unless a rule overrides them.

Defaults when the origin sends no cache header

StatusEdge TTL
200, 206, 301120 minutes
302, 30320 minutes
404, 4103 minutes
OthersNot cached
Requests other than GET, responses with Set-Cookie, and private or no-store responses are not cached by default.

Limits that differ by plan

FreeProBusinessEnterprise
Smallest Edge TTL in a rule2 hours1 hour1 second1 second
Largest cached file512 MB512 MB512 MB5 GB by default
Purge by tag, host, prefix, all5 a minute5 a second10 a second50 a second
Burst of those purges252550500
Tiered Cache, smart topologyYesYesYesYes
Regional and custom tiersNoNoNoYes
The smallest Edge TTL limits the override you set in a rule. Check the documentation before you rely on a number; plans change.

The cache key is the full URL plus a few headers by default. Cache rules can drop query strings or add headers and cookies. Too few parts and people see each other's pages; too many and almost nothing is shared. The theory is in cache TTL.

Will Cloudflare cache this?

A rule can also override the origin's headers; that branch is left out here.

Tiers

Tiered Cache protects the origin

Without tiers, every data centre that misses asks your origin. With tiers, lower data centres ask an upper tier, and only the upper tier asks the origin. It is available on every plan, and it helps most for long-tail files that each city requests rarely but the world requests often.

Requests that reach the origin

Ro=R (1−h1)(1−h2)100,000×0.10×0.30=3,000 per secondR_o = R\,(1-h_1)(1-h_2) \qquad 100{,}000 \times 0.10 \times 0.30 = 3{,}000 \text{ per second}
h1h_1 is the hit ratio in the nearby data centre and h2h_2 the ratio in the upper tier. The figures are an example: without the upper tier the origin would see 10,000.

Gains

  • Far fewer origin requests and connections
  • One city's miss fills the copy another city uses
  • A larger shared cache keeps rare files longer
  • Smart topology picks the best upper tier for your origin

Costs

  • A miss travels one hop more
  • Changing origin addresses can move the upper tier and cool the cache
  • An origin behind anycast hides its place; give a cloud region hint
  • Regional and custom topologies need Enterprise

Speed

Argo, HTTP/3 and images

FeatureWhat it doesWhen it pays
Argo Smart RoutingUses live network data to route requests around congestionVisitors far from the origin, dynamic requests
HTTP/3QUIC over UDP. A lost packet does not block other streamsMobile and lossy networks. Browsers fall back to HTTP/2
PolishStrips metadata and compresses images when they are fetchedImage-heavy sites
CompressionSends text in a compressed form the browser acceptsHTML, CSS, JavaScript, JSON
Argo is a paid, metered add-on. Measure your own traffic before and after. See HTTP/2 and HTTP/3.

Argo is like a navigation app that knows today's traffic jams: the destination is the same, but the road is chosen by how fast it is now.

Security

What happens before the cache

Inside one data centre

Inside one Cloudflare data centre, drawn as one thick box, a request from users passes attack filters, then WAF and rate limits, then a Worker, then the cache. On a miss it leaves the box for your origin.
A cache hit has still passed every security rule.

Layers of protection

  1. 1

    DDoS, layers 3 and 4

    Floods of packets are dropped automatically. In the fourth quarter of 2025 Cloudflare reported stopping an attack of 31.4 Tbps that lasted 35 seconds.

  2. 2

    DDoS, layer 7

    Floods of real HTTP requests are recognised and challenged or dropped. It is always on.

  3. 3

    WAF

    Managed rules look for common attacks such as SQL injection and cross-site scripting; your custom rules run before them.

  4. 4

    Rate limits and bots

    Rules count requests by address or other fields and block, challenge or log. See rate limiting.

  5. 5

    Magic Transit

    An Enterprise product that carries whole networks, not only HTTP, through the same filters.

Encryption modes

ModeVisitor to CloudflareCloudflare to origin
OffPlain HTTPPlain HTTP
FlexibleEncryptedPlain HTTP
FullEncryptedEncrypted, certificate not validated
Full (strict)EncryptedEncrypted and validated
Use Full (strict). Authenticated origin pulls also prove to the origin that the caller is Cloudflare. Newer zones use Automatic SSL/TLS, which picks the most secure mode your origin supports.

Code

Workers: your code in every data centre

A Worker is JavaScript or WebAssembly that handles a request. Workers run in isolates, light contexts inside one running process, so there is no container to boot for each customer. Use them for redirects, A/B tests, authentication, header changes, or a whole application.

Where a Worker keeps data

StoreShapeKnow this
Workers KVKey-value, read everywhereEventually consistent: a write may take 60 seconds or more to appear elsewhere
D1SQL database with SQLite semanticsReal queries for a site, user or tenant
R2S3-compatible object storageNo egress fees
Durable ObjectsOne object that owns its stateUse it when you need strong consistency
Limits at the time of writing: 128 MB of memory; 10 ms of CPU per request on the free plan; up to 5 minutes on the paid plan, 30 seconds by default.

A Worker in the path

CPU time counts only work. Waiting for a fetch or a KV read is not CPU time.

Change

Getting new content out

Choose how to update

MethodReachCost or risk
New file name, such as app.3f9a.jsCDN and browsersNone; needs a build step
Purge by URLCDN onlyThe recommended purge
Purge by tag, hostname or prefixCDN onlyAll plans; rate-limited by a token bucket
Purge everythingCDN onlyThe whole site must be fetched again from the origin
InvalidateCDN onlyMarks copies stale; unchanged files are revalidated, not downloaded again
Cloudflare reports a median under 150 ms for worldwide tag, host and prefix purges. More in CDN invalidation.

How many purges fit in a burst

n(t)=min⁡(B,;tokens left)+r tB=25,;r=5/min:n(2 min)=25+10=35n(t) = \min(B,; \text{tokens left}) + r\,t \qquad B = 25,; r = 5/\text{min}:\quad n(2\text{ min}) = 25 + 10 = 35
The free plan's bucket: 25 at once when full, then 5 a minute. One request can carry up to 100 operations, so batch them.

Failure

When something breaks

Read the signs

SignMeaningLook at
cf-cache-status: DYNAMICNot eligible for cacheExtension and cache rules
BYPASSEligible, but a header or cookie refused itSet-Cookie, private, no-store
EXPIRED, REVALIDATEDCopy was old; the origin was askedTTL and ETags
STALE, UPDATINGAn old copy was servedOrigin health, stale rules
Error 522No TCP connection in time, about 19 secondsFirewall, origin down
Error 524Connected, but no answer in 125 secondsSlow work; make it asynchronous
cf-rayIdentifier of this requestQuote it to support

Origin down. Cloudflare can serve stale copies. With Always Online it can also fall back to the Internet Archive, when you switch it on: only popular pages, crawled every 5 to 30 days depending on plan, with a banner. It does not save dynamic pages. Cloudflare's load balancer can move traffic between several origins.

Cloudflare down. On 18 November 2025 an oversized configuration file stopped the proxies from handling traffic, and on 5 December 2025 a change affected customers with about 28% of the HTTP traffic for about 25 minutes. Anycast does not help when the same software fails everywhere. Decide in advance: accept it, or keep a second CDN or a way to point DNS elsewhere, and know that going around the CDN also removes its protection.

Decide

When to choose it

Choose it when

  • You want a CDN and security that start simply and free
  • Origins are in several clouds or your own building
  • The site is global and mostly cacheable
  • You want security and code in the same place
  • APIs need short TTLs and better routes
  • Live video needs worldwide ingest and delivery

Think again when

  • Every response is personal and nothing is cacheable (it may still help with TLS and security)
  • All users sit next to the origin
  • Everything is in AWS and you want its access control and free origin transfer
  • Readers must never see an old value
  • You need control over each cached entry that rules cannot give
  • A policy forbids a third party from decrypting traffic

Compared with others

NetworkClosest inDiffers inChoose it for
Amazon CloudFrontEdge cache, functions, WAF, HTTP/3DNS picks the location; Origin Shield instead of Tiered Cache; tied to AWSOrigins in AWS
FastlyEdge cache, code at the edge, fast purgeConfigured in VCL; fewer, larger sitesFine control of caching in code
AkamaiReach, media, securityVery many small sites; enterprise salesLarge media and enterprise support
Google Cloud CDNAnycast, cacheAttached to Google's load balancerOrigins in Google Cloud
For choosing between products in general, see CDN design.
Text
resource "cloudflare_zone" "site" {  account = { id = var.account_id }  name    = "example.com"  type    = "full"}resource "cloudflare_dns_record" "www" {  zone_id = cloudflare_zone.site.id  name    = "www.example.com"  type    = "CNAME"  content = "origin.example.net"  ttl     = 1        # automatic  proxied = true     # traffic goes through Cloudflare}resource "cloudflare_ruleset" "cache" {  zone_id = cloudflare_zone.site.id  name    = "Cache rules"  kind    = "zone"  phase   = "http_request_cache_settings"  rules = [{    expression = "starts_with(http.request.uri.path, \"/static/\")"    action     = "set_cache_settings"    action_parameters = {      cache       = true      edge_ttl    = { mode = "override_origin", default = 86400 }      browser_ttl = { mode = "override_origin", default = 3600 }    }  }]}
Infrastructure as code (Terraform provider 5)

Summary

The whole topic in one minute.

Cloudflare is an anycast reverse proxy. A visitor reaches a nearby data centre, passes the security rules, then Workers, then the cache. A miss goes to an upper tier and only then to the origin, and simultaneous misses in one data centre are collapsed into one.

By default it caches a list of static file extensions and not HTML or JSON, so write cache rules. Prefer versioned URLs to purging, use Full (strict) encryption, remember that a purge never reaches a browser, and have a plan for the day the provider itself fails.

  • Anycast: the same addresses everywhere, routing chooses the data centre.
  • Every data centre runs DNS, TLS, filters, cache and Workers.
  • Security runs before the cache; a hit was still checked.
  • HTML and JSON are not cached until a rule says so.
  • Tiered Cache and the cache lock turn many misses into one origin request.
  • Version file names; a purge does not reach browsers.
  • Full (strict) encryption, a hidden origin, and a plan for the provider's bad day.

Sources