Sub topic 9
Controlling freshness with TTLs and Cache-Control
This chapter assumes you have a working distribution with an S3 origin and a cache behavior (see the earlier chapters), and that you can read HTTP headers and run AWS CLI commands. It covers how long CloudFront and browsers keep a copy of an object, which settings decide that, and which mistakes cause stale pages.
Two caches, one set of rules
A viewer's request can be answered from two caches:
- The browser cache, on the viewer's device.
- The CloudFront edge cache, shared by every viewer near that edge location.
Each cache decides separately whether its copy is still fresh. The decision uses the object's headers plus, for CloudFront, the TTL values in the cache policy. A TTL (time to live) is the number of seconds a cached copy counts as fresh. After that, the cache must go back to its source before it can reuse the object without checking.
CloudFront never rewrites the Cache-Control header it sends to the browser. The cache policy's TTLs only affect the edge. If S3 returns no Cache-Control header, the browser receives none, even when CloudFront caches the object for 24 hours.
The three TTL values in a cache policy
A cache policy contains three numbers:
| Setting | Meaning |
|---|---|
| Minimum TTL | The shortest time CloudFront keeps an object, even if the origin asks for less. |
| Default TTL | The time used when the origin sends no caching header. |
| Maximum TTL | The longest time CloudFront keeps an object, even if the origin asks for more. |
The managed policy CachingOptimized (ID 658327ea-f89d-4fab-a63d-7e88639e58f6, used in the distribution example earlier) sets them to 1 second, 86400 seconds (24 hours), and 31536000 seconds (one year). The managed policy CachingDisabled sets all three to 0.
How CloudFront picks the edge TTL
CloudFront looks at the headers S3 returned with the object:
- If
Cache-Controlcontainss-maxageormax-age, CloudFront uses it. When both are present,s-maxagewins, because it targets shared caches such as CDNs. Browsers ignores-maxage. - If neither is present but
Expiresis, CloudFront uses the time until that date. - If none of these headers is present, CloudFront uses the Default TTL.
- The result is then clamped: raised to the Minimum TTL if lower, and cut to the Maximum TTL if higher.
The Default TTL applies only to step 3. An object with max-age=60 is cached for 60 seconds even when the Default TTL is a day. The clamp in step 4 applies to every case.
Directives that say "do not cache"
If S3 returns Cache-Control: no-cache, no-store, or private, CloudFront honors them only when the Minimum TTL is 0. With a Minimum TTL above 0, CloudFront still caches the object for at least that long. CachingOptimized has a Minimum TTL of 1 second, so no-store objects are cached for one second under it. If you need no-store to mean what it says, use a custom policy with a Minimum TTL of 0.
Setting Cache-Control on S3 objects
S3 stores Cache-Control as object metadata and returns it on every GET. Set it when you upload:
aws s3 cp ./dist s3://amzn-s3-demo-bucket/assets/ --recursive --cache-control "public,max-age=31536000,immutable"The immutable directive tells browsers not to revalidate the file during its lifetime. That is safe only when a file's name changes whenever its content changes (see the next chapter on versioned file names). Use a different header for files that keep the same name, such as the HTML entry point:
aws s3 cp ./dist/index.html s3://amzn-s3-demo-bucket/index.html --cache-control "public,max-age=0,s-maxage=300" --content-type "text/html"Browsers see max-age=0 and revalidate on every visit. CloudFront sees s-maxage=300 and keeps the page for five minutes. A new deploy reaches every viewer within about five minutes without any invalidation.
Changing metadata on existing objects
You cannot edit metadata in place. You copy the object onto itself and replace the metadata:
aws s3 cp s3://amzn-s3-demo-bucket/index.html s3://amzn-s3-demo-bucket/index.html --metadata-directive REPLACE --cache-control "public,max-age=0,s-maxage=300" --content-type "text/html"With --metadata-directive REPLACE, the metadata you do not list is dropped. This is why the command repeats --content-type. Leave it out and the object may be served with the wrong content type.
Creating a custom cache policy
Use a custom policy when the managed ones do not fit, for example when you want a Minimum TTL of 0 and a short Default TTL for HTML:
Resources:
ShortLivedCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: site-short-lived
MinTTL: 0
DefaultTTL: 60
MaxTTL: 86400
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: true
EnableAcceptEncodingBrotli: true
HeadersConfig:
HeaderBehavior: none
CookiesConfig:
CookieBehavior: none
QueryStringsConfig:
QueryStringBehavior: noneAttach it to a cache behavior by its ID. A common layout is one behavior for /assets/* using CachingOptimized, and the default behavior using this policy.
Revalidation after expiry
When an object's edge TTL runs out, CloudFront does not always download it again. If S3 gave an ETag or Last-Modified value, CloudFront sends a conditional request with If-None-Match or If-Modified-Since. If the object has not changed, S3 answers 304 Not Modified with no body. CloudFront then marks its copy fresh for another TTL period. You see this as X-Cache: RefreshHit from cloudfront. It costs a request to S3 but transfers almost no data.
Checking what a viewer actually gets
Request the object with curl -I and read the headers:
curl -sI https://dxxxxxxxxxxxxx.cloudfront.net/assets/app.3f9a1c.js| Header | What it tells you |
|---|---|
| `X-Cache` | `Hit from cloudfront`, `Miss from cloudfront`, `RefreshHit from cloudfront`, or `Error from cloudfront`. |
| `Age` | Seconds the object has been in the edge cache. It is absent on a miss. |
| `Cache-Control` | The value from S3, passed through unchanged. This is what the browser will use. |
| `Last-Modified`, `ETag` | The values used for revalidation. |
Run the command twice. The first call is usually a Miss. The second should be a Hit with an Age greater than 0. If you see only misses, the object may be marked uncacheable, or the cache key may differ between requests (a topic for the cache policy chapter).
Error responses have their own TTL
CloudFront caches error responses too. By default it keeps 4xx and 5xx responses from the origin for 10 seconds (the error caching minimum TTL), unless the origin's own headers say otherwise. This stops a failing origin from receiving every request. It also means a file you upload right after a viewer got a 404 can keep returning 404 for a few seconds. You can change this value per status code under custom error responses.
Choosing values
| Content | Suggested `Cache-Control` | Reason |
|---|---|---|
| Fingerprinted JS, CSS, images (`app.3f9a1c.js`) | `public,max-age=31536000,immutable` | The name changes with the content, so a long lifetime is safe. |
| HTML entry pages | `public,max-age=0,s-maxage=300` | Browsers always revalidate. The edge holds a copy for a short time. |
| Files that change on a schedule, such as a feed | `public,max-age=60` | Both caches refresh about once a minute. |
| Per-user or sensitive files | Do not serve through a public behavior | Use signed URLs or signed cookies, covered in a later chapter. |
Common errors
- Stale HTML after a deploy. The page was uploaded with a long
max-ageor no header under a 24-hour Default TTL. Shorten the HTML TTL or invalidate. - Long TTL on a file whose name never changes. A one-year
immutableheader onlogo.pngmeans browsers will not look for a new version. Only versioned names make long lifetimes safe. no-storeignored. The Minimum TTL is above 0, as inCachingOptimized.- Missing
Cache-Controland a surprising delay. With no header, the edge uses the Default TTL, and browsers may apply their own guess based onLast-Modified. - Metadata changed but nothing happened. Cached copies still carry the old headers until they expire.
Exercise
S3 returns Cache-Control: max-age=300 for /news.html. The cache policy has Minimum TTL 0, Default TTL 86400, and Maximum TTL 3600. For how long does CloudFront keep the object at the edge? What happens if the object has no Cache-Control or Expires header instead?
Show answer
With the header, CloudFront uses 300 seconds. It falls between the Minimum and Maximum TTL, so no clamping applies, and the Default TTL is ignored. Without any caching header, CloudFront uses the Default TTL of 86400 seconds, but the Maximum TTL cuts it to 3600 seconds, so the object stays for one hour.
Exercise
You upload index.html with --cache-control "public,max-age=0,s-maxage=300". A browser requests it twice within one minute. Which cache does each part of the header affect, and what does the browser do on the second request?
Show answer
max-age=0 is used by the browser, which treats its copy as stale at once and revalidates on the second request. s-maxage=300 is used by CloudFront, which keeps its edge copy for 300 seconds and answers the browser's conditional request itself, usually with a Hit or a 304. The request does not reach S3 until the edge copy expires.