Skip to main content

Cloudflare System Design: CDN, DNS, Caching and DDoS Protection Explained

Calculating read time…

Right now, as you read this, Cloudflare is handling more than 50 million HTTP requests every single second. It is silently protecting tens of millions of websites, blocking attacks, serving cached content, and making the web faster for billions of people — all at the same time.

And here's the mind-blowing part: most people have never heard of it. It works completely invisibly. Every time you visit a popular website, there is a very good chance Cloudflare is sitting between you and that website — doing an incredible amount of work in milliseconds — and you have absolutely no idea.

Today we are going to lift the curtain completely. By the end of this post you will understand exactly how Cloudflare works, from a single DNS lookup all the way to blocking a 2.5 Tbps DDoS attack.

💡 Cloudflare by the Numbers — 2026

🌐 300+ data centers (PoPs) in 100+ countries
⚡ Handles 50 million+ HTTP requests per second
🛡️ Blocks 209 billion cyber threats per day on average
🏎️ Cloudflare's DNS 1.1.1.1 is the world's fastest public DNS resolver
💡 Powers websites for 20%+ of all internet traffic
📦 Largest DDoS attack ever mitigated: 5.6 Tbps (November 2024)
🧑‍💻 Cloudflare Workers: serverless code running in 300+ cities simultaneously

Cloudflare is not just a CDN — it is the world's largest network built to make the internet faster, safer, and more reliable for everyone.

🕵️ Section 1: Think of Cloudflare Like a Celebrity's Entire Security Team

Imagine a famous celebrity (your website) who receives millions of letters, phone calls, and visitor requests every day. Without help, they'd be overwhelmed.

So they hire a full security and logistics team that sits between them and the world. That team does everything: checks who's a genuine fan, blocks threatening strangers, sorts mail efficiently, keeps frequently-asked questions answered without disturbing the celebrity, and ensures VIP guests get in quickly.

Cloudflare is that entire security and logistics team for your website. Your website (origin server) sits safely behind Cloudflare. The outside world interacts with Cloudflare. Only clean, legitimate traffic ever reaches your actual server.

🕵️ Celebrity Security Team ☁️ Cloudflare Service 🔧 Engineering Concept
Front gate that checks everyone's ID Request inspection on every HTTP call Web Application Firewall (WAF)
Bodyguard absorbs an angry mob Absorbing a 5 Tbps DDoS flood DDoS Mitigation
FAQ pamphlet answers common questions Serving cached pages without hitting origin Edge Cache
Branch offices near every city 300+ data centers worldwide Points of Presence (PoPs)
Fastest route mapped for every visitor Intelligent routing across internet paths Argo Smart Routing
Detecting robots vs real humans at the door Separating bot traffic from real users Bot Management

🎯 Section 2: What Does Cloudflare Actually Do? — The Six Pillars

Cloudflare is many things at once. Let's establish the six core pillars of what Cloudflare does before we go deep on any single one.

🌐
1. CDN (Content Delivery)

Caches your website's static content (images, CSS, JS) across 300+ data centers worldwide. Visitors get content from the nearest location — dramatically faster load times.

🛡️
2. DDoS Protection

Absorbs and drops malicious flood traffic before it reaches your server. Cloudflare's network capacity (321 Tbps+) is so large that even the biggest attacks are a drop in the ocean.

🔒
3. SSL / TLS Encryption

Provides free HTTPS certificates. Terminates SSL at the edge (close to the user) and uses optimised connections to your origin. Makes the web encrypted by default.

🧱
4. Web Application Firewall

Inspects every incoming HTTP request for malicious patterns — SQL injection, cross-site scripting, OWASP Top 10 threats. Bad requests are blocked before they touch your server.

📡
5. DNS Resolution (1.1.1.1)

The world's fastest public DNS resolver. Also provides authoritative DNS for websites using Cloudflare — the fastest DNS in the industry with sub-millisecond propagation.

⚡
6. Edge Computing (Workers)

Run your own JavaScript/TypeScript/Wasm code at 300+ edge locations. Zero cold starts. Sub-millisecond response. Closer to your users than any traditional cloud server ever could be.


🌐 Section 3: Anycast — How One IP Address Reaches 300+ Cities

This is Cloudflare's most foundational and most genius engineering decision. Understanding Anycast unlocks everything else.

💡 The Emergency Services Analogy

When you call emergency services (112 or 911), you dial the same number no matter where you are in the country. But you don't get connected to a call centre in a different city — you get connected to the nearest emergency station automatically. The phone network routes you there based on where you're calling from.

Anycast works exactly the same way for internet traffic. Cloudflare advertises the same IP address from all 300+ of its data centers. When your computer sends a request to that IP, the internet's routing system (BGP — Border Gateway Protocol) automatically sends it to the geographically closest Cloudflare data center. You always get served by the nearest one. Automatically. Instantly.

🌐 Unicast vs Anycast — A Visual Comparison

❌ Unicast (Regular Hosting)

🇮🇳 User in Mumbai → 108.162.x.x
🇧🇷 User in São Paulo → 108.162.x.x
🇯🇵 User in Tokyo → 108.162.x.x
⬇️ ALL go to ONE server
🖥️ Single Server — New York

😩 Tokyo user waits 200ms. Mumbai user waits 180ms.

✅ Anycast (Cloudflare's Way)

🇮🇳 User in Mumbai → 108.162.x.x
🇧🇷 User in São Paulo → 108.162.x.x
🇯🇵 User in Tokyo → 108.162.x.x
⬇️ Each reaches NEAREST server!
📦 Mumbai PoP
📦 Brazil PoP
📦 Tokyo PoP

🚀 All users get <10ms! Same IP. Different server.

📡  Your Request Flying to the Nearest Cloudflare PoP

🇮🇳 Mumbai User
📦
🏢 Mumbai PoP (5ms!)
🇯🇵 Tokyo User
📦
🏢 Tokyo PoP (4ms!)
🇺🇸 New York User
📦
🏢 NYC PoP (3ms!)

↑ All three users send to the SAME Cloudflare IP address — but each reaches their nearest data center. This is Anycast magic! ✨

✅ Why Anycast is Also the World's Best DDoS Defence:

When a DDoS attack floods Cloudflare with traffic, Anycast spreads that attack across ALL 300+ data centers simultaneously. Instead of one server getting hit with 5 Tbps, each of 300 data centers absorbs about 17 Gbps — completely manageable for each one. The attacker's flood is diluted across the entire planet! 🌍

📡 Section 4: DNS — How Every Request to Your Website Starts

Before any HTTP request reaches Cloudflare, something else happens first: DNS lookup. This is the very first step every single time you visit a website. Let's understand it.

💡 The Phone Book Analogy

The internet speaks in IP addresses (numbers like 104.21.45.67). But humans type domain names (like www.example.com). DNS is the phone book that translates names → numbers.

Every time you type a website address, your computer secretly asks a DNS resolver: "What is the IP address of www.example.com?" Only after getting the answer can it connect to the website.

📡 DNS Resolution Flow — What Happens Before You Even Connect

Step 1 — You type "www.example.com" in your browser
Your browser checks its own cache first. Not there → asks your OS. Not there → asks your configured DNS resolver.
⬇️
Step 2 — Your DNS Resolver asks Cloudflare 1.1.1.1
If you use Cloudflare's public DNS resolver (1.1.1.1), your resolver asks it: "What's the IP for www.example.com?" Cloudflare's 1.1.1.1 is the fastest resolver in the world — average response: 11ms (Google's 8.8.8.8: ~20ms, ISP resolvers: 50–100ms).
⬇️
Step 3 — Authoritative DNS Response (from Cloudflare's DNS)
If the website is using Cloudflare, the answer comes from Cloudflare's own authoritative DNS — the fastest in the industry. Cloudflare stores DNS records in memory across all 300+ PoPs. Updates propagate globally in under 5 seconds (traditional DNS takes 24–48 hours!).
⬇️
Step 4 — Response: "example.com is at 104.21.45.67" (a Cloudflare IP!)
The DNS response doesn't give you your origin server's real IP. It gives you a Cloudflare IP address. This is how Cloudflare sits in the middle — the world connects to Cloudflare, not directly to your server. Your server's real IP is hidden!
⬇️
Step 5 — Browser now connects to 104.21.45.67 (Cloudflare's nearest PoP)
Thanks to Anycast, this IP routes your browser to the nearest Cloudflare data center. Now the actual request handling begins!

🏢 Section 5: Inside a Cloudflare Edge PoP — The Journey of One Request

Your HTTP request has arrived at the nearest Cloudflare PoP (Point of Presence). What happens inside? Your request passes through a pipeline of checks, each one in milliseconds, before getting a response.

🏢 The Cloudflare Edge Pipeline — Every Step Your Request Goes Through

1
TLS Termination (SSL Handshake)
Your browser wants to connect over HTTPS. Cloudflare performs the TLS handshake at the edge — close to you — in ~20ms. If TLS was done at your origin server (thousands of km away), this handshake alone could take 200ms+. Terminating at the edge is a huge speed win.
⬇️
2
🛡️ DDoS Layer 3/4 Filtering (IP & TCP/UDP level)
Before even looking at HTTP content, Cloudflare checks the network layer. Is this IP on a known attacker list? Is the request rate abnormally high? Is this a SYN flood or UDP amplification attack? Malicious packets are dropped here instantly — without any CPU used on your origin.
⬇️
3
🧱 WAF (Web Application Firewall) — Layer 7 Inspection
Now Cloudflare reads the actual HTTP request content. Does the URL contain a SQL injection attempt? Is the POST body trying an XSS attack? Does this match any known exploit pattern? Cloudflare's WAF has 65,000+ rules updated constantly from global threat intelligence. Bad requests → blocked. Clean requests → continue.
⬇️
4
🤖 Bot Management — Human or Machine?
Is this request from a real human browser or an automated bot? Cloudflare uses machine learning to analyse 100+ signals: browser fingerprint, mouse movement patterns, typing cadence, request timing, IP reputation. Good bots (Googlebot) are allowed. Bad bots (scrapers, credential stuffers) → challenged or blocked.
⬇️
5
🚦 Rate Limiting — Too Many Requests?
Has this IP or user made too many requests in the last minute? If an IP hits /login 1,000 times in a minute — that's clearly a brute-force attack. Cloudflare rate limiting blocks it with a 429 response. Your server never even knows it happened.
⬇️
6
📦 Cache Check — Do We Already Have This Response?
Can this request be answered from Cloudflare's edge cache? A CACHE HIT means the response is returned instantly from the edge — your origin server is never contacted! This is the biggest performance win. A CACHE MISS means Cloudflare must forward to your origin server.
⬇️ (only on cache miss)
7
🖥️ Forward to Origin Server (Over Argo Smart Route)
If the content isn't cached, Cloudflare forwards the request to your real server. But it doesn't use the regular internet — it uses Argo Smart Routing, which picks the fastest private internet path, avoiding congested routes. The response comes back, Cloudflare caches it and returns it to the user.

🛡️ Section 6: DDoS Protection — Absorbing the World's Biggest Attacks

A DDoS (Distributed Denial of Service) attack is when a bad actor sends so much fake traffic to your website that legitimate users can't get through. Think of a mob blocking the entrance of a shop so real customers can't enter.

Cloudflare's DDoS protection is the most comprehensive on Earth. Let's understand why.

🌊
Layer 3/4 Volumetric Attacks (Flood Attacks)

Sending massive amounts of raw data packets (UDP floods, ICMP floods, SYN floods) to overwhelm the target's bandwidth or connection table. Cloudflare's 321 Tbps+ network capacity means even a 5 Tbps attack is only 1.5% of Cloudflare's total capacity. The attack is simply absorbed.

🎯
Layer 7 Application Attacks (Smart Attacks)

These are more sophisticated. Attackers send seemingly normal HTTP requests that overwhelm your application logic (e.g., hitting a complex database query endpoint millions of times per second). Much harder to detect because each request looks legitimate. Cloudflare uses ML and behaviour analysis to identify these.

🔀
Amplification Attacks (DNS/NTP Reflection)

Attacker sends a small request to a third party (e.g., DNS server) but spoofs the victim's IP. The third party sends a massive response to the victim. Small input → huge amplified output. Cloudflare detects the forged IP patterns and drops the amplified packets at the network edge before they cause damage.

🛡️ Animated: How Cloudflare Absorbs a DDoS Attack

💀 Bot 1
2Gbps
💀 Bot 2
1.5Gbps
💀 Bot 3
3Gbps
💀 500K more bots...
5 Tbps flood!
➡️
🛡️ CLOUDFLARE
321 Tbps capacity
Attack is 1.5% of capacity
⚡ Absorbed instantly
Clean traffic only!
➡️
🖥️ Your Server
100% healthy
Sees nothing! 😌
💡 Cloudflare's Largest DDoS Attack Ever (November 2024)

In November 2024, Cloudflare mitigated a record-breaking 5.6 Tbps DDoS attack. It lasted 80 seconds and involved over 13,000 compromised IoT devices worldwide (a Mirai botnet variant).

Cloudflare's automated systems detected and mitigated it in under 1 second. No human intervention. No downtime. The targeted customer didn't even notice. 🎯

🧱 Section 7: The WAF — Cloudflare's Content Security Scanner

While DDoS protection handles volume attacks, the WAF handles smart attacks — malicious HTTP requests that try to exploit vulnerabilities in your web application.

💡 The Airport Security Analogy

At an airport, security doesn't just count how many passengers arrive (volume). They check what each passenger is carrying (content) using X-ray machines and metal detectors. Even if only one passenger out of a million is a threat — they catch them.

The WAF is exactly this. It X-rays every HTTP request for dangerous content — no matter how legitimate the source might appear.
🎯 Attack Type 🧨 What the Attacker Does 🛡️ How WAF Blocks It
SQL Injection Injects SQL code into a form field to steal your database Detects '; DROP TABLE, OR 1=1 patterns → block
XSS Injects JavaScript into your page to steal cookies Detects <script>, javascript: in inputs → block
Path Traversal Tries to access ../../etc/passwd to read system files Detects ../ traversal patterns in URL → block
RCE Sends commands that your server executes (Log4Shell, etc) Detects known exploit signatures → block in hours of discovery
Credential Stuffing Tries millions of username/password combinations Rate limiting + bot score + CAPTCHA challenge
✅ How Cloudflare Updates WAF Rules Globally in Hours (Not Weeks)

When a new vulnerability is discovered (like Log4Shell in December 2021), Cloudflare typically deploys a WAF rule to all 300+ data centers within a few hours — often before most companies even know they're vulnerable.

By the time you patch your own application, Cloudflare has already been blocking exploit attempts against you for days. This is the power of a global network with centralised security intelligence. 🔐

📦 Section 8: Edge Caching — Serving Content Without Touching Your Server

Every Cloudflare PoP has its own local cache. When a user requests a file that's already been cached at their nearest PoP — your origin server is never contacted. The response comes directly from the edge — ultra-fast.

📦 Cache HIT vs MISS — The Two Paths

✅ Cache HIT (Fast! ~5ms)

👤 User requests /logo.png
↓
📦 Cache: "I have this!" ✅
↓
🚀 Response in ~5ms. Origin: never called.
Header: CF-Cache-Status: HIT

⚠️ Cache MISS (First Request ~80ms)

👤 User requests /new-page.html
↓
📦 Cache: "Don't have it" ❌
↓ fetch from origin
🖥️ Origin server responds (50ms)
↓ cache + return
Header: CF-Cache-Status: MISS
(Next request will be HIT!)

⚙️ What Gets Cached? What Doesn't?

✅ Cloudflare DOES Cache
🖼️ Images (.jpg, .png, .webp, .svg)
🎨 CSS and JavaScript files
🎬 Video files (.mp4, .webm)
📄 Static HTML pages
📦 Download files (.pdf, .zip)
❌ Cloudflare Does NOT Cache (By Default)
🔐 Authenticated/personalised pages
🛒 Shopping cart / checkout pages
📊 API responses (dynamic data)
📝 POST requests (form submissions)
🍪 Pages with session cookies set

⚡ Section 9: Cloudflare Workers — Serverless Code at the Edge

Cloudflare Workers is one of the most revolutionary products in modern cloud computing. It lets you run your own code at every one of Cloudflare's 300+ data centers simultaneously — without managing any servers, with zero cold starts, and in under 1ms latency.

💡 The On-Demand Chef Analogy

Traditional cloud functions (AWS Lambda) are like ordering from a restaurant. Sometimes the kitchen is cold — you wait 200–500ms for it to warm up before your food is even started (this is the "cold start" problem).

Cloudflare Workers is like having a personal chef in every city in the world. The moment you order (request arrives), cooking starts instantly — no warming up, no delay. Because there are 300+ chefs globally, one is always ready near you.
Feature ⚡ Cloudflare Workers 🔶 AWS Lambda
Cold Start ~0ms (none!) 100–500ms
Execution Locations 300+ cities globally One region per function
Latency to User < 10ms (edge) 50–200ms (central DC)
Runtime V8 isolates (JS/TS/Wasm/Python) Containers (any language)
CPU Limit per Request 30s CPU time 15 minutes
💡 How Workers Achieves Zero Cold Starts — V8 Isolates

AWS Lambda spins up a full container (like a mini virtual machine) for each function instance. Starting a container takes 100–500ms.

Cloudflare Workers uses V8 Isolates — the same technology that runs JavaScript in Chrome. An isolate is incredibly lightweight (microseconds to start, kilobytes of memory). Thousands of isolates run simultaneously inside one Workers process. Each request gets its own isolate, completely isolated from others — but starting it takes essentially zero time. 🚀

🔒 Section 10: SSL/TLS — How Cloudflare Makes the Web Encrypted

When you see the padlock 🔒 in your browser, that means the connection is encrypted. Cloudflare has been one of the biggest forces in making HTTPS the default for the entire web.

🔒 Cloudflare's SSL Architecture — Two Separate Encrypted Connections

📱 Your Browser
Sends HTTPS request
🔒 TLS 1.3
(User ↔ CF)
➡️
🛡️ Cloudflare Edge
Terminates SSL
Inspects request
Re-encrypts
🔒 TLS (CF ↔ Origin)
(kept encrypted)
➡️
🖥️ Your Origin
Server
(Real IP hidden)

TLS is terminated at the edge (near the user) — dramatically faster TLS handshake. The connection to your origin is separately encrypted. Two TLS sessions, not one long one.

Cloudflare also introduced Universal SSL in 2014 — free HTTPS certificates for every website on Cloudflare. Before this, certificates cost $100–$300 per year. This single move helped encrypt a huge portion of the web overnight.

Cloudflare also pioneered TLS 1.3 adoption and Encrypted Client Hello (ECH) — which hides even which website you're connecting to from your ISP. Privacy at the protocol level. 🔐


🗺️ Section 11: Argo Smart Routing — The Private Fast Lane of the Internet

The regular internet is like a network of public roads — sometimes congested, sometimes slow, with unpredictable delays. Argo Smart Routing gives Cloudflare a network of private express highways.

💡 How Argo Works

Cloudflare has 300+ data centers connected by its own private backbone. When a request needs to reach your origin server, instead of going through unpredictable public internet routers (which might be congested in Frankfurt today, or slow through a Pacific cable), Cloudflare routes it through its own private inter-PoP network, picking the fastest path in real time based on current measured congestion data.

Result: 30% faster average response times and 60% reduction in connection errors compared to standard routing.

🗺️ Standard Internet Routing vs Argo Smart Routing

❌ Public Internet (Unpredictable)
📍 Cloudflare Edge (Mumbai)
↓ Hop 1: ISP router (Mumbai) — 5ms
↓ Hop 2: Transit provider — 12ms
↓ Hop 3: Congested backbone — 45ms ⚠️
↓ Hop 4: Another ISP — 8ms
↓ Hop 5: Origin Server (Singapore)
Total: ~80ms (unpredictable!)
✅ Argo Smart Route (Cloudflare Private Network)
📍 Cloudflare Edge (Mumbai)
↓ Cloudflare private link: 4ms
↓ Cloudflare Singapore PoP: 8ms
↓ Direct peering to Origin: 3ms
Total: ~15ms (30–60% faster!) 🚀

💻 Section 12: A Peek at the Code — Real Cloudflare Examples

Let's look at real-world code that uses Cloudflare's actual APIs. Cloudflare Workers uses standard Web APIs, so the code is clean and readable.

📌 What This Code Does (Read Before The Code!)

This is a Cloudflare Worker — a tiny JavaScript function that runs at every one of Cloudflare's 300+ data centers whenever a request comes in. This specific example does something very common: it intercepts every incoming request and checks if the URL contains an old path (like /old-blog) that needs to be redirected to a new URL (/new-blog). Instead of your server doing this redirect work, the Cloudflare edge handles it instantly — your origin server is never involved. This is called an edge redirect and it reduces load on your server while being faster for the user.

	// Cloudflare Worker — Smart URL Redirector at the Edge
	// This runs in 300+ cities simultaneously, no server management needed!

	// The 'fetch' event fires on every incoming HTTP request
	addEventListener('fetch', event => {
	  event.respondWith(handleRequest(event.request))
	})

	// Define your redirects — old URL → new URL
	const REDIRECTS = {
	  '/old-blog':          '/new-blog',
	  '/old-product':       '/products/latest',
	  '/download/v1':       '/download/v3',
	}

	async function handleRequest(request) {
	  const url = new URL(request.url)

	  // Step 1: Check if this path needs a redirect
	  const newPath = REDIRECTS[url.pathname]
	  if (newPath) {
		// Return a 301 Permanent Redirect immediately — origin server never called!
		// This response comes from the edge, <5ms from the user.
		return Response.redirect(
		  `${url.origin}${newPath}`,
		  301
		)
	  }

	  // Step 2: Not a redirect → forward to origin normally
	  return fetch(request)
	}
	
📌 What This Code Does (Read Before The Code!)

This Worker acts like a custom security layer — similar to a mini WAF. It inspects every incoming request for two specific security threats: (1) SQL injection patterns in the URL query string (e.g., someone trying to add OR 1=1 to your search form to trick your database), and (2) whether the request comes from a country you want to block. Any suspicious request is blocked with a 403 Forbidden response before it even comes close to your server. This is the power of edge security — threats are eliminated as close to their source as possible.

	// Custom Security Worker — Blocks SQL Injection + Geo-Blocking at the Edge

	addEventListener('fetch', event => {
	  event.respondWith(handleRequest(event.request))
	})

	// SQL injection patterns to watch for in URLs and query strings
	const SQL_INJECTION_PATTERNS = [
	  /(\bOR\b|\bAND\b)\s+[\d'"]+=[\d'"]+/i,    // OR 1=1, AND 'a'='a'
	  /UNION\s+(ALL\s+)?SELECT/i,              // UNION SELECT attacks
	  /DROP\s+TABLE/i,                          // DROP TABLE attempts
	  /;\s*--/,                                 // SQL comment injection
	]

	// Countries to block (ISO codes) — example: known high-abuse regions
	const BLOCKED_COUNTRIES = ['XX', 'YY']  // Replace with real codes

	async function handleRequest(request) {
	  const url = new URL(request.url)

	  // Check 1: Geo-blocking — Cloudflare tells us visitor's country!
	  const country = request.cf?.country  // e.g. "IN", "US", "DE"
	  if (BLOCKED_COUNTRIES.includes(country)) {
		return new Response('Access denied from your region.', {
		  status: 403,
		  headers: { 'Content-Type': 'text/plain' }
		})
	  }

	  // Check 2: SQL Injection scan on the full URL
	  const fullUrl = url.href
	  for (const pattern of SQL_INJECTION_PATTERNS) {
		if (pattern.test(fullUrl)) {
		  // Log the attack (to Cloudflare Logpush) then block it
		  console.log(`🚨 SQL Injection attempt from ${request.headers.get('CF-Connecting-IP')}: ${fullUrl}`)
		  return new Response('Request blocked by security policy.', { status: 403 })
		}
	  }

	  // All checks passed → forward cleanly to origin
	  return fetch(request)
	}
	
📌 What This Code Does (Read Before The Code!)

This is a custom rate limiter built with Cloudflare Workers + KV. KV (Key-Value) is Cloudflare's globally distributed storage available to Workers. This code tracks how many times each IP address has hit the /api/ endpoint in the last 60 seconds. If they go over 100 requests in that window, they get a 429 "Too Many Requests" response. The counter is stored in Cloudflare KV — which is globally replicated, so even if a user bounces between different Cloudflare PoPs, their counter is consistent. Your origin server is protected without writing a single line on your own backend!

	// Rate Limiter using Cloudflare Workers + KV Storage
	// KV is Cloudflare's globally distributed key-value store — always close to the user

	const RATE_LIMIT     = 100   // max requests allowed
	const WINDOW_SECONDS = 60    // time window in seconds

	addEventListener('fetch', event => {
	  event.respondWith(handleRequest(event.request))
	})

	async function handleRequest(request) {
	  const url = new URL(request.url)

	  // Only rate-limit API endpoints (/api/*)
	  if (!url.pathname.startsWith('/api/')) {
		return fetch(request)  // non-API routes pass through freely
	  }

	  // Identify the caller — Cloudflare provides real IP even behind proxies
	  const ip  = request.headers.get('CF-Connecting-IP')
	  const key = `ratelimit:${ip}:${Math.floor(Date.now() / 1000 / WINDOW_SECONDS)}`

	  // Read current request count from KV (global, millisecond latency)
	  const current = parseInt((await RATE_LIMIT_KV.get(key)) || '0')

	  if (current >= RATE_LIMIT) {
		// Over the limit → block immediately at the edge
		return new Response(
		  JSON.stringify({ error: 'Rate limit exceeded. Try again in 60 seconds.' }),
		  {
			status:  429,
			headers: {
			  'Content-Type':    'application/json',
			  'Retry-After':     '60',
			  'X-RateLimit-Limit':     `${RATE_LIMIT}`,
			  'X-RateLimit-Remaining': '0',
			}
		  }
		)
	  }

	  // Under the limit → increment counter and forward the request
	  await RATE_LIMIT_KV.put(key, String(current + 1), { expirationTtl: WINDOW_SECONDS })
	  return fetch(request)  // clean request goes to origin
	}
	
✅ Notice request.cf — Cloudflare's Gift to Developers

Every request inside a Cloudflare Worker has access to a special request.cf object that contains amazing metadata: the user's country, city, latitude/longitude, ASN (internet provider), threat score, whether TLS 1.3 is in use, and more.

This means you can build geo-targeting, personalisation, and security logic at the edge — without ANY backend code — using data Cloudflare already has. 🎁

📈 Section 13: Scalability — How Cloudflare Handles 50M Requests/Second

🌐 1. Anycast = Natural Load Distribution

50 million requests per second sounds impossible for any single system. But with Anycast, those 50M requests are naturally distributed to the nearest of 300+ PoPs. Each PoP handles only its local share. A popular website going viral in India hits the India PoPs — not the USA or Europe. Geography itself becomes the load balancer.

📦 2. Cache Everything Possible

The majority of requests for a typical website can be answered from cache. A cached response costs Cloudflare microseconds of compute — no database queries, no dynamic logic. By caching aggressively, Cloudflare's effective request capacity per PoP is multiplied many times over.

⚡ 3. V8 Isolates — 10,000x More Efficient Than Containers

For dynamic requests handled by Workers, V8 Isolates pack thousands of concurrent function executions into a single process using microtenths of memory per isolate. One physical server can run hundreds of thousands of Workers simultaneously — impossible with traditional container-based serverless.

🔄 4. Stateless Edge Servers

Every Cloudflare edge server is stateless — all persistent state lives in distributed stores (Cloudflare KV, Durable Objects, R2). This means any edge server can handle any request. Adding more capacity is as simple as adding more machines to any PoP — no session migration, no coordination complexity.

🧠 5. Threat Intelligence Gets Smarter at Scale

When Cloudflare sees an attack pattern on one customer's traffic, it immediately updates its WAF rules for all 20+ million customers. The network's scale creates a virtuous loop: more traffic → more threat data → smarter protection → safer for everyone. Cloudflare calls this the "network effect of security".


🛡️ Section 14: Reliability — Why Cloudflare Almost Never Goes Down

🌍 300+ Independent PoPs

Each Cloudflare data center operates independently. If an entire data center goes offline (hardware failure, ISP outage, power loss), Anycast automatically re-routes traffic to the next nearest PoP — typically within seconds. Users might experience a brief slowdown. Total outage: almost never.

📦 Redundant Hardware at Every PoP

Every PoP runs multiple servers in parallel. No single server handles a PoP alone. If one server fails within a PoP, the load balancer within the PoP shifts traffic to the remaining servers instantly. Hardware failures are routine and handled automatically.

🔄 No Single Point of Failure by Design

Cloudflare's control plane (the system that manages configuration and routes) is itself distributed and resilient. Even if Cloudflare's own management systems have issues, the edge servers continue to operate from their last-known-good configuration. The data plane runs independently from the control plane.

📊 Real-Time Global Monitoring

Cloudflare runs continuous synthetic probes to every PoP, every minute. Any PoP that becomes unhealthy is automatically removed from the Anycast routing table and traffic is re-routed. Response time: typically under 60 seconds from failure to re-route.


🗺️ Section 15: Everything Together — Complete Cloudflare Architecture

☁️ Cloudflare — Complete Architecture Map

── VISITORS FROM EVERYWHERE ──
🇮🇳 India
🇺🇸 USA
🇩🇪 Germany
🇯🇵 Japan
🇧🇷 Brazil
⬇️ Anycast → Nearest PoP
🏢 Cloudflare Edge PoP (300+ worldwide — this is what each one does)
🔒 TLS Termination (SSL Handshake at the Edge)
🛡️ DDoS L3/L4 Filtering (Drop attack packets instantly)
🧱 WAF (65,000+ rules — SQL Injection, XSS, OWASP Top 10)
🤖 Bot Management (ML-based human vs bot detection)
🚦 Rate Limiter (Token bucket per IP/API key)
📦 Edge Cache (Serve static content — origin never called!)
⚡ Workers (Run your JS code here, sub-millisecond)
⬇️ Only on cache miss — via Argo Smart Route
🗺️ Argo Smart Routing
Cloudflare private backbone — fastest path to origin
⬇️
🖥️ Your Origin Server
Only sees clean, legitimate, inspected traffic.
Real IP hidden behind Cloudflare.

📐 Section 16: Cloudflare's Core Design Principles

🌐 Edge-First, Always

Every Cloudflare product is designed to execute at the edge — as close to the user as physically possible. Whether it's TLS termination, WAF inspection, caching, or Workers code — it all happens at the PoP nearest the user. This is not just faster. It also means threats are stopped before they consume backbone bandwidth.

🛡️ Security as a Side Effect of Scale

Cloudflare's network capacity (321+ Tbps) exists primarily to serve content fast. But that same capacity makes DDoS attacks trivially absorbable. The infrastructure built for performance provides security as a free bonus. This is a rare and powerful property — building one thing exceptionally well that solves two different problems simultaneously.

🔁 Shared Intelligence Across All Customers

Every attack Cloudflare sees on any customer's traffic improves protection for all customers. New WAF rules are deployed globally. Bot signatures are shared across the network. IP reputation scores are updated in real time across all PoPs. This cross-customer network effect means Cloudflare gets smarter every minute — and a single customer benefits from protecting millions of sites.

♻️ Progressive Policy Enforcement

Rather than always hard-blocking suspicious traffic, Cloudflare uses a spectrum of responses: allow, log, challenge (CAPTCHA / JS challenge), block. This nuanced approach reduces false positives — legitimate users with suspicious characteristics get a challenge they can pass, while confirmed malicious actors get blocked.

🔓 Democratise Security

DDoS protection, free SSL, WAF, and CDN used to be available only to large enterprises with massive budgets. Cloudflare's free tier gave these capabilities to everyone — a small personal blog gets the same DDoS protection as a Fortune 500 company. This mission to make enterprise-grade protection universally accessible has fundamentally changed the internet's security landscape.


🎓 Section 17:Cheat Sheet

If you're asked to "Design Cloudflare" or "Design a CDN with DDoS protection", here is your exact 5-step framework:

Step 1: Clarify Requirements (5 mins)
  • CDN + DDoS + WAF + DNS — all at once? (say: yes, all are interconnected)
  • Global presence required? (say: yes, 300+ cities worldwide)
  • What scale? (say: 50M req/sec, 321+ Tbps capacity, millions of customer sites)
  • Workers (edge compute)? (say: yes, JS/Wasm with zero cold starts)
  • Free tier + enterprise tier? (say: yes, multi-tier pricing)
Step 2: Estimate Scale (5 mins)
  • 50M+ requests/second globally → ~167K req/sec/PoP across 300 PoPs
  • Network capacity: 321+ Tbps total across all PoPs
  • DNS: Cloudflare handles ~1.4 trillion DNS queries per day (1.1.1.1)
  • Workers: 50M+ Worker requests/day for edge compute customers
  • Attack scale: up to 5.6 Tbps mitigated in a single event
Step 3: High-Level Design (10 mins)
  • Anycast Network: same IP, 300+ locations, BGP routes to nearest PoP
  • Edge Pipeline: TLS → DDoS filter → WAF → Bot check → Rate limit → Cache → Worker → Origin
  • DNS: Authoritative + recursive (1.1.1.1), globally replicated, sub-5s propagation
  • Workers: V8 Isolates, zero cold start, KV + R2 + Durable Objects for state
  • Nightly threat intelligence updates to all PoPs via control plane
Step 4: Deep Dive (15 mins)
  • Explain Anycast in depth — BGP routing, how each PoP advertises same prefix
  • Explain DDoS absorption — Anycast dilution + volumetric capacity > any attack
  • Explain WAF rule pipeline — regex matching, ML-based anomaly detection, OWASP rules
  • Explain V8 Isolates vs Containers — why Workers has zero cold starts
  • Explain cache invalidation — TTL, Purge API, Cache-Control headers
Step 5: Edge Cases (5 mins)
  • PoP goes offline → Anycast automatically re-routes to next nearest in seconds
  • Zero-day exploit discovered → WAF rule deployed globally within hours (virtual patching)
  • Legitimate traffic looks like DDoS (flash crowd, viral content) → Cloudflare distinguishes via UA, TLS fingerprint, behaviour
  • Cloudflare itself gets attacked → Cloudflare's own infrastructure is protected by Cloudflare (Magic Transit)
  • Cache poisoning attempt → Vary headers, request canonicalisation, signed cache keys

🎉 Final Summary

🌐 Anycast Network — Same IP address, 300+ cities. BGP routes you to the nearest Cloudflare PoP automatically and invisibly
🛡️ DDoS Mitigation — Anycast dilutes attacks across all PoPs. 321+ Tbps capacity dwarfs any attack. Mitigated in under 1 second, automatically
🧱 WAF — 65,000+ rules inspect every HTTP request for SQL injection, XSS, RCE, and more. Updated globally in hours when new threats emerge
📦 Edge Cache — Static content served from the nearest PoP in milliseconds. Your origin server is never contacted for cache hits
📡 DNS 1.1.1.1 + Authoritative DNS — World's fastest resolver. Config changes propagate globally in under 5 seconds (vs 24–48 hours for traditional DNS)
🔒 TLS at the Edge — SSL handshake happens at the nearest PoP (~20ms) not at the distant origin (~200ms). Free Universal SSL for all websites
⚡ Workers + V8 Isolates — Zero cold start serverless at 300+ edge locations. 10,000x more memory-efficient than containers
🗺️ Argo Smart Routing — Private Cloudflare backbone bypasses congested public internet. 30% faster origin responses on average
🤖 Bot Management — ML analyses 100+ signals to distinguish real humans from automated bots. Good bots allowed, bad bots blocked or challenged
🔁 Network Effect of Security — Each attack seen on any customer improves protection for all 20M+ customers globally, in real time
✅ The Most Important Lesson from Cloudflare's Architecture:

Cloudflare demonstrates something profound about system design at scale: the best infrastructure solves multiple hard problems with one elegant solution.

Anycast was built for performance. But it also made DDoS mitigation trivial. The WAF was built for security. But each rule makes all customers safer. Workers was built for edge compute. But it also enables zero-latency security logic.

When your architecture is right at the fundamental level, solutions to hard problems emerge naturally. That's the hallmark of truly great engineering. 🎯
Happy Learning! Keep Building! 🔥

Comments