Our next-gen architecture is built to help you make sense of your ever-growing data. Watch a 4-min demo video!

What Are AWS Edge Locations & Using Lambda@Edge with CloudFront

  • 10 min read

What Are AWS Edge Locations?

AWS edge locations are part of the AWS global infrastructure, designed to deliver content with reduced latency and improved performance. These locations are data centers spread across the globe, optimized to serve content to users with the least amount of delay by being physically closer to them. By caching data in these edge locations, AWS ensures that end-users experience faster access to web applications, streaming content, and other online services.

The primary function of AWS edge locations is to work in conjunction with services like Amazon CloudFront, AWS’s content delivery network (CDN). Through CloudFront, AWS caches copies of static and dynamic content at edge locations so that when a user requests this content, it is served from the nearest edge location rather than the origin server. This speeds up the delivery of content and reduces the load on the origin server, minimizing bandwidth usage costs.

In this article, you will learn:

How Do Edge Locations Work?

Edge locations respond to user requests with the nearest cached content, reducing latency. When a user requests specific content—such as a web page, image, or video—the request is intelligently routed to the closest edge location. If the requested data is already cached there, it’s immediately delivered to the user.

For content not present in the cache of an edge location, AWS retrieves it from the origin server—be it an Amazon S3 bucket, an EC2 instance, or any other designated origin—and delivers it to the requesting user. Afterward, this content is cached at the edge location for future requests.

Edge Locations vs. AWS Regions vs. Availability Zones

Edge locations, AWS Regions, and Availability Zones represent different components of AWS’s global infrastructure.

Edge locations are primarily used for caching content close to users to reduce latency. They do not host primary AWS services like Amazon EC2 instances or Amazon S3 buckets; instead, they serve cached content to provide faster access for end-users around the globe.

AWS Regions are specific geographic locations around the world where AWS clusters its resources. Each Region is a separate geographic area that has multiple, isolated locations known as Availability Zones.

Availability Zones provide users with the ability to operate production applications and databases that are more highly available, fault tolerant, and scalable than would be possible from a single data center.

Unlike edge locations, both AWS Regions and Availability Zones support the deployment and operation of core infrastructure services such as computing resources and database storage.

Benefits of AWS Edge Locations

AWS edge locations offer the following capabilities:

  • Return a fast response directly to the user: When a user requests content that is cached at an edge location, AWS can serve this content nearly instantaneously since it is much closer to the user than the original server. This minimizes latency, leading to quicker load times and more engaging online experience. It is especially beneficial for dynamic content that changes frequently or personalized content tailored to individual users.
  • Route traffic onto the AWS network: This dedicated network of high-bandwidth fiber optic cables offers a more reliable and faster path for data to travel than the public Internet. When users access services via AWS edge locations, their data requests are intercepted and redirected through this optimized path, reducing latency and packet loss. This feature is particularly beneficial for applications requiring high throughput.
  • There are more edge locations than Regions: AWS’s global infrastructure includes a larger number of edge locations compared to AWS Regions. Users are more likely to be in close proximity to an edge location, strategically placed in major cities and metropolitan areas around the world.

Key AWS Services Utilizing Edge Locations

Here are some of the main AWS services that rely on the fast connectivity of edge locations.

Amazon CloudFront

Amazon CloudFront is a CDN service that securely delivers data, videos, applications, and APIs to customers globally with low latency and high transfer speeds. It integrates with AWS – both physically in terms of the AWS global infrastructure and through direct software integrations – to enable the distribution of content to end-users without minimum usage commitments.

CloudFront works by caching copies of the user’s static and dynamic content across its network of edge locations. The service is designed to work seamlessly with other AWS services such as Amazon S3 for storage, Amazon EC2 for compute power, and Amazon Route 53 for DNS routing.

CloudFront also provides security features, including AWS Shield Standard for DDoS protection, HTTPS support for secure data encryption in transit, and custom SSL certificates management through AWS Certificate Manager (ACM).

AWS Global Accelerator

AWS Global Accelerator is a networking service that improves the availability and performance of applications. By leveraging the AWS global network, it directs user traffic to the optimal endpoint based on health, geographic location, and policy configurations. This ensures a more consistent application experience for users worldwide, as traffic is routed to avoid congestion.

The service is suitable for applications requiring high availability across multiple regions. Global Accelerator optimizes path selection in real time. It provides static IP addresses that act as a fixed entry point to applications hosted in different AWS Regions. These IP addresses remain associated with each application, simplifying DNS management.

Amazon Route 53

Amazon Route 53 is a scalable cloud Domain Name System (DNS) web service, designed to provide a reliable way to route end users to Internet applications. It translates domain names like www.example.com into numeric IP addresses like 192.0.2.1, which computers use to connect to each other. Route 53 connects user requests to infrastructure running in AWS, such as Amazon EC2 instances, Elastic Load Balancing load balancers, or Amazon S3 buckets.

Route 53  also allows routing users to infrastructure outside of AWS. It is fully compliant with IPv6 as well, offering features such as health checking, traffic flow for load balancing, DNS failover to reroute web traffic upon application failure automatically, and DNSSEC for authenticating responses using secure signature algorithms.

What Is Lambda@Edge?

Lambda@Edge is a feature within AWS that allows developers to run Lambda functions at AWS edge locations, closer to the application users. This integration with Amazon CloudFront enables users to execute functions in response to CloudFront events, such as requests for content or responses from origin servers, without managing servers.

The service supports various use cases, including website customization, security control by inspecting cookies or headers before forwarding requests to origin servers, and intelligent routing of requests based on user location or device type. Lambda@Edge functions are stateless, automatically scaling with the number of requests across different locations.

Tutorial: Create a Basic Lambda@Edge Function in CloudFront

Here’s an overview of how to use get started with Lambda@Edge in CloudFront.

Set Up a CloudFront Distribution

To set up a Lambda@Edge function, you first need to create a CloudFront distribution, which acts as the environment where your function will operate:

1. Login into your AWS account and browse to Amazon S3 page. Click Create bucket.

2. Set up an Amazon S3 bucket to serve as the origin for your distribution:

3. To configure read-only access, click the Permissions tab and edit the bucket policy as shown in the following screenshots:

Enter the following code to allow read-only access:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "PublicReadGetObject",
      "Effect": "Allow",
      "Principal": "*",
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::YOUR-BUCKET-NAME/*"
    }
  ]
}


4. Begin by uploading sample content, such as image files, to this bucket and ensure you configure permissions to allow public read access. The content in your S3 bucket will be what CloudFront distributes through its network of edge locations.

5. Now browse to the CloudFront page and click Create a CloudFront distribution.

6. When creating a CloudFront distribution, choose your newly created S3 bucket as the origin. This process links your content with CloudFront, enabling it to be delivered efficiently worldwide.

7. Take note of the distribution ID, crucial since you’ll need it later when configuring triggers for your Lambda@Edge function.

Create the Lambda Function

To create a Lambda function to use with CloudFront:

1. Start by navigating to the AWS Management Console and accessing the AWS Lambda console. It’s important to ensure you’re in the US-East-1 (N. Virginia) region. Lambda@Edge functions can only be created in this specific region due to its proximity to CloudFront’s infrastructure. Click Create function.

2. Choose Use a blueprint for your method of creation, then type cloudfront into the search field to filter for CloudFront blueprints. Select the Modify HTTP response header blueprint, which provides a template designed for CloudFront use cases.

3. Next, you’ll need to configure your function with details such as naming it and setting up an execution role that grants necessary permissions. For example, inputting a name under Function name identifies your function within AWS.
4. When configuring the execution role, opt for Create a new role from AWS policy templates to ensure your function has permissions aligned with Lambda@Edge requirements.

This setup includes automatically adding a policy template that allows CloudFront to execute your Lambda function globally. The code snippet below shows how to modify security headers in responses from CloudFront:

'use strict';
exports.handler = (event, context, callback) => {
   //Get contents of response
   const response = event.Records[0].cf.request;
   const headers = response.headers;

   //Set new headers
   headers['strict-transport-security'] = [{key: 'Strict-Transport-Security', value: 'max-age= 63072000; includeSubdomains; preload'}];
   headers['content-security-policy'] = [{key: 'Content-Security-Policy', value: "default-src 'none'; img-src 'self'; script-src 'self'; style-src 'self'; object-src 'none'"}];
   headers['x-content-type-options'] = [{key: 'X-Content-Type-Options', value: 'nosniff'}];
   headers['x-frame-options'] = [{key: 'X-Frame-Options', value: 'DENY'}];
   headers['x-xss-protection'] = [{key: 'X-XSS-Protection', value: '1; mode=block'}];
   headers['referrer-policy'] = [{key: 'Referrer-Policy', value: 'same-origin'}];

   //Return modified response
   callback(null, response);
};

This code intercepts HTTP responses from CloudFront and adds several security-related headers before returning the modified response back through CloudFront to end-users, enhancing security practices without requiring changes at the origin server or manual involvement in content delivery processes.

    Add a CloudFront Trigger

    To integrate the Lambda function with CloudFront and have it execute in response to events, you must add a CloudFront trigger to run the function:

    1. Begin by navigating to the Lambda console and selecting your function.
    2. From there, choose Add trigger and select CloudFront as the trigger type. This initiates the deployment of your function to Lambda@Edge.
    3. In the configuration panel for the CloudFront trigger, input your distribution ID to link the function directly to your specific CloudFront distribution. For cache behavior, you can leave it set to *, indicating that the default cache behavior should apply.
    4. Next, select Origin response as the triggering event from CloudFront, meaning your function will execute whenever CloudFront fetches a response from your origin server.
    5. After confirming deployment to Lambda@Edge by checking the appropriate box, proceed by clicking Deploy. This action replicates your function across AWS locations. Note: deployment may take some time before it is available in your region.

      Verify the Function’s Operation

      To ensure that your Lambda@Edge function is operating correctly:

      1. Initiate a test by accessing a file from your S3 bucket through the CloudFront distribution URL. For ex, you might use an image file URL like https://d111111abcdef8.cloudfront.net/image.jpg. This step is crucial for verifying that the function adds the intended security headers to HTTP responses as designed. Using a web browser allows you to directly observe the effects of your Lambda function on live web content, providing immediate feedback on its performance.

            2. After accessing the file in your browser, utilize the Web Developer tools available in most modern browsers to inspect the HTTP response headers.

            3. Navigate to the Network tab and reload the page. You can select the request for your file and examine the headers in detail. This inspection should reveal the security headers added by your Lambda@Edge function, such as Strict-Transport-Security and Content-Security-Policy, among others. The presence of these headers confirms that your function is successfully modifying CloudFront responses, enhancing security without altering the origin server configurations.

                Coralogix CDN

                Coralogix sets itself apart in observability with its modern architecture, enabling real-time insights into logs, metrics, and traces with built-in cost optimization. Coralogix’s straightforward pricing covers all its platform offerings including APM, RUM, SIEM, infrastructure monitoring and much more. With unparalleled support that features less than 1 minute response times and 1 hour resolution times, Coralogix is a leading choice for thousands of organizations across the globe.

                Learn more about Coralogix WAF and CDN

                Observability and Security
                that Scale with You.