๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
Search coursesโ€ฆ
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

CDN & Edge Computing

Cloud ArchitecturePerformance & Cachingโญ Premium

Advertisement

CDN & Edge Computing

Difficulty: Senior Level | Companies: AWS, Google, Microsoft, Netflix, Uber

Why CDN & Edge Computing

Edge computing pushes compute and data closer to end users. CDNs cache content at edge locations worldwide, reducing latency and origin load. Together, they enable sub-50ms response times globally.

โ„น๏ธ

A well-configured CDN can reduce page load time by 50-70% and offload 80-90% of traffic from your origin servers.

CDN Architecture

Architecture Diagram
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ”‚              Users (Global)                     โ”‚
        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                             โ”‚
              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
              โ”‚              โ”‚              โ”‚
     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ” โ”Œโ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
     โ”‚  Edge Location  โ”‚ โ”‚  Edge     โ”‚ โ”‚  Edge     โ”‚
     โ”‚  (Tokyo)        โ”‚ โ”‚  (London) โ”‚ โ”‚  (Sรฃo    โ”‚
     โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”‚ โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ” โ”‚ โ”‚  Paulo)  โ”‚
     โ”‚  โ”‚   Cache   โ”‚  โ”‚ โ”‚  โ”‚Cache โ”‚ โ”‚ โ”‚  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”โ”‚
     โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ”‚ โ”‚  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ”‚ โ”‚  โ”‚Cache โ”‚โ”‚
     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜ โ””โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
              โ”‚                โ”‚            โ”‚
              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                               โ”‚
                      โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ดโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                      โ”‚  Origin Server  โ”‚
                      โ”‚  (us-east-1)    โ”‚
                      โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Pattern 1: CloudFront with Lambda@Edge

Process requests at edge locations for personalization and A/B testing.

// Lambda@Edge for A/B testing at the edge
exports.handler = async (event) => {
  const request = event.Records[0].cf.request;
  const headers = request.headers;
  
  // Check for A/B test cookie
  const cookie = headers['cookie']?.[0]?.value || '';
  const abMatch = cookie.match(/ab_test=([a-z]+)/);
  const group = abMatch ? abMatch[1] : determineGroup(headers);
  
  // Rewrite URI based on test group
  if (group === 'variant-b') {
    request.uri = request.uri.replace('/v1/', '/v2/');
  }
  
  // Set response header for tracking
  request.headers['x-ab-group'] = [{ key: 'X-AB-Group', value: group }];
  
  return request;
};

function determineGroup(headers) {
  // Hash user agent + accept-language for consistent bucketing
  const hash = simpleHash(
    (headers['user-agent']?.[0]?.value || '') +
    (headers['accept-language']?.[0]?.value || '')
  );
  return hash % 100 < 10 ? 'variant-b' : 'variant-a';
}

Pattern 2: Multi-Layer Caching

Implement browser, CDN, and origin caching with proper cache headers.

# Cache-Control header strategy
CACHE_HEADERS = {
    # Static assets - immutable, long cache
    'static-assets': {
        'Cache-Control': 'public, max-age=31536000, immutable',
        'Vary': 'Accept-Encoding',
    },
    
    # API responses - short cache, stale-while-revalidate
    'api-responses': {
        'Cache-Control': 'public, max-age=60, stale-while-revalidate=300',
        'Vary': 'Authorization, Accept',
    },
    
    # HTML pages - moderate cache
    'html-pages': {
        'Cache-Control': 'public, max-age=300, stale-while-revalidate=60',
        'Vary': 'Accept-Encoding',
    },
    
    # Dynamic content - no cache
    'dynamic': {
        'Cache-Control': 'private, no-cache, no-store, must-revalidate',
    },
}

def set_cache_headers(response_type, response):
    headers = CACHE_HEADERS.get(response_type, CACHE_HEADERS['dynamic'])
    for key, value in headers.items():
        response.headers[key] = value
    return response

โš ๏ธ

Always set Vary headers correctly. Missing Vary: Accept-Encoding causes CDNs to serve uncompressed content to some users, or cache compressed content for users who don't support it.

Pattern 3: Edge-Side Rendering with CloudFront Functions

Transform content at the edge without Lambda cold starts.

// CloudFront Function for URL normalization (runs in <1ms)
function handler(event) {
  var request = event.request;
  var uri = request.uri;
  var querystring = request.querystring;
  
  // Remove trailing slash (except root)
  if (uri !== '/' && uri.endsWith('/')) {
    uri = uri.slice(0, -1);
  }
  
  // Add .html extension for clean URLs
  if (!uri.includes('.')) {
    uri = uri + '.html';
  }
  
  // Forward only necessary headers
  request.headers = {
    'host': request.headers['host'],
    'cloudfront-is-mobile-viewer': request.headers['cloudfront-is-mobile-viewer'],
  };
  
  request.uri = uri;
  return request;
}

Pattern 4: Origin Shield for Reducing Origin Load

Use CloudFront Origin Shield to add a centralized caching layer.

// Terraform CloudFront with Origin Shield
resource "aws_cloudfront_distribution" "main" {
  origin {
    domain_name = aws_s3_bucket.assets.bucket_regional_domain_name
    origin_id   = "S3-assets"
    
    s3_origin_config {
      origin_access_identity = aws_cloudfront_origin_access_identity.main.cloudfront_access_identity_path
    }
  }
  
  origin {
    domain_name = aws_lb.api.dns_name
    origin_id   = "API-origin"
    
    origin_shield {
      enabled              = true
      origin_shield_region = "us-east-1"  # Central shield region
    }
    
    custom_origin_config {
      http_port              = 80
      https_port             = 443
      origin_protocol_policy = "https-only"
      origin_ssl_protocols   = ["TLSv1.2"]
    }
  }
  
  default_cache_behavior {
    allowed_methods        = ["GET", "HEAD", "OPTIONS"]
    cached_methods         = ["GET", "HEAD"]
    target_origin_id       = "S3-assets"
    viewer_protocol_policy = "redirect-to-https"
    
    # Edge TTL settings
    min_ttl     = 0
    default_ttl = 86400
    max_ttl     = 31536000
    
    forwarded_values {
      query_string = false
      cookies { forward = "none" }
    }
  }
  
  # API behavior - no cache
  ordered_cache_behavior {
    path_pattern           = "/api/*"
    allowed_methods        = ["GET", "HEAD", "OPTIONS", "PUT", "POST", "PATCH", "DELETE"]
    cached_methods         = ["GET", "HEAD"]
    target_origin_id       = "API-origin"
    viewer_protocol_policy = "https-only"
    
    min_ttl     = 0
    default_ttl = 0
    max_ttl     = 0
    
    forwarded_values {
      query_string = true
      headers      = ["Authorization", "Content-Type", "Origin"]
      cookies { forward = "all" }
    }
  }
}

โ„น๏ธ

Origin Shield can reduce origin requests by up to 99% by caching responses that would otherwise miss at edge locations.

Pattern 5: Edge Database with Durable Objects

Use Cloudflare Durable Objects or CloudFront Workers for edge-stateful applications.

// Cloudflare Durable Object for edge state
export class EdgeCounter {
  constructor(state, env) {
    this.state = state;
  }
  
  async fetch(request) {
    const url = new URL(request.url);
    
    if (url.pathname === '/increment') {
      // Durable Object maintains state across requests
      let count = await this.state.storage.get('count') || 0;
      count++;
      await this.state.storage.put('count', count);
      
      return new Response(JSON.stringify({ count }), {
        headers: { 'Content-Type': 'application/json' },
      });
    }
    
    return new Response('Not found', { status: 404 });
  }
}

Performance Benchmarks

StrategyTTFB (Tokyo โ†’ Origin us-east-1)Origin Load
No CDN300-500ms100%
CDN (no shield)50-100ms10-20%
CDN + Origin Shield50-100ms1-5%
Edge Compute10-30ms<1%

Follow-Up Questions

  1. How do you handle cache invalidation for user-specific content without purging the entire CDN cache?
  2. What are the trade-offs between CloudFront Functions, Lambda@Edge, and Cloudflare Workers for edge computing?
  3. How would you design a CDN strategy for a streaming video platform with DRM content?

Advertisement