Caching

Lesson 11 of 14 · 20 min

x
79%

CDN Caching & Edge Delivery

A CDN (Content Delivery Network) caches content at edge servers distributed globally — Cloudflare, AWS CloudFront, Fastly, Azure CDN. A user in Tokyo gets the response from a Tokyo edge node instead of your server in Virginia, cutting latency from 200ms to 20ms. CDNs excel at static content: images, videos, CSS, JavaScript bundles. Configure cache behaviors by path pattern — /assets/* gets a long TTL, /api/* bypasses the cache. Cache purging invalidates edge copies when you deploy new assets. For dynamic content, CDNs support edge-side includes and stale-while-revalidate at the edge. The key decision is what to cache at the edge vs what must reach your origin server. User-specific API responses (my profile, my orders) should not be cached at the CDN. Public, identical responses (product catalog, blog posts, static pages) are ideal CDN candidates.

Before
All traffic hits origin server
// User in Tokyo → 200ms round trip to US-East
GET https://api.example.com/products
→ Origin server in Virginia
→ 200ms latency per request
After
CDN serves cached responses at the edge
// CloudFront distribution config
{
  "pathPattern": "/products/*",
  "cachePolicy": {
    "defaultTTL": 300,
    "maxTTL": 3600
  }
}

// User in Tokyo → 15ms from Tokyo edge
GET https://cdn.example.com/products
→ CloudFront Tokyo edge (cache hit)
→ 15ms latency

// Purge on deploy
await cloudfront.createInvalidation({
  Paths: { Items: ['/products/*'] }
});

Key Takeaway

Cache public, identical content at the CDN edge — keep user-specific and dynamic API responses at the origin.

PreviousNext Lesson