Cache on Cloudfront for a year, but browser should revalidate every 24 hours

Viewed 922

I have a JS asset which needs to be served from a fixed URL, so I can't use versioning. (Many different sites are already accessing it, and they can't be changed easily)

The file is sitting on AWS Cloudfront.

I would like the file to be cached in browsers for up to a year, but still revalidate every 24 hours. It is not vital to be exactly 24 hours. The file is being updated roughly every month.

I was thinking of using these headers:

cache-control: public, max-age=31536000, must-revalidate, proxy-revalidate, stale-while-revalidate=6800

When a new version of the file is published to the CDN I could issue a Cache Invalidate command from Travis.

1 Answers

I'm not clear on exactly what you're asking; the title says you want to cache in Cloudfront for a year, but the question itself says you "would like the file to be cached in browsers for up to a year".

If it's the former, you can use the s-maxage directive, which indicates how long a shared cache (like Cloudfront) can serve a response:

Cache-Control: public, s-maxage=3153600, max-age=86400, stale-while-revalidate=6800

If you really do mean that you "would like the file to be cached in browsers for up to a year, but still revalidate every 24 hours", then you may be misunderstanding how caching works. You can't control how long a cache stores something (other than no-store), you can only indicate how long it should consider a stored response to be fresh. So there's no way to tell the browser to store something for a year but only consider it fresh for 24 hours.

Related