π CDN Caching β Explained Practically
CDN caching is when static or semi-static content (like images, videos, JS/CSS, etc.) is stored on servers distributed across the globe, closer to users. This drastically reduces load times, bandwidth usage, and server strain.
π§ How It Works
-
User requests a resource (say, an image from your website).
-
The request is routed to the nearest CDN edge server.
-
If the edge server has the resource cached:
- It serves it directly β super fast.
-
If not:
- It fetches it from the origin server, serves it to the user, and stores a copy for the next user.
π‘ Example
-
You host a blog at
yourblog.com. -
You use a CDN (like Cloudflare, Akamai, or AWS CloudFront).
-
A user in Germany requests an image β Served from a Frankfurt edge node.
-
A user in India β Served from a Mumbai node.
Same image, but different cache locations closer to the user = π₯ faster experience.
π§ What Gets Cached in a CDN
| Type of Content | Cached? |
|---|---|
| HTML documents | Sometimes (depends on headers) |
| CSS / JS | Yes |
| Images / Fonts | Yes |
| Videos / PDFs | Yes |
| API responses | Can be (with proper headers) |
π οΈ Controlled via HTTP Headers
CDNs obey (or override) headers like:
-
Cache-Control-
public, max-age=86400β cache for 1 day -
no-cacheβ check with origin every time
-
-
ETag/Last-Modified- Helps with conditional requests
-
Vary- Allows separate cache versions per user-agent, language, etc.
β±οΈ Cache Invalidation
What if your content changes?
-
Time-based: Use short TTLs (
max-age=60). -
Manual purge: Invalidate files via CDN dashboard/API.
-
Versioning: Add a hash to filenames (
style.abc123.css) β new name = new cache.
π Benefits
-
β‘ Speed: Reduced latency for global users.
-
π Load: Offloads traffic from your origin server.
-
π° Cost: Lower bandwidth and compute usage.
-
π Security: Some CDNs protect against DDoS, add HTTPS, etc.
β οΈ Limitations / Gotchas
-
Dynamic content caching needs careful setup.
-
Stale cache issues if you donβt version or purge well.
-
CDNs usually donβt cache POST responses (only GET).
π§ͺ Real-World Use Case
-
Hosting product images on a fashion app.
-
CDN caches them globally.
-
When new images are uploaded β you purge the old ones via API or add versioning to filenames.