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
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
| Strategy | TTFB (Tokyo β Origin us-east-1) | Origin Load |
|---|---|---|
| No CDN | 300-500ms | 100% |
| CDN (no shield) | 50-100ms | 10-20% |
| CDN + Origin Shield | 50-100ms | 1-5% |
| Edge Compute | 10-30ms | <1% |
Follow-Up Questions
- How do you handle cache invalidation for user-specific content without purging the entire CDN cache?
- What are the trade-offs between CloudFront Functions, Lambda@Edge, and Cloudflare Workers for edge computing?
- 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
- Misidentifying the problem type β Always start by categorizing the problem
- Incorrect formula application β Verify the formula applies to your specific case
- Unit errors β Always check units are consistent throughout
- Sign errors β Pay careful attention to positive and negative values
- Rounding too early β Keep full precision until the final answer
- 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
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- 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
- Previous Topic β Build on the foundation laid here
- Next Topic β See how this concept extends to more advanced material
- Practice Problems β Additional exercises with solutions
- Video Explanation β Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids 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