Sub topic 9
Serving content through CloudFront
This chapter assumes you know how S3 buckets, EC2 instances, and Application Load Balancers work, and that you have read the earlier chapters on how AWS prices data transfer and on the traffic paths that cost money. It covers how CloudFront changes the price of internet egress, what drives your cache hit ratio, and how to check that the savings are real.
Why a CDN lowers the bill
Serving content straight from S3 or EC2 to the internet is billed as data transfer out to the internet, at the origin's rate. CloudFront is a content delivery network (CDN). It caches copies of your content at edge locations close to viewers. This changes your costs in three ways:
- Transfer from an AWS origin (S3, ALB, EC2) to CloudFront is not charged. You pay CloudFront's own per-GB rate for the data it sends to viewers.
- A cache hit never reaches the origin. A popular file can be requested a million times and leave the origin once per edge cache.
- CloudFront's free tier includes 1 TB of data transfer out and 10 million requests each month. CloudFront's per-GB rates also drop as volume grows through its pricing tiers.
CloudFront also bills per request, in units of 10,000 requests. For very small objects at high volume, the request charge can outweigh the transfer charge. Check current rates on the CloudFront pricing page, because they vary by the geographic region of the viewer.
How a request flows
A viewer request goes to the nearest edge location. On a miss, CloudFront checks a regional edge cache, a larger cache that serves many edge locations. Only then does it contact the origin.
Each layer that answers a request is a layer where origin transfer and origin compute are avoided. The goal of every tuning step below is to move more requests up this chain.
The cache hit ratio
The cache hit ratio is the share of requests answered from cache. It is the single number that predicts your savings. Three settings control it.
The cache key
The cache key is the set of request attributes CloudFront uses to decide whether two requests want the same object. By default it includes the URL path and the host. Anything you add to the key splits one object into many cached copies.
Common mistakes:
- Forwarding all query strings. A tracking parameter such as
?utm_source=...makes every campaign link a separate cache entry. - Forwarding all cookies. A session cookie gives every user their own copy of an otherwise identical image.
- Forwarding headers such as
User-Agent. It has thousands of distinct values.
Include only the attributes that change the response. For static assets, that is usually nothing beyond the path.
Time to live
Time to live (TTL) is how long an object stays in cache before CloudFront revalidates it with the origin. A short TTL on static files forces repeated origin fetches. CloudFront takes TTL from the cache policy's minimum, default, and maximum values and from the origin's Cache-Control and Expires headers. If the origin sends Cache-Control: max-age=31536000, CloudFront honors it within the minimum and maximum bounds in the cache policy.
A practical pattern is to give static files versioned names such as app.3f9c2a.js, set a long TTL, and change the name when the content changes. You get a near-permanent cache without needing invalidations.
Invalidations
An invalidation removes objects from cache before their TTL expires. The first 1,000 invalidation paths each month are free, and each path after that is charged. A wildcard path such as /images/* counts as one path. Frequent invalidation also lowers your hit ratio, so prefer versioned file names to routine invalidation.
Creating a cache policy
A cache policy defines the cache key and the TTLs. The following policy forwards no headers, cookies, or query strings, and enables compression variants. First save the policy as cache-policy.json:
{
"Name": "static-assets-long-ttl",
"Comment": "Path-only cache key for versioned static files",
"DefaultTTL": 86400,
"MaxTTL": 31536000,
"MinTTL": 1,
"ParametersInCacheKeyAndForwardedToOrigin": {
"EnableAcceptEncodingGzip": true,
"EnableAcceptEncodingBrotli": true,
"HeadersConfig": { "HeaderBehavior": "none" },
"CookiesConfig": { "CookieBehavior": "none" },
"QueryStringsConfig": { "QueryStringBehavior": "none" }
}
}Then create it:
aws cloudfront create-cache-policy \
--cache-policy-config file://cache-policy.jsonThe command returns a policy ID. Attach that ID to a cache behavior in your distribution. A cache behavior is a rule that maps a path pattern, such as /static/*, to an origin and a cache policy.
Use separate behaviors for separate content types. Static files go under a long-TTL, path-only policy. Dynamic API paths use a policy that forwards the headers or query strings the application needs, or the managed CachingDisabled policy if responses must never be cached.
Compression at the edge
CloudFront can compress responses with gzip or Brotli, which reduces the bytes billed as data transfer out. The cache policy setting in the previous example enables it. The conditions are:
- The behavior must have compression turned on.
- The viewer must send an
Accept-Encodingheader that includesgziporbr. - The object must be between 1,000 bytes and 10,000,000 bytes.
- The
Content-Typemust be one CloudFront treats as compressible, such as HTML, CSS, JavaScript, and JSON. Images such as JPEG and PNG are already compressed and are left alone. - The origin must not have compressed the response already.
Text responses often shrink by well over half, and the billed bytes shrink with them. The chapter on compression and smaller payloads covers this in more detail.
Keeping the origin cheap and private
Two origin settings protect the savings.
For S3 origins, use origin access control (OAC) and block public access on the bucket. Then viewers cannot bypass CloudFront and fetch objects directly at the higher S3 internet egress rate.
For an ALB or EC2 origin, restrict the origin's security group to CloudFront using the AWS-managed prefix list for CloudFront origin-facing servers. This keeps users from hitting the origin directly. You can also add a secret custom header at the distribution and require it at the origin.
CloudFront also offers Origin Shield, an additional caching layer in front of the origin. It collapses misses from many regions into one request to the origin. It is billed per request, so it pays off only when the origin is expensive to hit or when many regional caches request the same objects. For most static workloads, the regional edge cache is enough.
Measuring whether it works
Check the cache hit ratio before and after any change. The CacheHitRate metric is available in CloudWatch once you enable additional metrics on the distribution, which carries an extra charge. CloudFront metrics are published in us-east-1.
aws cloudwatch get-metric-statistics \
--region us-east-1 \
--namespace AWS/CloudFront \
--metric-name CacheHitRate \
--dimensions Name=DistributionId,Value=E123EXAMPLE Name=Region,Value=Global \
--start-time 2026-11-19T00:00:00Z \
--end-time 2026-11-26T00:00:00Z \
--period 86400 \
--statistics AverageReplace E123EXAMPLE with your distribution ID. The command returns one daily average for the week. In the CloudFront console, the Cache statistics report shows the same ratio without extra metrics, along with the most requested objects and the top misses.
If the ratio is low, read the standard logs or real-time logs for the x-edge-result-type field. Values of Miss and RefreshHit show which objects keep returning to the origin. The usual causes are query strings in the cache key, short TTLs, and Cache-Control: no-store sent by the origin.
Then compare cost lines in Cost Explorer. Group by usage type and look at your internet data transfer out lines for the origin service against the CloudFront data transfer lines. A successful rollout shows the origin line shrinking while the CloudFront line grows by less than the amount saved.
Common pitfalls
| Symptom | Likely cause | Fix |
|---|---|---|
| Low hit ratio on static files | Query strings or cookies in the cache key | Remove them from the cache policy |
| Origin still shows high egress | Viewers reach the origin directly | Use OAC or a CloudFront-only security group |
| Many origin fetches after deploys | Invalidating `/*` on every release | Use versioned file names |
| Responses not compressed | Object under 1,000 bytes, or an incompressible type | Check size and content type |
| High request charges | Many tiny objects | Bundle assets, raise TTLs, or lower request counts |
Summary of decisions
- Put every public, cacheable path behind CloudFront and block direct access to the origin.
- Build the narrowest cache key that still returns correct responses.
- Set long TTLs on versioned static files.
- Turn on gzip and Brotli.
- Measure the hit ratio, then compare the origin and CloudFront cost lines.
Exercise
A distribution serves product images from S3. The hit ratio is 35%. The cache policy forwards all query strings, and marketing links append ?utm_campaign=... to image URLs. What change would you make, and why does it reduce transfer cost?
Show answer
Change the cache policy so query strings are not part of the cache key (QueryStringBehavior set to none), or forward only the parameters that change the image. Each distinct utm value creates a separate cache entry, so identical images are fetched from the origin repeatedly and counted as misses. With the parameters out of the key, one cached copy serves all of them, the hit ratio rises, and fewer requests reach the origin.
Exercise
Why is it risky to set Cache-Control: no-store on an S3 origin for static JavaScript files, and what would you use instead?
Show answer
CloudFront will not cache the files, so every request goes to the origin and you lose the benefit of the free origin-to-CloudFront leg and cache hits. Use versioned file names with a long max-age (or a long default TTL in the cache policy), and change the name when the content changes.