Short answer: a cache policy decides which parts of a request make up CloudFront's cache key (the headers, cookies and query strings that make two requests "different"), and how long CloudFront keeps a response. Anything in the cache key is also sent to your origin automatically. An origin request policy adds things your origin needs to see without putting them in the cache key. So: put a value in the cache key only if the origin sends a different response for it. Everything else the origin merely wants to read goes in the origin request policy.
Two policies, two questions
Each cache behavior gets a cache policy (or the older legacy cache settings) and, optionally, an origin request policy:
| Policy | Answers | Changes the cache key? | Sets TTLs? |
|---|---|---|---|
| Cache policy | Which requests share a cached copy, and for how long? | Yes | Yes |
| Origin request policy | What else does the origin get on a cache miss? | No | No |
With nothing in either policy, CloudFront sends the origin the URL path, the body (if any) and headers it sets itself, such as X-Amz-Cf-Id, a Host of the origin's domain name and a User-Agent of Amazon CloudFront. The viewer's own headers, cookies and query strings stay out unless a policy includes them.
A useful way to think about it: the cache key is what CloudFront looks at when deciding whether it already has the answer. The origin request policy is extra information it passes along when it doesn't.
Why the cache key hurts your hit rate
Every value you add to the cache key splits the cache. CloudFront keeps one copy per combination of values, so a header with many possible values means many copies, more misses and more requests to your origin.
User-Agenthas thousands of values. Caching on it effectively turns the cache off. AWS recommends against caching on it (or onDate). If the origin varies by device, cache onCloudFront-Is-Mobile-Viewerand its siblings instead: CloudFront sets them totrueorfalsefrom the user agent.- All cookies in the cache key means a visitor with an analytics cookie gets their own copy of every page. If the origin varies by one cookie, include just that cookie.
- All query strings means
?utm_source=newslettercreates a new copy. Include only the parameters that change the response.
If the origin only needs to see a value (for logging, analytics or a redirect that doesn't change the cached response), forward it with the origin request policy instead. The origin still gets it on every miss, and the cache stays shared.
A cache policy can only list headers by name; there's no "all headers" option. An origin request policy can forward all viewer headers, all except some, or a list. By default each policy can list up to 10 headers, 10 cookies and 10 query strings (you can ask AWS for more), with their names adding up to no more than 1,024 characters.
The managed policies
CloudFront provides ready-made policies, so most behaviors don't need a custom one. The cache policies you're most likely to use:
| Cache policy | Min / Default / Max TTL | In the cache key | Use it for |
|---|---|---|---|
| CachingOptimized | 1 s / 24 h / 1 year | Nothing (apart from compression) | Static files that are the same for everyone |
| CachingDisabled | 0 / 0 / 0 | Nothing | APIs and anything personal |
| UseOriginCacheControlHeaders | 0 / 0 / 1 year | Host, Origin, three method-override headers, all cookies | Origins that send Cache-Control and vary by cookie |
There's also UseOriginCacheControlHeaders-QueryStrings, the same with all query strings in the key. And the origin request policies:
| Origin request policy | Forwards | Use it for |
|---|---|---|
| AllViewer | Every viewer header, cookie and query string | Custom origins such as a load balancer |
| AllViewerExceptHostHeader | The same, but not Host (CloudFront sends the origin's own domain name), plus CloudFront's viewer headers such as location and device type | API Gateway and Lambda function URLs |
| CORS-S3Origin | Origin, Access-Control-Request-Headers, Access-Control-Request-Method | S3 buckets that answer CORS themselves |
| CORS-CustomOrigin | Origin | Custom origins that answer CORS themselves |
| UserAgentRefererHeaders | User-Agent, Referer | Origins that log or check them |
The common pairings are CachingDisabled with AllViewerExceptHostHeader for an API (nothing cached, everything forwarded) and CachingOptimized with no origin request policy for static files on S3. AWS recommends not forwarding headers to an S3 origin unless you need CORS (or personalise with Lambda@Edge), so for an S3 bucket with CORS add CORS-S3Origin, and put Origin in the cache key if S3's answer differs by origin (see Why your S3 CORS request is blocked).
Things that catch people out
Forwarding Authorization without caching on it. CloudFront removes Authorization from GET and HEAD requests unless a policy forwards it. You can forward it with an origin request policy (AllViewer does), but then it's not in the cache key, and CloudFront can serve one user's cached response to another user, or to someone with no credentials at all. AWS's advice is to either put Authorization in the cache key with a cache policy or turn caching off (CachingDisabled) for origins that check it.
Forwarding Host to API Gateway or a Lambda function URL. These origins expect their own domain name in Host. AllViewer forwards the viewer's Host (your distribution's domain), which can stop them working. Use AllViewerExceptHostHeader.
Adding Accept-Encoding yourself. Don't put it in either policy. Turn on the cache policy's Gzip and Brotli settings instead: CloudFront then normalises Accept-Encoding to br,gzip, gzip or br, puts that in the cache key and sends it to the origin. If the viewer supports neither, it leaves it out of the key and sends Accept-Encoding: identity. Adding Accept-Encoding to an origin request policy has no effect. Only enable them if your origin compresses or the behavior has CloudFront compression turned on, or the hit rate drops for nothing.
Expecting * to be a wildcard. In a cache policy's header and query string lists, * is a literal character. It only works as a wildcard in cookie names, such as userid_*.
Using a managed AllViewer policy with S3 and response-content-* parameters. With the managed AllViewer, AllViewerAndCloudFrontHeaders-2022-06 and AllViewerExceptHostHeader policies, CloudFront doesn't forward response-content-type, response-content-disposition or response-content-encoding to an S3 origin. Use a custom origin request policy if you rely on them.
How long CloudFront keeps a response
The cache policy's three TTLs work together with the Cache-Control and Expires headers your origin sends:
| The origin sends | Minimum TTL is 0 | Minimum TTL is more than 0 |
|---|---|---|
max-age (and no s-maxage) | max-age, capped at the Maximum TTL | max-age, kept between the Minimum and Maximum TTL |
s-maxage | s-maxage, capped at the Maximum TTL | s-maxage, kept between the Minimum and Maximum TTL |
no-cache, no-store or private | CloudFront respects the header | Cached for the Minimum TTL anyway |
No Cache-Control or Expires | The Default TTL | The greater of the Minimum and Default TTL |
Browsers use max-age, not s-maxage, whatever the TTLs say, so you can keep HTML at the edge for a few minutes while browsers check every time:
Cache-Control: public, max-age=0, s-maxage=300
Two consequences worth knowing:
- CachingOptimized's Minimum TTL is 1 second, so a
Cache-Control: no-storeresponse is still cached for a second. Use a policy with Minimum TTL 0 for anything personal. - CachingOptimized's Default TTL is 24 hours, and CDK's
Distributionuses CachingOptimized when you don't set a cache policy. HTML uploaded to S3 withoutCache-Controlis then cached for a day, and visitors keep getting the old page after a deploy unless you invalidate.
stale-while-revalidate and stale-if-error also work, up to the Maximum TTL. The HTTP caching explainer shows what browsers and CloudFront each do with a set of headers.
A setup that works
A site on S3 with an API under /api needs three behaviors. HTML follows the origin's Cache-Control with nothing in the cache key. Fingerprinted files (app.3f9c2b.js) use CachingOptimized. The API caches nothing and forwards everything except Host:
| Behavior | Cache policy | Origin request policy | Send from the origin |
|---|---|---|---|
Default (*) | Custom: TTLs 0 / 0 / 1 year, empty key | None | public, max-age=0, s-maxage=300 |
/assets/* | CachingOptimized | None | public, max-age=31536000, immutable |
/api/* | CachingDisabled | AllViewerExceptHostHeader | no-store |
In CDK:
const htmlCachePolicy = new cloudfront.CachePolicy(this, "HtmlCachePolicy", {
comment: "HTML: follow the origin's Cache-Control; nothing in the cache key",
minTtl: cdk.Duration.seconds(0),
defaultTtl: cdk.Duration.seconds(0),
maxTtl: cdk.Duration.days(365),
headerBehavior: cloudfront.CacheHeaderBehavior.none(),
cookieBehavior: cloudfront.CacheCookieBehavior.none(),
queryStringBehavior: cloudfront.CacheQueryStringBehavior.none(),
enableAcceptEncodingGzip: true,
enableAcceptEncodingBrotli: true,
});
const distribution = new cloudfront.Distribution(this, "Distribution", {
defaultRootObject: "index.html",
defaultBehavior: {
origin: siteOrigin,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: htmlCachePolicy,
compress: true,
},
additionalBehaviors: {
"/assets/*": {
origin: siteOrigin,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: cloudfront.CachePolicy.CACHING_OPTIMIZED,
compress: true,
},
"/api/*": {
origin: apiOrigin,
viewerProtocolPolicy: cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cachePolicy: cloudfront.CachePolicy.CACHING_DISABLED,
originRequestPolicy:
cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
allowedMethods: cloudfront.AllowedMethods.ALLOW_ALL,
compress: true,
},
},
});
html_cache_policy = cloudfront.CachePolicy(
self, "HtmlCachePolicy",
comment="HTML: follow the origin's Cache-Control; nothing in the cache key",
min_ttl=Duration.seconds(0),
default_ttl=Duration.seconds(0),
max_ttl=Duration.days(365),
header_behavior=cloudfront.CacheHeaderBehavior.none(),
cookie_behavior=cloudfront.CacheCookieBehavior.none(),
query_string_behavior=cloudfront.CacheQueryStringBehavior.none(),
enable_accept_encoding_gzip=True,
enable_accept_encoding_brotli=True,
)
distribution = cloudfront.Distribution(
self, "Distribution",
default_root_object="index.html",
default_behavior=cloudfront.BehaviorOptions(
origin=site_origin,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cache_policy=html_cache_policy,
compress=True,
),
additional_behaviors={
"/assets/*": cloudfront.BehaviorOptions(
origin=site_origin,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cache_policy=cloudfront.CachePolicy.CACHING_OPTIMIZED,
compress=True,
),
"/api/*": cloudfront.BehaviorOptions(
origin=api_origin,
viewer_protocol_policy=cloudfront.ViewerProtocolPolicy.REDIRECT_TO_HTTPS,
cache_policy=cloudfront.CachePolicy.CACHING_DISABLED,
origin_request_policy=cloudfront.OriginRequestPolicy.ALL_VIEWER_EXCEPT_HOST_HEADER,
allowed_methods=cloudfront.AllowedMethods.ALLOW_ALL,
compress=True,
),
},
)
Why not CachingOptimized for the HTML too? Its Default TTL would cache any page sent without Cache-Control for a day. And not UseOriginCacheControlHeaders? It puts every cookie in the cache key. The CloudFront policy builder generates the whole stack, including the bucket, Origin Access Control and response headers, for this and other setups.
