Sub topic 8
Cache policies and what goes into the cache key
This chapter assumes you can read a CloudFront distribution definition, you know what an S3 origin is, and you understand HTTP request headers, cookies, and query strings. It covers how CloudFront decides whether two requests are the same request. That decision controls your cache hit ratio.
What the cache key is
CloudFront stores each cached object under a cache key. This is a string built from the request. When a request arrives at an edge location, CloudFront builds the key and looks it up.
- If an object is stored under that key and is still fresh, CloudFront returns it. This is a cache hit.
- If not, CloudFront fetches the object from S3, stores it under that key, and returns it. This is a cache miss.
The key always includes the request path, such as /assets/app.js, and the distribution's origin. A cache policy decides what else goes into the key. It can add three kinds of request data: headers, cookies, and query strings. It also sets the TTLs and the compression behavior.
Two requests that produce the same key share one cached copy. Two requests that produce different keys each get their own copy, even if S3 would return identical bytes for both.
What a cache policy contains
| Setting | What it controls | Typical value for an S3 origin |
|---|---|---|
| Minimum TTL | Lowest time an object stays cached, even if the origin says less | 1 second or 0 |
| Default TTL | Lifetime used when the origin sends no `Cache-Control` or `Expires` | 86400 seconds |
| Maximum TTL | Upper limit, applied even if the origin asks for longer | 31536000 seconds |
| Headers | Which request headers join the key | None |
| Cookies | Which cookies join the key | None |
| Query strings | Which query string parameters join the key | None |
| Compression | Whether `Accept-Encoding` gzip and Brotli are supported | Both enabled |
The next chapter covers the TTL settings in detail. Here the focus is on the three key components and compression.
Managed policies
AWS provides managed cache policies, so you often do not need to write one. You can list them from the CLI:
aws cloudfront list-cache-policies --type managed \
--query "CachePolicyList.Items[].CachePolicy.CachePolicyConfig.Name"Three of them matter most for S3 content.
- CachingOptimized (ID
658327ea-f89d-4fab-a63d-7e88639e58f6) puts no headers, cookies, or query strings in the key. It sets a minimum TTL of 1 second, a default TTL of 86400 seconds, and a maximum TTL of 31536000 seconds. It enables gzip and Brotli. This is the right starting point for static sites. - CachingOptimizedForUncompressedObjects (ID
b2884449-e4de-46a7-ac36-70bc7f1ddd6d) is the same, but with compression turned off. - CachingDisabled (ID
4135ea2d-6df8-44a3-9df3-4b5a84be39ad) sets all TTLs to 0, so CloudFront does not cache. It is useful for paths that must always reach the origin.
You can inspect any policy with aws cloudfront get-cache-policy --id <ID> before attaching it.
Why a smaller key is better for S3
An S3 object is addressed by its key (its path). S3 GetObject requests do not change their response based on your cookies or most query strings. If you add those values to the cache key anyway, you create many cache entries for one object.
Suppose the policy includes all query strings. A marketing link adds ?utm_source=newsletter to /index.html. Another link uses ?utm_source=twitter. CloudFront treats the two URLs as different keys. Each one is a miss on its first request, and each one stores its own copy of the same file. Your hit ratio drops and your origin request count rises.
The rule is to include only values that change the response. For a plain S3 origin that is usually nothing.
If the key includes nothing, CloudFront also does not forward those values to S3 (unless you add an origin request policy, described below). That keeps requests simple and reduces the chance of S3 rejecting unusual headers.
Cache key versus origin request
The cache key and the origin request are separate ideas, and it is easy to mix them up.
- The cache key decides which cached copy a request matches.
- The origin request is what CloudFront sends to S3 on a miss.
A cache policy values are both in the key and forwarded to the origin. If you want to forward a value to the origin without splitting the cache, use an origin request policy. It lists headers, cookies, and query strings to forward on a miss, and none of them enter the key. On a hit, CloudFront ignores them.
For S3 you rarely need an origin request policy. A common exception is cross-origin resource sharing (CORS). S3 builds its CORS response headers from the Origin request header. To receive them, forward Origin to S3. The managed origin request policy CORS-S3Origin does this.
A matching cache policy for CORS
Forwarding Origin is not enough on its own. If Origin is not in the cache key, CloudFront may serve the response cached for https://a.example to a viewer on https://b.example, with the wrong Access-Control-Allow-Origin value. When S3 varies its response by Origin, put Origin in the key too.
This CloudFormation excerpt defines a custom cache policy that does that:
Resources:
CorsCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: cors-s3-cache-policy
Comment: Cache key includes the Origin header for S3 CORS responses
MinTTL: 1
DefaultTTL: 86400
MaxTTL: 31536000
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: true
EnableAcceptEncodingBrotli: true
HeadersConfig:
HeaderBehavior: whitelist
Headers:
- Origin
CookiesConfig:
CookieBehavior: none
QueryStringsConfig:
QueryStringBehavior: noneYou attach it to a cache behavior by setting CachePolicyId: !Ref CorsCachePolicy. For a CloudFormation AWS::CloudFront::CachePolicy resource, Ref returns the policy ID.
Cache keys that include a header make the cache less efficient, because each distinct Origin value gets its own copy. Use this only for paths that serve cross-origin requests, such as a /fonts/* behavior. The previous chapter showed how to give such paths their own behavior.
Compression and the Accept-Encoding header
When EnableAcceptEncodingGzip or EnableAcceptEncodingBrotli is true, CloudFront does two things:
- It adds a normalized form of the
Accept-Encodingheader to the cache key. Viewers that accept Brotli, gzip only, or neither end up in at most a few groups, not one entry per browser string. - It compresses eligible objects at the edge.
CloudFront compresses an object only if all of these hold:
- The viewer's
Accept-Encodingincludes gzip or Brotli. - The object's content type is one CloudFront treats as compressible, such as
text/html,text/css,application/javascript, andapplication/json. - The object is between 1,000 bytes and 10,000,000 bytes.
- The origin response includes a
Content-Lengthheader and has noContent-Encodingheader.
S3 supplies Content-Length. If you upload pre-compressed files with Content-Encoding: gzip, CloudFront serves them as stored and does not compress again. In that case you must make sure every viewer can handle gzip, since a viewer without gzip support would receive bytes it cannot read.
Checking the result
Request the same object twice and read the response headers:
curl -sI https://d111111abcdef8.cloudfront.net/assets/app.js | grep -i -E "x-cache|^age"
curl -sI https://d111111abcdef8.cloudfront.net/assets/app.js | grep -i -E "x-cache|^age"The first response normally shows X-Cache: Miss from cloudfront. The second shows X-Cache: Hit from cloudfront and an Age header giving the seconds since the object was cached. Now add a changing query string:
curl -sI "https://d111111abcdef8.cloudfront.net/assets/app.js?t=1" | grep -i x-cache
curl -sI "https://d111111abcdef8.cloudfront.net/assets/app.js?t=2" | grep -i x-cacheWith a policy that excludes query strings, both responses should be hits, because both requests share one key. With a policy that includes them, you would see a miss for each new value.
Common errors
- Including all cookies or all headers "to be safe". This splits the cache by values S3 never uses. Start with none and add a value only when the response actually differs.
- Changing the cache policy and expecting old objects to update. A new policy changes how future requests build keys. Existing entries stay under their old keys until they expire.
- Combining a header in the key with zero TTLs. CloudFront rejects a cache policy that places headers, cookies, or query strings in the key when the maximum TTL is 0. Those settings only make sense when caching is on.
- Forgetting that
Hostis not forwarded to S3 in the key. For an S3 origin, CloudFront sets theHostheader to the bucket's domain name. Do not try to build keys around it. - Mixing the old forwarded-values settings with cache policies. Legacy cache settings and cache policies cannot be used together on one behavior. Use cache policies for new work.
Exercise
A site on a private S3 origin uses the CachingOptimized policy. A marketing team starts sharing links like /index.html?utm_source=email and /index.html?utm_source=social. Do these links create extra cache entries, and what would change that?
Show answer
No. CachingOptimized puts no query strings in the cache key, so both URLs map to the same key and share one cached copy. They would create separate entries only if the cache policy included query strings (all, or utm_source in an allow list). That would lower the hit ratio without changing what S3 returns.
Exercise
S3 returns Access-Control-Allow-Origin based on the Origin request header. Which two settings do you need so each site receives the right CORS header, and why is a cache policy alone not enough if you only forward the header?
Show answer
Forward Origin to S3 (for example with the CORS-S3Origin origin request policy, or by listing it in the cache policy) and include Origin in the cache key (a cache policy with a header allow list containing Origin). If Origin is forwarded but not in the key, CloudFront can serve the copy cached for one site to a viewer from another site, with the wrong CORS header.