What a CDN Actually Does
A Content Delivery Network (CDN) is a distributed network of servers spread across multiple geographic locations. When someone visits your website, the CDN serves the content from the server closest to them rather than from your single origin server, which might be on the other side of the planet.
The concept is straightforward: physical distance affects network latency. A request from Lugano to a server in Virginia takes roughly 100-150ms just for the round trip, before any page rendering even starts. If the same content is cached on a server in Zurich or Milan, that round trip drops to 5-15ms. That difference might sound small, but it compounds across every asset on the page: HTML, CSS, JavaScript, images, fonts.
But modern CDNs do far more than just cache static files. They have evolved into comprehensive platforms that handle security, optimization, and compute at the edge.
How CDNs Work: The Technical Details
Points of Presence (PoPs)
A CDN operates through a network of data centers called Points of Presence. Major CDN providers operate hundreds of these worldwide:
- Cloudflare - 300+ cities across 100+ countries
- AWS CloudFront - 450+ points of presence across 90+ cities
- Fastly - 80+ points of presence, focused on major internet exchange points
- Akamai - 4,200+ points of presence (the largest network)
Each PoP contains servers that cache your content. When a user in Lugano requests your page, they connect to the nearest PoP (likely Zurich or Milan), which serves the cached content directly. If the content is not in that PoP's cache, it fetches it from your origin server, caches it, and serves it. Subsequent requests from the same region are served from cache.
DNS-Based Routing
When you configure a CDN, you typically point your domain's DNS to the CDN provider. When a user's browser resolves your domain, the CDN's DNS returns the IP address of the nearest PoP using anycast or geographic DNS routing. The user's browser connects to that PoP transparently.
The Origin Server
Your origin server is where the actual content lives. The CDN sits in front of it, handling requests and serving cached content whenever possible. The origin server only gets hit when the cache is cold (first request for that content) or when the cache has expired (TTL has passed).
For a busy website, a well-configured CDN can absorb 90-99% of all requests without the origin server being involved at all. This is a significant factor for both performance and security.
Caching Strategies That Actually Work
Caching is where most of the CDN performance gain comes from, but getting it right requires thought.
Cache-Control Headers
The Cache-Control header tells the CDN (and browsers) how long to cache a resource and under what conditions. The key directives:
max-age=31536000- Cache for one year. Use for immutable assets like versioned CSS/JS files (e.g.,style.a1b2c3.css).max-age=3600, s-maxage=86400- Browser caches for 1 hour, CDN caches for 24 hours. Good for HTML pages that update periodically.no-cache- Can be cached but must be revalidated with the origin before use. The CDN sends a conditional request (If-Modified-Since or If-None-Match) to check freshness.no-store- Never cache. Use for sensitive data like personalized pages, bank statements, or API responses with private data.stale-while-revalidate=60- Serve stale content while fetching a fresh copy in the background. This gives instant responses while keeping content fresh.
Cache Key Design
The cache key determines what makes a cached resource unique. By default, most CDNs use the full URL including query parameters. This means /page?utm_source=twitter and /page?utm_source=email are cached separately, even though the content is identical.
Smart cache key design strips irrelevant query parameters (marketing tags, analytics parameters) while preserving meaningful ones (language, region, page number). This dramatically improves cache hit ratios.
Cache Purging
When you update content, you need the old version to disappear from the CDN. There are several approaches:
- Cache tags/surrogate keys - Tag cached resources by category. When a product price changes, purge all resources tagged "product-123" across all PoPs. Fastly excels at this.
- Wildcard purge - Purge everything matching a pattern like
/blog/*. Useful for section-level updates. - Full purge - Clear the entire cache. Use sparingly because it causes a stampede of requests to your origin.
- Content hashing - Include a hash in the filename (e.g.,
bundle.a1b2c3.js). When content changes, the filename changes, and the old version naturally expires. This is the most elegant approach for static assets.
A Practical Caching Strategy
| Resource Type | Cache Duration | Strategy |
|---|---|---|
| HTML pages | 1-24 hours at CDN, shorter in browser | s-maxage=86400, max-age=3600, stale-while-revalidate=60 |
| CSS/JS (hashed filenames) | 1 year | max-age=31536000, immutable |
| Images (hashed) | 1 year | max-age=31536000, immutable |
| Images (non-hashed) | 1 week | max-age=604800 |
| API responses (public) | 5-60 minutes | s-maxage=300, stale-while-revalidate=30 |
| API responses (private) | Never | no-store, private |
| Fonts | 1 year | max-age=31536000, immutable |
CDN Security: More Than Just Speed
This is where CDNs deliver value that goes far beyond performance. For businesses that take web security seriously, the security features of a modern CDN are often the primary reason to adopt one.
DDoS Mitigation
We have written extensively about DDoS protection strategies, and a CDN is the foundation of most DDoS defense. The mechanics are simple but effective:
- The CDN's massive distributed network absorbs volumetric attacks across hundreds of PoPs instead of concentrating them on your single origin server.
- Anycast routing automatically distributes attack traffic to the nearest PoP, preventing any single location from being overwhelmed.
- Your origin server's IP address is hidden behind the CDN, so attackers cannot bypass the CDN to attack your infrastructure directly.
- Major CDN providers have network capacities measured in tens of Tbps, dwarfing even the largest recorded DDoS attacks.
Cloudflare, for example, reports mitigating attacks exceeding 2 Tbps on their network regularly. Their free tier includes basic DDoS protection, which is a remarkable amount of security for zero cost.
Web Application Firewall (WAF) at the Edge
A CDN-based WAF inspects incoming requests before they reach your origin server. This means malicious requests are blocked close to their source, reducing latency and ensuring your server never processes attack traffic.
What a CDN WAF typically protects against:
- SQL injection attempts
- Cross-site scripting (XSS) payloads
- Remote file inclusion
- Known vulnerability exploits (Log4j, Struts, etc.)
- Bot traffic (scrapers, credential stuffers, spam bots)
- Rate-based attacks
The advantage of edge-based WAF over a WAF running on your own server is scale and intelligence. CDN providers see traffic from millions of websites, giving them unmatched visibility into attack patterns. When a new attack technique appears on one site, the CDN provider can update WAF rules across their entire network within minutes.
SSL/TLS Termination
CDNs handle SSL/TLS encryption and decryption at the edge. This provides several benefits:
- Free SSL certificates - Most CDN providers include SSL certificates at no additional cost, automatically renewed.
- Automatic HTTPS - Redirect all HTTP traffic to HTTPS without any server configuration.
- Latest TLS versions - CDN providers keep their TLS implementations up to date. When TLS 1.3 was released, CloudFlare had it enabled within weeks.
- Reduced server load - SSL handshakes are computationally expensive. Handling them at the edge offloads that work from your origin server.
- Faster handshakes - TLS handshakes happen at the nearest edge location rather than requiring a round trip to your origin. This alone can save 100-300ms for distant users.
Bot Management
Not all bot traffic is malicious, but a significant portion is. Google's crawlers are welcome; credential stuffing bots are not. CDN-level bot management uses several signals to classify traffic:
- IP reputation databases
- JavaScript fingerprinting (browsers execute JS; simple bots do not)
- Behavioral analysis (bots navigate differently from humans)
- CAPTCHA challenges when confidence is low
- Machine learning models trained on billions of requests
Image Optimization at the Edge
Images typically account for 40-70% of a web page's total weight. CDN-level image optimization can dramatically reduce this without any changes to your codebase.
What Modern CDNs Can Do with Images
- Format conversion - Automatically serve WebP to Chrome/Firefox and AVIF to supporting browsers, falling back to JPEG/PNG for older browsers. WebP is typically 25-35% smaller than JPEG at equivalent quality; AVIF is 40-50% smaller.
- Responsive resizing - Serve appropriately sized images based on the device. A mobile phone does not need a 4K image.
- Quality adjustment - Reduce quality slightly (from 100 to 80-85) with minimal visual difference but significant file size reduction.
- Lazy loading hints - Add loading="lazy" attributes to images below the fold.
- EXIF stripping - Remove metadata (GPS coordinates, camera info) from images, reducing file size and preventing accidental location data leakage.
Real Numbers
A typical business website with 20 images per page might transfer 5MB of image data. With CDN optimization (WebP conversion, responsive sizing, quality adjustment), that drops to 1-1.5MB. That is a 70-80% reduction in image payload, which directly translates to faster page loads, especially on mobile connections.
Performance Gains: Real Numbers
Here is what businesses actually see when they implement a CDN properly:
| Metric | Without CDN | With CDN | Improvement |
|---|---|---|---|
| Time to First Byte (TTFB) | 200-800ms | 10-50ms | 80-95% |
| Largest Contentful Paint (LCP) | 2.5-6s | 0.8-2s | 50-75% |
| Page load time | 3-10s | 1-3s | 60-80% |
| Origin server load | 100% of requests | 5-15% of requests | 85-95% reduction |
| Bandwidth costs | Baseline | 20-40% of baseline | 60-80% savings |
These numbers are not theoretical. We have seen these improvements consistently across client projects. The biggest gains come from the TTFB improvement, which cascades through every other metric. For more on website performance optimization, see our performance optimization guide.
Cloudflare vs. AWS CloudFront vs. Fastly: A Practical Comparison
These are the three CDN providers we encounter most frequently in business contexts. Each has distinct strengths.
Cloudflare
Best for: Small to medium businesses, websites that need strong security without complexity.
- Free tier - Genuinely useful. Includes CDN, basic DDoS protection, shared SSL, and basic WAF. Most small business websites can run on the free tier indefinitely.
- Ease of setup - Point your nameservers to Cloudflare and you are running. No complex configuration needed.
- Workers - Serverless edge compute platform. Runs JavaScript/TypeScript at the edge with extremely low latency.
- Pages - Static site hosting with automatic builds from Git. Comparable to Vercel or Netlify.
- R2 Storage - S3-compatible object storage with zero egress fees.
- Pricing - Free, Pro ($20/mo), Business ($200/mo), Enterprise (custom).
AWS CloudFront
Best for: Applications already running on AWS, complex enterprise requirements.
- AWS integration - Seamless integration with S3, EC2, Lambda@Edge, API Gateway. If your infrastructure is on AWS, CloudFront is the natural choice.
- Lambda@Edge - Run custom code at edge locations. More powerful than Cloudflare Workers but with higher cold start latency.
- Fine-grained control - Extensive configuration options for caching, origin failover, and content routing.
- Pricing - Pay-as-you-go based on data transfer and requests. No free tier for CloudFront specifically (though AWS Free Tier includes some usage).
Fastly
Best for: High-traffic sites needing instant cache purging, media and e-commerce.
- Instant purge - Cache purge propagates globally in under 150ms. If your content changes frequently and cache freshness is critical, this is Fastly's killer feature.
- VCL (Varnish Configuration Language) - Extremely powerful edge logic. More flexible than other CDNs but steeper learning curve.
- Compute@Edge - WebAssembly-based edge compute. Supports Rust, Go, JavaScript, and more.
- Real-time analytics - Sub-second log streaming and analytics. Invaluable for debugging and performance monitoring.
- Pricing - Pay-as-you-go, starting around $50/month for most business sites.
Comparison Summary
| Feature | Cloudflare | CloudFront | Fastly |
|---|---|---|---|
| Free tier | Yes (generous) | Limited | No |
| Ease of setup | Very easy | Moderate | Moderate |
| DDoS protection | Excellent (included) | Good (Shield extra) | Good |
| WAF | Included (Pro+) | Extra cost | Extra cost |
| Cache purge speed | 30 seconds | 5-10 minutes | < 150ms |
| Edge compute | Workers (JS/TS) | Lambda@Edge | Compute@Edge (Wasm) |
| Best for | SMBs, websites | AWS ecosystems | High-traffic, media |
Common CDN Mistakes
We see these regularly in security assessments and performance audits:
- Origin IP exposed - Setting up a CDN but leaving the origin server IP discoverable through DNS history, email headers, or subdomains that bypass the CDN. Tools like SecurityTrails and Censys make finding origin IPs trivial.
- Caching private content - Serving personalized or authenticated pages through the CDN cache without proper
Cache-Control: privateorno-storeheaders. User A sees User B's account page. - Cache poisoning - Not sanitizing headers that become part of the cache key. An attacker injects a malicious
X-Forwarded-Hostheader, the response gets cached, and all subsequent users get the poisoned version. - Over-caching API responses - Caching API responses that contain time-sensitive or user-specific data without proper cache control.
- Ignoring the CDN for API traffic - Only routing static assets through the CDN while sending API traffic directly to the origin. This misses the security benefits (WAF, DDoS protection, rate limiting) for your most vulnerable surface.
Getting Started: A Step-by-Step Approach
- Choose your provider. For most businesses, Cloudflare's free or Pro tier is the best starting point. If you are on AWS, use CloudFront.
- Configure DNS. Point your domain to the CDN. With Cloudflare, this means changing your nameservers. With CloudFront, you create a distribution and update your DNS CNAME.
- Set cache headers. Add proper
Cache-Controlheaders to your origin server responses. Start conservative (short TTLs) and increase as you gain confidence. - Enable HTTPS. Most CDNs provide free SSL certificates. Enable HTTPS everywhere and configure HTTP-to-HTTPS redirection.
- Enable WAF rules. Start with the managed ruleset provided by your CDN. Monitor for false positives in the first week before enabling block mode.
- Test. Verify that your site works correctly through the CDN. Check that authenticated pages are not being cached. Verify that cache purging works.
- Monitor. Set up analytics to track cache hit ratio, bandwidth savings, blocked threats, and performance improvements.
The Business Case for CDN Investment
For most businesses, a CDN is one of the highest-ROI investments in their web infrastructure. The math is simple: Cloudflare's Pro tier costs $20/month and provides CDN caching, DDoS protection, WAF, SSL, and image optimization. An equivalent setup built from individual components would cost hundreds per month and require ongoing maintenance.
At Envestis, we implement CDN strategies for businesses across Lugano and Switzerland as part of our web security and performance services. If you want to understand how a CDN can improve your website's speed and security posture, get in touch with our team.
Want to know if your site is secure?
Request a free security audit. In 48 hours you get a complete report.
Request Free Audit