CDN Configuration for Maximum Performance
In this tutorial, you will learn how to configure a content delivery network for static assets, dynamic content caching, and DDoS protection. A CDN distributes content across geographically distributed servers so users always connect to the nearest edge node. DodaZIP uses CloudFront with 400+ edge locations to serve installer downloads with median latency under 30 milliseconds.
What You Will Learn
- How to set up a CDN distribution for static assets
- How to configure cache behavior with TTLs and cache policies
- How to implement custom origin failover and Load Balancing
- How to use CDN analytics to monitor performance
Why It Matters
Without a CDN, a user in Tokyo loading assets from a server in Frankfurt experiences 250ms of latency. With a CDN, that drops to under 20ms. CDNs also absorb traffic spikes, reduce origin server load by up to 90 percent, and block many common DDoS attacks.
Real-World Use Case
Durga Antivirus Pro distributes virus definition updates to millions of users. Using a CDN with 24-hour cache headers, 85 percent of update requests never reach the origin server. This reduced bandwidth costs by 70 percent and eliminated update server scaling issues.
Prerequisites
You should understand DNS basics and HTTP caching headers. Familiarity with NGINX or Apache configuration is helpful. Knowledge of Caching Strategies is recommended.
Step-by-Step Tutorial
Step 1: Choose a CDN Provider
Popular CDN providers include Cloudflare, Amazon CloudFront, Fastly, and Akamai. Each offers different feature sets and pricing models. For this tutorial we use Cloudflare due to its generous free tier and simple setup.
Step 2: Set Up a CDN Distribution
The basic setup involves pointing your domain to the CDN provider and configuring the origin server.
# Using Cloudflare API to add a DNS record
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/dns_records" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{
"type": "CNAME",
"name": "cdn",
"content": "origin.dodatech.com",
"proxied": true
}'
Expected result: cdn.dodatech.com resolves to Cloudflare edge IPs. Traffic passes through Cloudflare before reaching the origin.
Step 3: Configure Cache Rules
Set caching rules based on content type and path. Static assets receive long TTLs while HTML receives shorter TTLs or bypasses the cache.
# Cloudflare page rule for static assets
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/pagerules" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{
"targets": [
{"target": "url", "constraint": {"operator": "matches", "value": "*dodatech.com/static/*"}}
],
"actions": [
{"id": "cache_level", "value": "cache_everything"},
{"id": "edge_cache_ttl", "value": 604800}
]
}'
Expected behavior: Static files in /static/* are cached at Cloudflare edge for 7 days. Subsequent requests return cf-cache-status: HIT with very low latency.
Step 4: Configure Origin Cache Headers
The CDN respects Cache-Control headers from the origin. Configure your web server to send appropriate headers.
# NGINX configuration for cache headers
server {
location /static/ {
expires 365d;
add_header Cache-Control "public, immutable";
}
location /api/ {
add_header Cache-Control "no-cache, private";
}
location / {
add_header Cache-Control "public, s-maxage=300, stale-while-revalidate=3600";
}
}
Expected behavior: Assets in /static/ are cached for one year. API responses are never cached by the CDN. HTML pages are cached for 5 minutes with stale-while-revalidate serving stale content for up to an hour while fetching fresh data.
Step 5: Enable Gzip and Brotli Compression
Ensure your CDN compresses responses using Brotli (preferred) or Gzip.
# Cloudflare automatically compresses text-based responses by default
# Verify by checking response headers
curl -I -H "Accept-Encoding: br" https://cdn.dodatech.com/styles.css
Expected output: Content-Encoding: br in the response headers indicates Brotli compression is active.
Step 6: Configure Origin Failover
If your origin server goes down, the CDN should serve cached content from its stale cache to maintain availability.
# Enable stale-while-revalidate at the CDN level (Cloudflare)
# This is configured in the dashboard or via API by setting
# the Always Online feature
curl -X PATCH "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/settings/always_online" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{"value": "on"}'
Expected behavior: If the origin is unreachable, Cloudflare serves a cached version of the page. Users see content even during origin outages.
Step 7: Set Up Custom Error Pages
Replace generic CDN error pages with branded error pages that match your site.
# Configure custom 502 error page in Cloudflare
curl -X POST "https://api.cloudflare.com/client/v4/zones/$ZONE_ID/custom_pages" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{
"url": "https://dodatech.com/errors/502.html",
"state": "customized"
}'
Expected result: When the origin returns 502 or is unreachable, users see a branded error page with navigation links and contact information.
Step 8: Monitor CDN Performance
Use CDN analytics to track cache hit ratio, bandwidth, and top requested assets.
# Get Cloudflare analytics via GraphQL API
curl -X POST "https://api.cloudflare.com/client/v4/graphql" \
-H "Authorization: Bearer $TOKEN" \
-H "Content-Type: application/json" \
--data '{
"query": "{\n viewer {\n zones(filter: {zoneTag: \"$ZONE_ID\"}) {\n httpRequests1mGroups(limit: 10, orderBy: [datetime_DESC]) {\n sum {\n requests,\n bytes,\n cachedRequests,\n cachedBytes\n }\n }\n }\n }\n}"
}'
Expected output: JSON data showing total requests, bytes served, cached requests ratio, and cached bytes ratio. A cache hit ratio above 70 percent is good; above 90 percent is excellent.
Learning Path
flowchart LR A[Caching Strategies] --> B[CDN Configuration] B --> C[HTTP/2 and HTTP/3] B --> D[Reduce TTFB] C --> E[Performance Testing] D --> E style B fill:#4f46e5,color:#fff style A fill:#6366f1,color:#fff style C fill:#6366f1,color:#fff
Common Errors
Not proxying traffic through the CDN: Simply pointing DNS to the CDN does not enable caching. Ensure the proxied flag is enabled so the CDN processes the request.
Cache keys that do not vary by device: If your site serves different content to mobile and desktop users, the cache key must include a device type header or cookie.
Overriding origin cache headers incorrectly: CDN page rules that force caching can override sensible origin headers and cause stale content to be served.
Ignoring SSL/TLS configuration: Without proper SSL configuration, the CDN may serve mixed content warnings or fail to establish secure connections.
Not purging the cache after deployment: Deploying new CSS or JavaScript without purging the CDN cache means users receive old files for the duration of the TTL.
Using geo-blocking without fallback: Blocking traffic from certain regions without a proper fallback can break the experience for legitimate users using VPNs or corporate proxies.
Practice Questions
- What is the primary purpose of a CDN?
- What is a cache hit ratio and what is a good target?
- How does stale-while-revalidate improve availability?
- What is the difference between edge cache TTL and browser cache TTL?
- Why should API responses use different caching rules than static assets?
Answers: 1. To serve content from edge servers geographically closer to users, reducing latency. 2. The percentage of requests served from the CDN cache without contacting the origin; above 90 percent is excellent. 3. It serves stale content immediately while fetching fresh content in the background, eliminating wait times during cache expiration. 4. Edge cache TTL controls how long the CDN stores content; browser cache TTL controls how long the browser stores it. 5. API responses often contain dynamic data that changes frequently; static assets rarely change and can be cached longer.
Challenge
Set up a Cloudflare distribution for a sample static site. Configure page rules to cache images for 30 days, CSS and JavaScript for 7 days, and HTML for 1 hour. Enable Brotli compression, set up a custom 502 error page, and verify the cache hit ratio using the GraphQL analytics API.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro