🌍 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

  1. User requests a resource (say, an image from your website).

  2. The request is routed to the nearest CDN edge server.

  3. If the edge server has the resource cached:

    • It serves it directly – super fast.
  4. 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 ContentCached?
HTML documentsSometimes (depends on headers)
CSS / JSYes
Images / FontsYes
Videos / PDFsYes
API responsesCan 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.