AWS Cloudfront is a content delivery network (CDN) service, which delivers data fast and security world wide. It keeps a copy of files to their own server for faster delivery. Sometimes when you apply changes to your application, it not appear on frontend immediately. This is due to Cloudfront serve those files from there own server. It takes some time to read latest files from original servers.
To apply changes immediately, you need to clear cache on Amazon Cloudfront. AWS provides an option to create cache invalidation request against your Cloudfront distribution. This tutorial help you to clear cache on Amazon Cloudfront.
Clear All Cache of Cloudfront
You must have AWS-CLI tools installed and configured on your system. Open a terminal on your system have aws-cli installed. Execute the following command to create cache invalidation request. Make sure to change YOUR_CF_DIST_ID with the distribution ID of your cloudfront distribution.
aws cloudfront create-invalidation --distribution-id YOUR_CF_DIST_ID --paths "/*"
On success, you will see the results like below.
{ "Location": "https://cloudfront.amazonaws.com/2019-03-26/distribution/YOUR_CF_DIST_ID/invalidation/I1YH8TKX3DC1MK", "Invalidation": { "Id": "I1YH8TKX3DC1MK", "Status": "InProgress", "CreateTime": "2020-08-12T14:09:03.117Z", "InvalidationBatch": { "Paths": { "Quantity": 1, "Items": [ "/*" ] }, "CallerReference": "cli-1597241342-987270" } } }
The current status of invalidation is “InProgress”. Note down the Id of the invalidation request to check status of the invalidation requests.
Clear Specific Files from Cache
Instead of clearing all chache, you can clear specific files from Cloudfront cache. For example, you have just updated 1 or 2 files in your application. Now, you need to clear that files only from cloudfront.
To clear specific files from cache, execute command as following:
aws cloudfront create-invalidation --distribution-id YOUR_CF_DIST_ID \
--paths "/static/images/newfile.jpg" "/static/css/style.css"
The above command will clear only /static/images/newfile.jpg and /static/css/style.css from cloudfront cache, So new files will reflect immediately.
View Request Status of Invalidation
Now, use below command to check invalidation request status. Execute the following command with your cloudfront distribution id and pass the request id to “–id” parameter. See the below example:
aws cloudfront get-invalidation --distribution-id YOUR_CF_DIST_ID --id I1YH8TKX3DC1MK
{ "Invalidation": { "Id": "I1YH8TKX3DC1MK", "Status": "Completed", "CreateTime": "2020-08-12T14:09:03.117Z", "InvalidationBatch": { "Paths": { "Quantity": 1, "Items": [ "/*" ] }, "CallerReference": "cli-1597241342-987270" } } }
The invalidation process take less than a minute. Once the invalidation request successfully completed, you will see the status as “Completed”.