RNG

thoughts on software development and everything else

Replacing Lambda@Edge with CloudFront Functions

2022-04-18

Mid last-year AWS introduced CloudFront Functions - designed for running extra-small (sub-millisecond) operations on web requests without the overhead of a full Lambda function.

This is perfect for the use cases I wrote Lambda@Edge functions for:

In fact, AWS even provides those as examples in their documentation: https://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/functions-example-code.html

CloudFront Functions are only available as viewer-request and viewer-response, so they will be called more often than the origin-request and origin-response Lambda@Edge functions. But:

  1. They are cheaper per invocation : $0.10 per 1M invocations vs $0.60 for Lambda@Edge.
  2. They don’t have a memory+execution-time based charge. Lambda@Edge costs $0.00005001 per GB/second used.
  3. There is a free tier for CloudFront Functions: 2 million invocations per month. There is no free tier for Lambda@Edge.

These considerations are pretty theoretical for my personal website, which costs around 90c a month. But CloudFront Functions are a very attractive option for large-traffic distributions.

Step 1: Removing the existing Lambda@Edge associations

Open up the “Behaviour” tab of the CloudFront distribution config. Down the bottom are the Lambda associations. Remove them: Removing Lambda associations from CloudFront distribution

Then we visit a sub-page to verify the URL-rewriter has been removed, so that /blog/ no longer fetches the resource /blog/index.html: URL without index.html leads to 404

And also that the security headers are no longer being added: Developer Tools showing security headers no longer included in response

AWS removes lambda versions automatically after there are no distributions associated with them.

Step 2: Adding CloudFront Functions

You can create functions directly from the CloudFront console: The CloudFront Function creation screen CloudFront Function javascript code for pretty URLs You can test the function behaviour in a similar way to testing Lambda functions. Unfortunately you can’t save multiple test cases to retry. The CloudFront Function test page for pretty URLs

Once the function is published, it can be associated with a cloudfront distribution: Publishing a CloudFront Function Associating a Function to a CloudFront distribution

Now we can check the functions in the wild:

Pretty URL working with CloudFront Functions
No more 404!

Security headers being added by CloudFront Functions
Security headers are back!

Switching to CloudFront Functions was surprisingly easy to do! I’d recommend anyone to try it if you have some extra-simple Lambda@Edge functions lying around.