πŸŽ‰ 75% of content is free forever β€” Unlock Premium from $10/mo β†’
CW
NEWSLIVESearch All Content
πŸ’Ό Servicesℹ️ Aboutβœ‰οΈ ContactView Pricing Plansfrom $10

CDN & Edge Computing

Cloud ArchitecturePerformance & Caching⭐ Premium

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

Users (Global)Edge Location β”‚ β”‚ Edge β”‚ β”‚ Edge(Tokyo) β”‚ β”‚ (London) β”‚ β”‚ (SΓ£oPaulo)Cache β”‚ β”‚ β”‚ β”‚CacheCacheOrigin Server(us-east-1)

Pattern 1: CloudFront with Lambda@Edge

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

javascript
// 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.

python
# 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.

javascript
// 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.

javascript
// 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.

javascript
// 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?

Extended Learning: Beyond the Basics

Key Concepts Summary

This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.

Prerequisite Knowledge

Before studying this topic in depth, ensure you understand:

  • Basic definitions and terminology
  • Core formulas and their derivations
  • Common applications in real-world scenarios
  • Typical pitfalls and misconceptions

Step-by-Step Walkthrough

Let us work through a complete example to solidify understanding:

Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.

Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.

Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.

Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.

Common Mistakes to Avoid

  1. Misidentifying the problem type β€” Always start by categorizing the problem
  2. Incorrect formula application β€” Verify the formula applies to your specific case
  3. Unit errors β€” Always check units are consistent throughout
  4. Sign errors β€” Pay careful attention to positive and negative values
  5. Rounding too early β€” Keep full precision until the final answer
  6. Forgetting constraints β€” Check that solutions satisfy all given conditions

Real-World Applications

Understanding this concept is essential for:

  • Advanced problem solving in examinations
  • Building intuition for more complex topics
  • Developing analytical thinking skills
  • Applying mathematical reasoning to practical situations

Practice Exercises

  1. Basic: Solve 5 problems of increasing difficulty using the core concept.
  2. Intermediate: Apply the concept to word problems with multiple steps.
  3. Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
  4. Challenge: Create your own problem that requires this concept plus additional knowledge.

Interview and Exam Tips

  • Common question patterns: Identify which exam or interview formats test this topic
  • Time management: Practice completing problems within time constraints
  • Common traps: Know the typical mistakes examiners set as distractors
  • Verification strategy: Develop a quick method to check your answer

Related Topics

Quick Reference Card

ConceptFormula/RuleKey InsightCommon Use
Core DefinitionSee main textUnderstand the intuitionFoundation for all applications
Key FormulaSee main textMemorize the derivationDirect problem solving
Special CaseSee main textRecognize when it appliesSimplifies complex problems
Edge CaseSee main textKnow the limitationsAvoids errors

Further Reading

For students who want to go deeper:

  • Standard textbooks on the subject
  • Research papers applying this concept
  • Online courses with video explanations
  • Practice problem collections with detailed solutions
πŸ”’

Premium Content

CDN & Edge Computing

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

🎯End-to-end Projects
πŸ’ΌInterview Prep
πŸ“œCertificates
🀝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-11-14

β€”
β˜†β˜†β˜†β˜†β˜†
0 ratings

Rate & Feedback

Advertisement