Skip to content

CDN Guide — Content Delivery Networks Explained

DodaTech Updated 2026-06-20 11 min read

In this tutorial, you'll learn about CDN Guide. We cover key concepts, practical examples, and best practices.

A Content Delivery Network (CDN) caches web content at edge servers near visitors, reducing latency and offloading traffic from origin servers.

In this tutorial, you will learn how CDNs work under the hood, configure CDN caching rules for different content types, set up a CDN in front of your website with AWS CloudFront and Cloudflare, implement cache invalidation strategies, protect against DDoS attacks, and measure performance improvements. DodaTech uses multiple CDNs to deliver Doda Browser updates and Durga Antivirus Pro signature files to millions of users globally.

What You'll Learn

By the end of this guide, you will understand how CDNs cache content at edge locations, configure a CDN for your website, apply cache policies for different asset types, invalidate stale content, and measure the latency improvement.

Why CDN Matters

CDNs power over 70% of all web traffic. Without a CDN, a Tokyo visitor waits 200-400ms for a US server. With a CDN, that drops to 10-30ms. For any global audience, a CDN is essential, complementing NGINX proxies and Docker deployments.

CDN Learning Path

flowchart LR
  A[How CDNs Work] --> B[Cache Policies]
  B --> C[CDN Providers]
  C --> D[Cache Invalidation]
  D --> E[DDoS Protection]
  E --> F[Performance Testing]
  F --> G{You Are Here}
  style G fill:#f90,color:#fff

How CDNs Work

When a user visits a website behind a CDN, the request follows this path:

sequenceDiagram
  participant User as 🌐 Visitor
  participant Edge as 📡 Edge Server
  participant Origin as 🖥️ Origin Server

  User->>Edge: GET /style.css
  Edge->>Edge: Cache HIT? (TTL check)
  alt Cache HIT
    Edge-->>User: 200 OK (cached copy)
  else Cache MISS
    Edge->>Origin: Fetch /style.css
    Origin-->>Edge: 200 OK + Cache-Control headers
    Edge->>Edge: Store in cache
    Edge-->>User: 200 OK
  end

Key CDN Concepts

Concept Explanation Example
Edge server A server in a CDN data center close to users 450+ Cloudflare locations
Origin server Your main web server where the CDN fetches content Your EC2 instance or shared host
Cache HIT Content is served from the edge without contacting origin 10ms response time
Cache MISS Content was not cached; must fetch from origin 200ms response time
TTL Time-To-Live — how long content stays in cache 24 hours for images, 0 for HTML
Purge Manually removing cached content before TTL expires After deploying a site update

Cache Policy Configuration

The most important configuration on any CDN is the cache policy — what gets cached, for how long, and how the edge should handle different content types.

Cache-Control Headers

Your origin server communicates cache rules through HTTP headers:

# NGINX config — set Cache-Control headers for different assets
location /assets/ {
    expires 7d;
    add_header Cache-Control "public, immutable";
}

location /images/ {
    expires 30d;
    add_header Cache-Control "public, immutable";
}

location /api/ {
    # API responses should never be cached by the CDN
    add_header Cache-Control "no-cache, no-store, must-revalidate";
}

Expected behavior

curl -I https://example.com/assets/style.css
# HTTP/2 200
# cache-control: public, immutable
# age: 12345
# x-cache: HIT

curl -I https://example.com/api/users
# HTTP/2 200
# cache-control: no-cache, no-store, must-revalidate
# x-cache: MISS
Content Type TTL Cache-Control Rationale
CSS/JS (versioned) 1 year public, immutable Filename changes on update (e.g., style.v2.css)
Images (JPEG, PNG, WebP) 30 days public, immutable Rarely change after upload
Fonts (WOFF2, TTF) 1 year public, immutable Never change file content
HTML pages 0 or 5 min no-cache or max-age=300 Content updates frequently
API responses 0 no-cache, no-store Dynamic data per request
Redirects (301) 1 hour public, max-age=3600 Short TTL so changes propagate

CDN Provider Configuration

AWS CloudFront — Create a Distribution

# Create a CloudFront distribution pointing to your origin
aws cloudfront create-distribution \
  --origin-domain-name app.example.com \
  --default-root-object index.html \
  --default-cache-behavior '{
      "TargetOriginId": "app.example.com",
      "ViewerProtocolPolicy": "redirect-to-https",
      "AllowedMethods": {
        "Quantity": 2,
        "Items": ["GET", "HEAD"],
        "CachedMethods": {
          "Quantity": 2,
          "Items": ["GET", "HEAD"]
        }
      },
      "ForwardedValues": {
        "QueryString": false,
        "Cookies": {
          "Forward": "none"
        }
      },
      "MinTTL": 0,
      "DefaultTTL": 86400,
      "MaxTTL": 31536000
    }'

Expected output

{
  "Distribution": {
    "Id": "E1ABCDEFGHIJK2",
    "DomainName": "d1234abcdef.cloudfront.net",
    "Status": "InProgress",
    "LastModifiedTime": "2026-06-20T12:00:00Z"
  }
}

Cloudflare — Cache Rules via Page Rules

Cloudflare offers a simpler interface through Page Rules:

# Cache everything under /assets/
Pattern: example.com/assets/*
Setting: Cache Level → Cache Everything
Setting: Edge Cache TTL → 30 days

# Bypass cache for admin section
Pattern: example.com/admin/*
Setting: Cache Level → Standard
Setting: Security Level → High

# Always use HTTPS
Pattern: example.com/*
Setting: Always Use HTTPS → On

Cache Invalidation

Sometimes you need to remove cached content before the TTL expires — after deploying a new version, fixing a bug, or updating images.

CloudFront Invalidation

# Invalidate specific paths
aws cloudfront create-invalidation \
  --distribution-id E1ABCDEFGHIJK2 \
  --paths "/index.html" "/style.css" "/assets/*"

# Expected output
# {
#   "Invalidation": {
#     "Id": "I1ABCDEFGHIJKLMN",
#     "Status": "InProgress"
#   }
# }

Cloudflare Purge

# Purge everything via API
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/purge_cache" \
  -H "Authorization: Bearer YOUR_API_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"purge_everything":true}'

Cache-Busting Best Practice

Instead of invalidating, use unique filenames:

<!-- ❌ Bad: same filename, must purge cache -->
<link rel="stylesheet" href="/style.css">

<!-- ✅ Good: versioned filename, browser gets new file automatically -->
<link rel="stylesheet" href="/style.v2.css">

DDoS Protection

CDNs absorb massive DDoS attacks by distributing traffic across thousands of edge servers.

How CDNs Stop DDoS Attacks

Attack Type CDN Defense Mechanism
Layer 3/4 (SYN flood, UDP amplification) Traffic absorbed at edge; rate limiting at network level
Layer 7 (HTTP flood) Behavioral analysis, IP reputation, CAPTCHA challenges
Application layer (slow loris) Connection timeouts, request rate limiting
DNS amplification CDN's authoritative DNS with rate limiting

Expected behavior during attack

Normal:    User → CDN Edge → Cache HIT → 200 OK (10ms)
During attack: Attacker → CDN Edge → Rate limited → 503 (blocked at edge)
                Legitimate user → CDN Edge → Still served normally

Performance Testing

Measure the impact of a CDN with these tools:

Using curl to Compare Latency

# Test direct origin latency
curl -w "Total time: %{time_total}s\n" -o /dev/null -s \
  -H "Host: example.com" http://origin-ip/

# Test CDN latency
curl -w "Total time: %{time_total}s\n" -o /dev/null -s \
  https://d1234abcdef.cloudfront.net/

Expected improvement

Direct origin: Total time: 0.342s (from US East)
CDN (US East):  Total time: 0.012s  (28x faster)
CDN (Europe):   Total time: 0.024s  (14x faster)
CDN (Asia):     Total time: 0.035s  (10x faster)

Using WebPageTest

# Install webpagetest CLI
npm install -g webpagetest

# Run a test from multiple locations
webpagetest test https://example.com \
  --location Dulles:Chrome \
  --firstViewOnly

# Expected output
# Load time with CDN: 0.8s
# Load time without CDN: 3.2s
# Improvement: 75% faster

Common Errors

1. CDN Serving Stale Content After Update

The CDN still serves old files because the TTL has not expired. Purge the cache immediately after deployment. Better yet, use cache-busting filenames (style.v2.css) so old files expire naturally.

2. Mixed Content Warning (HTTP vs HTTPS)

Your origin serves some assets over HTTP while the page loads over HTTPS. Fix all asset URLs to use https:// or protocol-relative URLs (//cdn.example.com/style.css). Update the CMS database to replace hardcoded HTTP URLs.

3. CDN Causing Login/Auth Issues

Dynamic pages (cart, account, admin) are cached and served to the wrong user. Ensure authenticated pages have Cache-Control: no-cache, no-store, must-revalidate headers. Configure the CDN to bypass cache for URLs containing /admin/, /cart/, or /account/.

4. "Too Many Redirects" Error

The CDN redirects HTTP to HTTPS, but the origin server also redirects HTTP to HTTPS, creating a redirect loop. Set the CDN to forward the original protocol via the X-Forwarded-Proto header and configure the origin to trust the CDN as a termination point.

5. CDN Not Caching as Expected

The origin sends Set-Cookie headers or Cache-Control: private, which prevent CDN caching. Remove unnecessary cookies from static asset responses. Ensure cache headers explicitly allow public caching (Cache-Control: public, max-age=86400).

6. High Origin Load Despite CDN

Cache HIT ratio is low. Check that (a) cache headers allow caching, (b) the CDN is configured to cache the content type, (c) query strings are not random (disable query string caching), and (d) cookies are not breaking cache.

7. SSL Certificate Error on CDN Domain

The CDN's SSL certificate does not cover the custom domain. For CloudFront, request a free ACM certificate in us-east-1. For Cloudflare, enable "Full (strict)" SSL mode and let Cloudflare issue an edge certificate automatically.

Practice Questions

1. What is a CDN and why is it important?

A CDN is a distributed network of servers that caches content at edge locations close to users. It reduces latency (response time), offloads traffic from the origin server, and provides DDoS protection.

2. What is the difference between a cache HIT and a cache MISS?

A cache HIT means the requested content was found at the edge server and served directly. A cache MISS means the edge server did not have the content and had to fetch it from the origin server, adding latency.

3. How do Cache-Control headers affect CDN behavior?

Cache-Control headers tell the CDN (and browser) what to cache and for how long. public, max-age=86400 caches for 24 hours. no-cache, no-store prevents caching entirely. immutable tells the CDN the file never changes.

4. How do you invalidate CDN cache after a deployment?

Use the CDN provider's purge API: CloudFront's create-invalidation, Cloudflare's purge_cache endpoint, or the provider's dashboard. For versioned assets, no invalidation is needed — old files expire naturally.

5. Challenge: Set up a multi-origin CDN configuration

Configure a CDN with two origins: one for static assets (S3 bucket) and one for dynamic content (EC2). Route /assets/* to S3 with a 1-year TTL and /* to the EC2 origin with no caching. Test both paths with curl.

Mini Project: Full CDN Setup

Configure a CDN for a production website:

  1. Choose a CDN provider (CloudFront or Cloudflare)
  2. Point the CDN to your origin server
  3. Configure cache rules:
    • Assets (/assets/*): Cache 1 year, public, immutable
    • Images (/images/*): Cache 30 days, public, immutable
    • Pages (/): No cache or 5 min TTL
    • API (/api/*): No cache, no store
  4. Set up HTTPS with automatic redirect from HTTP
  5. Test performance before and after CDN
  6. Simulate a cache invalidation after a deployment
  7. Enable DDoS protection features

Test performance:

# Before CDN (direct origin)
curl -w "Time: %{time_total}s\n" -o /dev/null -s \
  http://origin-ip/assets/style.css
# After CDN
curl -w "Time: %{time_total}s\n" -o /dev/null -s \
  https://cdn-domain/assets/style.css

# Verify cache headers
curl -I https://cdn-domain/assets/style.css
# Expected: cache-control: public, immutable
# Expected: x-cache: Hit from cloudfront (or similar)

# Test purge
curl -I https://cdn-domain/assets/style.css
# First request: x-cache: Miss
# Second request: x-cache: Hit

This CDN architecture is what DodaTech uses to deliver Doda Browser updates and Durga Antivirus Pro signature files to millions of users worldwide with sub-50ms latency.

FAQ

Is a CDN necessary for a small website?

For local or low-traffic sites, a CDN is optional. But even small sites benefit from CDN-level DDoS protection, SSL termination, and performance improvements. Most CDN providers offer generous free tiers (Cloudflare is free, CloudFront has 1 TB free).

Can a CDN cache dynamic content?

Yes — dynamic content can be cached for short periods. For example, a news homepage can be cached for 5-60 seconds. CDNs support "stale-while-revalidate" where stale content is served while the CDN fetches a fresh copy in the background.

How does a CDN choose which edge server to use?

The CDN uses DNS-based routing or Anycast to direct the user to the nearest edge server. Anycast announces the same IP from multiple locations — routers automatically route to the closest one. DNS-based routing returns the IP of the nearest data center.

What is the difference between a CDN and a web server?

A web server (NGINX, Apache) hosts the original content. A CDN is a distributed caching layer in front of the web server. The web server handles requests that miss the cache, while the CDN handles the majority of traffic at the edge.

How do CDNs protect against DDoS attacks?

CDNs have massive bandwidth capacity (100+ Tbps) spread across hundreds of edge locations. During an attack, traffic is distributed across all edge nodes, making it impossible for attackers to overwhelm a single target. Behavioral filters block malicious traffic at the edge before it reaches the origin.

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro