Yasuhiro TATSUNO
Yasuhiro TATSUNO

Reputation: 2009

How to invalidate CloudFront cache of dynamic content when content is updated

I am developing Web APIs using AWS Lambda, API Gateway and CloudFront.
CloudFront is currently used as reverse proxy to some endpoints of API Gateway, cache behaviors are disabled at all.

There are several frequently-used APIs, of which contents are rarely-updated (e.g. once a week or once a month), therefore are candidates for caching for faster response time.

However, I am wondering how to invalidate such CloudFront cache of frequently-used-but-rarely-updated dynamic content when their contents are updated.
My observation is that CloudFront holds cache of older content, since CloudFront does not pass requests to API origin, until cache reaches max-age.

E.g.: Let's say I have a GET /projects/PROJECT_ID/members API.
Project members are rarely updated, but once member added/removed via PUT /projects/PROJECT_ID/members API, cache should be invalidated to deliver the freshly-updated content of project members.

Should I invalidate the very-particular URL (/projects/ABC/members for above example) using invalidation API each time after updating their content (PUT /projects/ABC/members invoked) ?
Or, should I avoid to cache such dynamic content?

Upvotes: 5

Views: 3977

Answers (2)

Varun Mehrotra
Varun Mehrotra

Reputation: 21

There are multiple ways to handle this:

  1. CloudFront Cache Invalidation.
    If you are using S3 as origin, then you can create an S3 event on lambda function. This lambda will automatically invalidate CloudFront cache if there is a change in S3.

  2. Use cache headers like Min. TTL, Max. TTL or Default TTL to define how much time you want those objects in cache before CloudFront makes a call to origin.

  3. Use object versioning on you object. So, that CloudFront will fetch latest version of the objects everytime.

Can refer CloudFront docs for more information on these.

Upvotes: 2

Rez Moss
Rez Moss

Reputation: 4602

You have two options:

1-Call the invalidation API each time someone edits your member list. For example, if someone adds/remove/edit member list (not get request), you should call invalidation API in Cloudfront and invalidate the path

/projects/PROJECT_ID/members

2-Control cache on your API side, also you can set header for some resources to cache in Cloudfront for sometimes.

For more info about CloudFront invalidation API, check the following link

https://docs.aws.amazon.com/cloudfront/latest/APIReference/API_CreateInvalidation.html

Upvotes: 1

Related Questions