CloudFront Caching through Lambda (Serverless)

Vinod Kisanagaram
Jan 15 · 2 min read

Caching Serverless requests through CloudFront has multiple benefits — predominantly saving costs on resource usage(if your function calls other APIs/services like storage/database etc) and improving speed of serving

Before you jump on to using below, recommend reading the article at caching-in-with-cloudfront

Below is sample serverless.yml reference which can cache your requests.

Note the usage of QueryString: true — this ensures that cloudfront will cache based on your query parameters to GET request.

Caching based on query params or header params is sometimes a bad idea — For example let’s say you have used caching on query params for URL like below

When cloudfront caching is enabled for URL like above, AWS will cache based on orderid, and it will retrieve entire Order model. If your Order has field ‘status’

“orderid”: “1234”,
“status”: “PLACED”,
“product”:”BLAH BLAH”

and if your order will undergo multiple changes in Status cycles — PLACED, SHIPPED, CANCELLED, DELIVERED etc by some other APIs (sometimes using other functions created under same Cloudfront/Serverless service), cloudfront will always return the initial Order with status “PLACED”!! which is highly undesirable.

For scenarios like Order like above, it’s always recommended to cache within service by using Caching mechanisms like Redis/Memcached/In memory cache etc.

So when to use Cloudfront’s cache?

When responses for URL doesn’t change or change less frequently.

Example: Assume you are building a site that retrieves the images of fruits —

Here banana’s pic will not change and this is best served through Cloudfront cache, rather than you exposing S3 link or your function serving image from project folder/s3 bucket.

To explore more on the possible values for ForwardedValues — go through

Back to Serverless usage

Example for a GET request of format, cloud front will cache responses and refetch from cache whenever the name param has value world

Here’s complete sample serverless.yml that includes cloudfront caching

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade