Thursday 20 August 2015

Automate Cloudfront Cache Invalidation Using AWS .NET Toolkit

Amazon CloudFront is a content delivery web service to give developers and businesses an easy way to distribute content to end users with low latency and high data transfer speeds.

Amazon Cludfront has a number of edge locations worldwide, when your application target audience is scattered worldwide then Amazon Cloudfront is a good choice for caching your files and contents to give high throughput and low latency. Let say, if someone is accessing your application from east zone of USA then your contents will be delivered by one of the cloudfront edge servers located in USEast.

Your files which got cached on cloudfront edge locations will be automatically invalidated as per the default Cache Timeout set in request header. But sometimes you may forcefully want to clear files from Cloudfront cache prior to the actual Cache Timeout.


You can do this either by logging into the AWS dashboard, select Distribution for which you want to clear cache and then create Invalidation Rule (By specifying file path) or you can automate the whole procedure using Aws .NET Toolkit. For the second case you need not to login to AWS dashboard every time to Invalidate cache from cloufront edge locations.

Here is how we can Invalidate Cache using AWS .NET Toolkit

First Create Amazon Cloudfornt Client,
 var client = AWSClientFactory.CreateAmazonCloudFrontClient(awsAccessKey, 
           awsSecretAccessKey, RegionEndpoint.USWest2);
And then use it to Invalidate your file(s) cache,
 CreateInvalidationResponse InvalidateResonse = client.CreateInvalidation(
                          new CreateInvalidationRequest
                          {
                                    DistributionId = distributionId,
                                    InvalidationBatch = new InvalidationBatch
                                    {
                                            Paths = new Paths
                                            {
                                                Quantity = arrayOfPaths.Length,
                                                Items = arrayOfPaths.ToList()
                                            },
                                        CallerReference = DateTime.Now.Ticks.ToString(),
                                    },
                          });

You can find awsAccessKey and awsSecretKey when you signup for Amazon web services. Your account must have full access (read/write) to aws otherwise you will get Security Exception when you try to invalidate cache.

arrayOfPaths is the local string array which will have all the files path you want to invalidate,
Ex private static string[] arrayOfPaths = new string[] { "/Styles/*", "/Javascripts/*"};


More on Cloudfront Cache Invalidation:

http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/Invalidation.html

No comments:

Post a Comment