In my previous blog, We have talked about What is CloudFront with its works and in this blog, we will learn how CloudFront Caching and Invalidations works.
Reducing the number of requests to our origin server directly is one of the goals of using CloudFront. Due to CloudFront caching, more objects are served from CloudFront edge locations, which are nearer to users. This reduces latency and minimizes the load on our origin server.
We can cache on multiple things:
- Session Cookies
- Query string parameters
As we know the cache lives at each CloudFront Edge location.
In the diagram, we can see that when a client makes a request to the CloudFront Edge Locations the cache will be checked on the basics of the values of headers and the cookies and the query string parameters.
And then the cache has an expiry based on the time to live in the cache, and if the value is not in the cache, then the query, or the entire HTTPS request, is forwarded directly to the origin, and then the cache is filled by query response.
So, the main purpose of the Cloudfront is to minimize the number of requests on our origin by maximizing the number of cache hits that it gets, i.e., the number of requests that are served directly from the cache.
For this, we can adjust the cache’s TTL, which ranges from 0 seconds to 1 year, as well as some headers, such as the cache control header or the expires header.
Now, let’s see how it works.
- AWS Account
- CloudFront Distribution
Let’s look at the caching behavior of our CloudFront Distribution as it will tell how the cache will work.
Click on Edit. You can see Cache Policy which is called CachingOptimized which is recommended for S3 origins.
Click on View policy to view the Policy.
We can see that the caching Policy in CloudFront is having a TTL of a minimum of one second, a maximum of 31536000, and a default of 86400 seconds. We can create our own new policy if we want to change the Time To Live (TTL) settings of our file.
So now let’s fetch an object from CloudFront using the Distribution domain name.
Now if we upload a new version of this file in our S3 Bucket and try to access it.
We are getting this updated file directly by Amazon S3 and if we refresh the page for CloudFront we will still get ” Hello World !! “.
So, to tell CloudFront to force fetch this new version of the file we need to create invalidations.
Click on Create invalidations. Add the star (*), which instructs CloudFront to erase all things from its cache and fetch new CloudFront Amazon S3 objects in its place.
Once it is created refresh the CloudFront Page we will get the updated file as it is correctly fetched.
In this blog, we have learned what is AWS CloudFront Caching and how it works with proper demonstration. If you have any doubt you can directly reach out to me.
To read my previous blog AWS CloudFront – A Quick Overview!!
To read more about DevOps.
Happy Learning !!