Sub topic 15
Monitoring cache performance and understanding cost
This chapter assumes you have a working distribution with a private S3 origin (Origin Access Control and a bucket policy), and that you know cache policies, TTLs, and invalidations from earlier chapters. You should be comfortable running AWS CLI commands and reading basic Python.
After the chapter you should be able to:
- Read the cache hit ratio from CloudFront reports and logs.
- Explain which metrics are free and which cost extra.
- Estimate a monthly delivery bill from traffic numbers.
What to measure
A distribution succeeds when most requests are answered at the edge and few reach S3. Four signals tell you whether that is happening.
- Cache hit ratio: the share of requests served from an edge cache.
- Error rates: 4xx and 5xx responses, split by status code where possible.
- Origin latency: how long S3 takes to answer a miss.
- Traffic volume: requests and bytes, which drive the bill.
Each signal comes from a different source, and the sources differ in cost, detail, and delay.
Console reports and CloudWatch metrics
The CloudFront console has a Monitoring tab per distribution. It charts requests, bytes downloaded, and error rates. CloudFront also publishes these metrics to CloudWatch automatically at no charge.
| Metric | What it tells you | Cost |
|---|---|---|
| `Requests` | Total viewer requests | Included |
| `BytesDownloaded` | Bytes sent to viewers | Included |
| `BytesUploaded` | Bytes sent to the origin by POST or PUT | Included |
| `4xxErrorRate`, `5xxErrorRate`, `TotalErrorRate` | Percentage of requests with errors | Included |
| `CacheHitRate` | Percentage of cacheable requests served from cache | Additional metrics, extra charge |
| `OriginLatency` | Time from edge request to first byte from origin | Additional metrics, extra charge |
| Error rate per status code (for example `401ErrorRate`, `404ErrorRate`) | Which specific errors occur | Additional metrics, extra charge |
CloudFront is a global service, so all of its CloudWatch metrics live in the us-east-1 Region. The namespace is AWS/CloudFront, and the dimensions are DistributionId and Region=Global. If your alarms or dashboards show no data, check that you are looking in us-east-1.
You can enable the additional metrics per distribution from the Monitoring tab. They are billed per distribution per month, so enable them where the hit ratio matters and not everywhere.
This command pulls hourly request counts for one day:
aws cloudwatch get-metric-statistics \
--region us-east-1 \
--namespace AWS/CloudFront \
--metric-name Requests \
--dimensions Name=DistributionId,Value=EDFDVBD6EXAMPLE Name=Region,Value=Global \
--start-time 2026-11-25T00:00:00Z \
--end-time 2026-11-26T00:00:00Z \
--period 3600 \
--statistics SumThe CacheHitRate metric counts only cacheable requests. A request that a policy marks as uncacheable (for example, a minimum TTL of 0 with Cache-Control: no-store from the origin) does not appear in that ratio. A distribution with a 95% hit rate can still send most of its traffic to the origin if most of that traffic is uncacheable.
Logs: the detailed view
Metrics show trends. Logs show which paths cause misses. CloudFront offers two kinds.
- Standard logs are delivered as gzipped, tab-separated files to an S3 bucket, usually within minutes but with no guarantee. They are cheap to produce, and you pay only for storing and querying them.
- Real-time logs go to Kinesis Data Streams within seconds. You choose the fields and a sampling rate. They suit alerting and live dashboards, and they are billed per log line plus Kinesis charges.
Both include the field x-edge-result-type, which records what the edge did with the request.
| Value | Meaning |
|---|---|
| `Hit` | Served from the edge cache |
| `RefreshHit` | Object was stale, edge revalidated with the origin, and the origin said it was unchanged |
| `OriginShieldHit` | Served from the Origin Shield cache, if you enabled it |
| `Miss` | Fetched from the origin |
| `Error` | The request or response failed |
| `Redirect` | Edge redirected HTTP to HTTPS |
| `LimitExceeded`, `CapacityExceeded` | Request rejected because of limits or capacity |
Do not write standard logs into the bucket that holds your site content. Use a separate logging bucket, and add a lifecycle rule to expire old logs. Otherwise log storage grows without limit and mixes with the content you serve.
Computing a hit ratio from standard logs
This script reads downloaded log files and counts result types. It finds the column from the #Fields: header line, so it keeps working if the field order changes.
import gzip
import sys
from collections import Counter
def count_results(paths):
counts = Counter()
for path in paths:
with gzip.open(path, "rt") as f:
fields = None
for line in f:
if line.startswith("#Fields:"):
fields = line.split()[1:]
continue
if line.startswith("#") or not line.strip():
continue
row = line.rstrip("\n").split("\t")
counts[row[fields.index("x-edge-result-type")]] += 1
return counts
if __name__ == "__main__":
counts = count_results(sys.argv[1:])
total = sum(counts.values())
hits = counts["Hit"] + counts["RefreshHit"] + counts["OriginShieldHit"]
for name, n in counts.most_common():
print(f"{name:20} {n}")
if total:
print(f"hit ratio: {hits / total:.1%} of {total} requests")Run it as python hit_ratio.py logs/*.gz. This ratio counts every request, including uncacheable ones, so it is lower than the CacheHitRate metric for the same period.
Finding the cause of a low hit ratio
If the ratio is lower than you expect, group the Miss lines by cs-uri-stem and cs-uri-query and look for patterns.
- Many distinct query strings on the same path. The cache policy includes query strings in the cache key, so each variant is a separate object. Forward only the parameters the origin uses, or none.
- Cookie or header values in the cache key. The same problem applies. Each distinct cookie value creates a separate cache entry.
- Short TTLs. Objects expire before they are requested again. Raise the TTL, and use versioned file names so a long TTL is safe.
- Frequent invalidations. Each one empties entries that would otherwise hit.
- Low traffic per object. A rarely requested file may expire from edge caches before its next request. Nothing is wrong, and Origin Shield can help by adding a second cache layer.
Cache-Control: no-storeorprivateon objects. Check the metadata you set when uploading to S3.
A request for a missing key also shows as a miss. Check sc-status for 403 and 404 responses. With a private bucket, S3 returns 403 for a missing key unless the policy grants s3:ListBucket, so a spike in 403 errors can mean broken links and not a permissions fault.
Understanding the bill
CloudFront charges mostly for four things:
- Data transfer out to viewers, priced per GB. The rate depends on the viewer's geographic region and drops at higher monthly volumes.
- Requests, priced per 10,000. HTTPS requests cost more than HTTP, and the rate varies by region.
- Invalidation paths. The first 1,000 paths per month are free, then each extra path is charged. A wildcard like
/css/*counts as one path. - Optional features: real-time logs, additional metrics, Origin Shield, Lambda@Edge, CloudFront Functions, and dedicated IP custom SSL.
Transfer from S3 to CloudFront is free. So a higher hit ratio does not make CloudFront cheaper, but it removes S3 GET request charges and speeds up responses. Serving the same traffic directly from S3 would bill internet data transfer out from S3 instead.
CloudFront also has a monthly free tier that covers a fixed amount of data transfer out and a fixed number of requests. Check the current pricing page for the exact allowances and rates, because both change.
A worked estimate
The rates below are made-up round numbers chosen to show the arithmetic. Replace them with current prices for your regions. The example also ignores the free tier.
gb_out = 500
requests = 5_000_000
rate_per_gb = 0.085 # example rate, USD
rate_per_10k_requests = 0.01 # example rate, USD
transfer_cost = gb_out * rate_per_gb
request_cost = requests / 10_000 * rate_per_10k_requests
print(f"transfer: ${transfer_cost:.2f}")
print(f"requests: ${request_cost:.2f}")
print(f"total: ${transfer_cost + request_cost:.2f}")This prints $42.50 for transfer, $5.00 for requests, and $47.50 in total. Use the BytesDownloaded and Requests metrics for a real month to fill in gb_out and requests, and divide BytesDownloaded by 1,000,000,000 (or by 2^30, depending on how the pricing page defines a GB).
Ways to lower the bill:
- Compress text assets so fewer bytes leave the edge. Gzip or Brotli compression is a cache policy setting.
- Resize and compress images before upload.
- Prefer a price class that excludes the most expensive regions if your viewers are mostly elsewhere. Viewers outside those regions may see higher latency.
- Avoid wide invalidations. Use versioned file names instead.
Alarms worth creating
5xxErrorRateabove a small threshold for several periods. This often means S3 or a function is failing.TotalErrorRateabove your normal level. This catches broken deploys that delete files.Requestsfar above the daily baseline. This flags abuse or runaway clients.CacheHitRatebelow your target, if you pay for additional metrics.
Create these alarms in us-east-1, because the metrics are published there.
Exercise
A site's standard logs show 40% Miss results for /api-docs/page.html. The URLs look like /api-docs/page.html?utm_source=a, ?utm_source=b, and so on, with thousands of distinct values. S3 ignores query strings. What is the likely cause, and what is the fix? Also, why does the CacheHitRate metric for the same period read higher than the ratio you compute from the logs?
Show answer
The cache policy includes all query strings in the cache key, so each utm_source value is stored as a separate object and misses on first request. Change the cache policy so it does not forward query strings (or forwards only the ones the origin uses). The CacheHitRate metric counts only cacheable requests, while a ratio from logs divides hits by every request, including uncacheable ones, so the metric reads higher.