Invalidating CloudFront's Cache

Posted by Brian Roepke on Thu 24 June 2021 Updated on Thu 24 June 2021

Invalidating with Python and the Boto3 SDK

Cloudfront's default TTL for edge caches is 24 hours. In most cases this is totally sufficient, however, I've found in some that it's handy when deploying new changes to be able to force the update.

Utilizing the python boto3 sdk, it's possible to invalidate items. The below script will invalidate all objects in your cache. You can modify this to invalidate a single item if you wish.

Note: The preferred method is to use the TTL feature or versioned URLs. This will automatically invalidate items and you will not have to wait the approximate 10-15 minutes for an invalidation to finish.

Note: There are no charges for the first 1000 invalidations per month. After that, each one will cost you $0.005 (one half of one cent).

Checking Status

After you run the srcipt, you can go to your AWS CloudFront console and check the status.

AWS CloudFront Invalidate Status

Python Boto3 Script

import boto3
import time

# Create CloudFront client
cf = boto3.client('cloudfront')

# Enter Original name

# A string of characters that can be found in your CF console
DISTRIBUTION_ID = "<distribution id>" 

# Create CloudFront invalidation
def create_invalidation():
    res = cf.create_invalidation(
            'Paths': {
                'Quantity': 1,
                'Items': [
            'CallerReference': str(time.time()).replace(".", "")
    invalidation_id = res['Invalidation']['Id']
    return invalidation_id

# Create CloudFront Invalidation
id = create_invalidation()
print("Invalidation created successfully with Id: " + id)

If you liked what you read, subscribe to my newsletter and you will get my cheat sheet on Python, Machine Learning (ML), Natural Language Processing (NLP), SQL, and more. You will receive an email each time a new article is posted.


tags: aws, python