Search code examples
cachingamazon-web-servicesamazon-cloudfront

How can I tell if CloudFront has an object stored in cache?


I'm trying to dynamically clear CloudFront's cache of certain objects. I've got invalidation set up and working, but since I only get 1000 free invalidation requests, I want to avoid unnecessary ones by checking if the object is cached by CloudFront at all. Is there a way to do this through the API?


Solution

  • There is no API call to check the contents of a CloudFront cache. (Actually, there's more than once cache, since objects could be cached at any of the 50+ CloudFront edge locations.)

    An alternative would be to modify your web app to serve content that refers to a newer version of the object via cache busting. For example, append ?version=1 to a URL. Then, to ignore that cached object and access a new one, use ?version=2. This would force CloudFront to retrieve the object again. (While it hasn't invalidated the old version, that version will simply timeout after a period. There is no charge for data stored in a cache.)

    Using that method, you don't even have to invalidate objects. However, it will involve a code change in your web app.