Invalidate cache cloudfront

I’ve a website that’s hosted on S3 with CloudFront as CDN. Is there a simple way to update changes to S3 and invalidate cache?

aws cli is your friend for this:

aws cloudfront create-invalidation --distribution-id <your-distribution-id> --paths /*

I was hoping to not use AWS cli and instead just use serverless as cloud agnostic devops. Not possible?

I don’t believe there is a way to do it through CloudFormation, therefore not built in mechanism for doing it with serverless, unless you feel adventurous enough to write a plugin for it.

1 Like

There’s a couple of ways you could do this:

  • You could set cache headers on the objects in S3 and use CloudFront to forward them.
  • You can also override the cache headers on CloudFront and force shorter TTL values.

Personally I do the first when I upload objects to S3.

1 Like

Originally we didn’t set cache TTL’s and needed to invalidate the cache during every deployment. That took a while and quickly became painful. We then changed to setting the cache control to 30 seconds when uploading to S3. Here’s our command if that helps.

aws s3 cp SRCDIR s3://S3-BUCKET/ --profile PROFILE --recursive --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers --cache-control "max-age=30"

It’s a trade off between longer cache times that are good for performance and being able to test changes quickly. Right now I think we’ve swung too far towards development and I plan to experiment with longer cache times over the next few weeks.

The other alternative we have started using is to set Cloudfront to forward all query parameters and cache on them and then pass a query parameter thats different with each release. The same can be done with headers instead if you prefer