CDN & Edge Computing

Difficulty: Intermediate

Question

How does a CDN work? When would you use edge computing vs a centralized server?

Answer

A CDN (Content Delivery Network) is a distributed network of servers that cache content at locations geographically close to users.

How it works: 1. User requests a resource (image, JS, CSS) 2. DNS resolves to the nearest CDN edge server (anycast routing) 3. Edge server checks its cache - if found, returns immediately 4. On cache miss, fetches from origin server, caches locally, then returns

Benefits: - Reduced latency (content served from nearby edge) - Reduced origin server load - DDoS protection (distributed attack absorption) - Automatic failover between edge nodes

Edge Computing extends this: run actual code at edge locations, not just cache static files. Examples: Cloudflare Workers, AWS Lambda@Edge, Vercel Edge Functions.

Use edge for: A/B testing, geolocation redirects, authentication, personalized responses, API routing.

Code examples

CDN Configuration & Cache Headers

// Cache-Control headers determine CDN caching behavior

// Static assets (images, CSS, JS) - cache aggressively
// Cache-Control: public, max-age=31536000, immutable
// File names include content hash: app.a1b2c3.js

// API responses - short cache or no cache
// Cache-Control: private, no-cache
// Or: Cache-Control: public, max-age=60, s-maxage=300
//     (browser: 60s, CDN: 300s)

// Express middleware for cache headers
function setCacheHeaders(req, res, next) {
  if (req.path.match(/\.(js|css|png|jpg|woff2)$/)) {
    // Static assets: cache for 1 year
    res.set('Cache-Control', 'public, max-age=31536000, immutable');
  } else if (req.path.startsWith('/api/')) {
    // API: no cache by default
    res.set('Cache-Control', 'private, no-store');
  } else {
    // HTML pages: revalidate on each request
    res.set('Cache-Control', 'public, max-age=0, must-revalidate');
  }
  next();
}

// CDN cache invalidation (CloudFront example)
// When you deploy new static assets:
await cloudfront.createInvalidation({
  DistributionId: 'E1234567890',
  InvalidationBatch: {
    Paths: { Quantity: 1, Items: ['/*'] },
    CallerReference: Date.now().toString()
  }
});
// Better approach: use content-hashed filenames
// so new deploys use new URLs (no invalidation needed)

Cache-Control headers tell both browsers and CDNs how long to cache content. Content-hashed filenames eliminate the need for cache invalidation because new versions get new URLs.

Edge Function (Cloudflare Workers)

// Cloudflare Worker: runs at 300+ edge locations worldwide
// Executes in < 50ms, no cold start

export default {
  async fetch(request) {
    const url = new URL(request.url);

    // Geolocation-based routing
    const country = request.cf?.country;
    if (country === 'CN') {
      return Response.redirect('https://cn.example.com' + url.pathname);
    }

    // A/B testing at the edge
    const bucket = hashUserId(request) % 100;
    const variant = bucket < 50 ? 'control' : 'experiment';

    // Fetch from origin with variant header
    const response = await fetch(request.url, {
      headers: { 'X-AB-Variant': variant }
    });

    // Add headers for client-side tracking
    const modifiedResponse = new Response(response.body, response);
    modifiedResponse.headers.set('X-AB-Variant', variant);
    return modifiedResponse;
  }
};

// Edge use cases:
// - Auth token validation (no round trip to origin)
// - Bot detection and blocking
// - Image resizing based on device
// - Personalized caching (vary by user segment)
// - Rate limiting at the edge

Edge functions run application logic at CDN edge locations, eliminating the round trip to origin servers. They are ideal for lightweight operations like routing, auth checks, and A/B testing.

Multi-CDN Architecture

// Multi-CDN: use multiple CDN providers for resilience

// DNS-based traffic splitting
// Route 53 weighted routing:
// - 60% traffic -> CloudFront
// - 30% traffic -> Cloudflare
// - 10% traffic -> Fastly

// Real-time performance-based routing
class CDNRouter {
  constructor() {
    this.providers = [
      { name: 'cloudfront', url: 'https://cf.example.com', weight: 60 },
      { name: 'cloudflare', url: 'https://cl.example.com', weight: 30 },
      { name: 'fastly', url: 'https://fl.example.com', weight: 10 }
    ];
    this.healthStatus = {};
  }

  getProvider(clientRegion) {
    // Filter healthy providers
    const healthy = this.providers.filter(
      p => this.healthStatus[p.name] !== 'down'
    );

    // Performance-based selection
    const latency = this.getLatencyData(clientRegion);
    return healthy.sort(
      (a, b) => latency[a.name] - latency[b.name]
    )[0];
  }

  // Health check every 30 seconds
  async healthCheck() {
    for (const provider of this.providers) {
      try {
        const start = Date.now();
        await fetch(`${provider.url}/health`);
        this.healthStatus[provider.name] = Date.now() - start;
      } catch {
        this.healthStatus[provider.name] = 'down';
      }
    }
  }
}

// Key CDN metrics to monitor:
// - Cache hit ratio (target: 90%+)
// - Origin offload percentage
// - Edge latency (p50, p95)
// - Bandwidth savings vs serving from origin

Multi-CDN provides resilience against CDN outages and can route users to the fastest provider for their region. Active health checks detect and route around degraded CDN nodes.

Key points

Concepts covered

CDN, Edge Caching, Cache Invalidation, DNS Routing, Static Assets