Skip to content

Edge Computing with CloudFront Lambda@Edge — Use Cases, CDN, Edge Functions

DodaTech Updated 2026-06-22 5 min read

Edge Computing processes data close to users instead of centralized data centers, reducing latency by running code at CDN edge locations worldwide.

What You'll Learn

You'll learn how CloudFront and Lambda@Edge work, when to use edge functions, how to optimize content delivery, and real-world use cases like A/B testing, image optimization, and authentication.

Why It Matters

Every 100ms of latency reduces conversion rates by 7%. Edge Computing brings computation to 400+ global locations, delivering sub-50ms response times. Content Delivery Networks combined with edge functions enable powerful optimizations. Doda Browser's page preloading uses edge-side techniques to anticipate user navigation.

Real-World Use

A global news website uses CloudFront to serve static assets with 10ms latency worldwide, Lambda@Edge to dynamically resize images per device, and edge functions to redirect users to the nearest regional API endpoint.

CloudFront CDN Basics

CloudFront is AWS's content delivery network that caches content at edge locations and accelerates dynamic content delivery.

flowchart LR
  A[User in Tokyo] --> B[Edge Location Tokyo]
  A2[User in London] --> C[Edge Location London]
  B --> D[Origin: S3 Bucket]
  C --> D
  B --> E[Origin: ALB us-east-1]
  C --> E
  style A fill:#48f,color:#fff
  style A2 fill:#4a4,color:#fff
  style D fill:#f80,color:#fff
  style E fill:#f80,color:#fff
# Create a CloudFront distribution
aws cloudfront create-distribution \
  --origin-domain-name dodatech-blog.s3.amazonaws.com \
  --default-root-object index.html \
  --enabled \
  --default-cache-behavior \
    TargetOriginId=dodatech-blog,\
    ViewerProtocolPolicy=redirect-to-https,\
    CachePolicyId=658327ea-f89d-4f48-a8e0-f9b1c8ed9a2b

Expected behavior: CloudFront serves content from the nearest edge location. Cache hits serve sub-50ms while misses fetch from origin.

Lambda@Edge

Lambda@Edge runs Node.js or Python functions at CloudFront edge locations in response to four trigger events: viewer request, viewer response, origin request, and origin response.

# Lambda@Edge: viewer request — redirect based on device
def lambda_handler(event, context):
    request = event["Records"][0]["cf"]["request"]
    headers = request["headers"]

    user_agent = headers.get("user-agent", [{"value": ""}])[0]["value"]

    if "Mobile" in user_agent or "Android" in user_agent:
        request["uri"] = "/mobile" + request["uri"]

    return request

Expected behavior: When a mobile user requests /article, Lambda@Edge rewrites the URI to /mobile/article before CloudFront fetches from the origin.

// Lambda@Edge: origin response — inject security headers
exports.handler = (event, context, callback) => {
  const response = event.Records[0].cf.response;
  const headers = response.headers;

  headers["strict-transport-security"] = [
    { key: "Strict-Transport-Security", value: "max-age=31536000; includeSubdomains" }
  ];
  headers["x-content-type-options"] = [
    { key: "X-Content-Type-Options", value: "nosniff" }
  ];
  headers["x-frame-options"] = [
    { key: "X-Frame-Options", value: "DENY" }
  ];
  headers["referrer-policy"] = [
    { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }
  ];

  callback(null, response);
};

Expected behavior: Every response that CloudFront sends to the client includes security headers. The origin does not need to set them.

Use Cases for Edge Functions

Use Case Trigger Benefit
URL rewrites Viewer request Clean URLs without origin changes
A/B testing Viewer request Route percentage of users to different origins
Image optimization Origin request Resize/convert images at edge
Authentication Viewer request Validate JWT tokens before reaching origin
Geolocation routing Viewer request Redirect based on viewer country
Response compression Origin response Compress content at edge

Image Optimization at the Edge

# Lambda@Edge: origin request — request WebP images
def lambda_handler(event, context):
    request = event["Records"][0]["cf"]["request"]
    headers = request["headers"]

    accept = headers.get("accept", [{"value": ""}])[0]["value"]

    if "image/webp" in accept:
        # Add query parameter for WebP format
        uri = request["uri"]
        if "." in uri:
            base, _ = uri.rsplit(".", 1)
            request["uri"] = base + ".webp"

    return request

Expected behavior: Browsers that support WebP receive .webp images. Other browsers continue receiving JPEG or PNG. No client-side code changes needed.

Common Errors

  1. Lambda@Edge timeout limits: Viewer events have a 5-second timeout. Origin events have 30 seconds. Functions that exceed the limit fail silently.
  2. Size constraints: Lambda@Edge functions are limited to 1MB for viewer events and 50MB for origin events. Large packages must use layers or stay within limits.
  3. No environment variables: Lambda@Edge does not support environment variables. Use DynamoDB or a configuration file stored in the function package.
  4. Caching side effects: Response-altering Lambda@Edge functions must include a cache behavior key like <a href="/cloud-computing/cloudfront-cdn/">CloudFront</a>-Viewer-Country or cached responses will serve wrong content.
  5. Cold start latency: Edge functions have cold starts like regular Lambda. Use provisioned concurrency cautiously and monitor the error rate.
  6. Forgetting IAM permissions at the edge: Lambda@Edge must be created in us-east-1 and requires specific IAM roles with CloudFront and Lambda permissions.

Practice Questions

  1. What is the difference between viewer request and origin request triggers? Viewer request fires before the cache is checked. Origin request fires only when a cache miss occurs.
  2. Can Lambda@Edge modify the response body? Viewer response can add, remove, or modify headers but cannot change the body. Origin response can modify the body.
  3. How many edge locations does CloudFront have? CloudFront has 600+ points of presence (POPs) and 13 regional edge caches globally.
  4. What happens if Lambda@Edge throws an error? CloudFront returns a 502 or 503 error. Errors in request triggers prevent the request from reaching the origin. Errors in response triggers pass the original response through.
  5. Challenge: Design an Edge Computing Strategy for a global e-commerce site that serves users in 50 countries. Use Lambda@Edge for geolocation-based pricing, device-specific layouts, and A/B testing.

Mini Project

Implement an edge-optimized content delivery system:

  • Create a CloudFront distribution with an S3 origin containing images
  • Write a Lambda@Edge function that redirects mobile users to a mobile-specific path
  • Write a second function that adds security headers (HSTS, CSP, X-Frame-Options)
  • Write a third function that serves WebP images when the browser supports it
  • Enable CloudFront logging and verify responses with curl
  • Test latency reduction by comparing direct origin access vs CloudFront delivery
  • Monitor function execution duration with CloudWatch

Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro