Trigger lambda *only* on 404 (or other error) from s3+cloudfront

0

I'm using S3 and Cloudfront to host a static site and want to return a directory listing (via lambda) of the bucket contents if an index.html file doesn't exist. There's already a Cloudfront function that directs content to the index.html page if the user doesn't provide an extension, or if the request ends with a "/".

Problem is, I don't want the lambda function to always run. The answer from a similar (but different) question of "Can I trigger a Lambda function when a file is not found on S3?" uses lambda to intercept the origin response (and determine what the status code is) and return a potentially modified response.

If the lambda function always runs, then it ends up having to be run on every file/request from the web client, which adds unnecessary latency and costs. I'm also not sure either about the costs of having a lambda function return large files from S3, especially when it's unnecessary 99% of the time.

Thank you for considering this question and any potential answers.

1 Answer
0

It's not currently possible to selectively invoke a Lambda@Edge function based on the status code in the response, but it's worth being aware of how caching in CloudFront will impact the number of invocations.

Functions associated with the Origin triggers only run when CloudFront requests an object from the origin - ie. in the event of a cache miss. If the object is in Cache, CloudFront returns it to the viewer immediately and does not invoke Lambda@Edge functions on either of the Origin triggers.

Objects in an S3 bucket usually lend themselves well to caching, so you should find that your function only executes for the minority of requests that are cache misses. By checking the status code early in your function, you can minimise the execution time where the request results in anything other than a 404.

Note that CloudFront will cache errors as well - but make sure you have configured the TTL to suit your preference, following the documentation here.

AWS
EXPERT
Paul_L
answered 10 months ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions