What does putting CloudFront in front of an API actually change in your bill?
Without CloudFront, your API's responses leave AWS as internet egress, billed at the origin's data transfer out rate, and every request reaches your compute. With CloudFront in front, transfer from AWS origins (ALB, EC2, API Gateway, S3) to CloudFront is not billed as egress. The internet-facing spend moves to CloudFront's own per-request and per-GB transfer pricing.
Request flow: Client → Edge location (request fee + bytes to client billed) → Origin Shield, optional (request fee on requests it handles) → Origin (compute billed per request that reaches it; response bytes to CloudFront not billed as egress)
Note one exception. Bytes CloudFront sends to the origin, such as POST and PUT bodies, are billed as data transfer out to origin. Upload-heavy APIs see less benefit.
The savings come from two independent levers:
| Lever | Applies to | What it reduces | Why it works |
|---|---|---|---|
| Egress pricing + compression | All traffic, including uncacheable | Per-GB transfer cost | CloudFront transfer rates can be lower than origin egress, and edge compression shrinks JSON payloads before they are billed |
| Origin offload | Cache hits only | Compute, database queries, autoscaling headroom | A hit is answered at the edge, so the origin never runs the handler |
The first lever helps even if you cache nothing. The second depends on your hit ratio and often matters more, because it shrinks your fleet and database tier as well as your transfer bill.
List prices vary by region and change over time. Check the current CloudFront and data transfer pricing pages, and compare them against your own negotiated, private, or committed-use rates. A discount on either side can reverse the egress comparison.
Legend: [R] CloudFront request fee [T] CloudFront transfer to client
[U] data transfer out to origin (POST/PUT bodies)
[C] origin compute + DB per request [F] not billed as egress
+----------------+
| Client |
+----------------+
| ^
| request | response bytes [T]
v |
+----------------+
| Edge location | cache hit: answered here, origin never runs
| cache [R] |
+----------------+
| ^
| miss | response
v |
+----------------+
| Origin Shield | optional regional cache layer;
| (optional) [R] | [R] applies to requests it handles
+----------------+
| ^
| miss | response bytes [F]
| body [U] |
v |
+----------------+
| Origin | ALB / EC2 / API Gateway / S3
| [C] per req |
+----------------+
Request flow through CloudFront to an AWS origin, showing where request fees, transfer to clients, upload bytes to the origin, and origin compute are billed, and which hop is not billed as egress.
How does CloudFront caching work for API responses?
CloudFront decides whether a request is a hit by computing a cache key. By default the key is the host and URL path. The cache policy extends it with whichever headers, cookies and query strings you list, and every value you add is also forwarded to the origin. The origin request policy is separate. It forwards additional values to the origin without adding them to the key, so you can pass something like a tracing header that your backend logs but that never changes the response body.
Mixing the two up is the most common way to lose hit ratio. If a cache policy includes all query strings, all cookies or a header such as User-Agent, nearly every request gets a unique key. The distribution still works, but hits approach zero and you pay CloudFront request fees on top of full origin load. Key only on the inputs that change the response, for example page, limit and Accept-Language for a catalog listing.
The origin's Cache-Control header should be the source of truth. A response such as Cache-Control: public, max-age=30, s-maxage=300 lets CloudFront hold the object for 300 seconds, because s-maxage takes precedence for shared caches, while browsers keep it for 30. The cache policy's TTLs set the bounds:
- Maximum TTL caps whatever the origin requests.
- Default TTL applies only when the origin sends no caching headers.
- Minimum TTL sets a floor. If it is above zero, CloudFront will cache responses even when they are marked
no-storeorprivate. Keep it at 0 for APIs.
CloudFront caches only GET and HEAD by default, with OPTIONS available as an option. POST, PUT, PATCH and DELETE always pass through to the origin.
# Expected origin response for GET /v1/catalog?page=2&limit=50:
# Cache-Control: public, max-age=30, s-maxage=300
# Vary: Accept-Language
# Per-user endpoints should send Cache-Control: private or no-store.
Resources:
CatalogCachePolicy:
Type: AWS::CloudFront::CachePolicy
Properties:
CachePolicyConfig:
Name: catalog-api-cache
Comment: Key only on inputs that change the catalog response
MinTTL: 0 # Floor of 0 so no-store and private are honored
DefaultTTL: 60 # Used only when the origin sends no caching headers
MaxTTL: 3600 # Caps whatever s-maxage or max-age the origin sends
ParametersInCacheKeyAndForwardedToOrigin:
EnableAcceptEncodingGzip: true
EnableAcceptEncodingBrotli: true
HeadersConfig:
HeaderBehavior: whitelist
Headers: [Accept-Language]
CookiesConfig:
CookieBehavior: none # Session cookies would make every key unique
QueryStringsConfig:
QueryStringBehavior: whitelist
QueryStrings: [page, limit] # Tracking params like utm_* are dropped
CatalogOriginRequestPolicy:
Type: AWS::CloudFront::OriginRequestPolicy
Properties:
OriginRequestPolicyConfig:
Name: catalog-api-origin
Comment: Forward to origin without adding to the cache key
HeadersConfig:
HeaderBehavior: whitelist
Headers: [X-Request-Id] # Logged by the backend, never changes the body
CookiesConfig:
CookieBehavior: none
QueryStringsConfig:
QueryStringBehavior: none # Key params are already forwarded by the cache policy
A CloudFormation cache policy that keys only on page, limit and Accept-Language with a zero minimum TTL, paired with an origin request policy that forwards a tracing header without fragmenting the cache, alongside the origin Cache-Control header it relies on.
Which API endpoints are realistically cacheable?
The question is not whether an endpoint is a GET. It is whether many callers send the same request within a useful window.
| Endpoint type | Example | Suggested directives | TTL range |
|---|---|---|---|
| Public reference data | Currency codes, country lists | public, max-age, s-maxage |
Hours to a day |
| Catalog and config | Product catalog, feature flags | public, s-maxage, stale-while-revalidate |
1–15 minutes |
| Paginated lists | Search, "latest" feeds | public, s-maxage |
5–60 seconds |
| Per-tenant data | Tenant settings | private to browsers, s-maxage with the tenant ID in the cache key |
Seconds to minutes |
| Personalized or dynamic | Cart, balances | no-store |
None |
Per-tenant caching is only safe when the cache key includes a validated tenant identifier. Never derive the key from a client-supplied value that the origin does not also enforce.
Why seconds matter (illustrative estimate): Assume a hot endpoint receives 500 identical requests per second, spread across 10 edge locations. With a 5-second TTL, each location fetches roughly once per 5 seconds. That is about 2 origin requests per second instead of 500. CloudFront also collapses simultaneous misses for the same key into a single origin fetch.
The long tail: Endpoints with low traffic behave differently. Each edge location warms its own cache, so a request that arrives a few times per hour across many locations rarely hits a warm entry. Origin shield adds a central caching layer, which raises hit ratios for these endpoints. It also bills its own request charge on traffic that passes through it.
The APIs that benefit most are read-heavy and serve repeated identical requests.
Worked cost model: origin-direct vs CloudFront-fronted
Illustrative estimate (assumed numbers, not a benchmark). Replace every rate with your own contract or pricing-page figures.
Assumed inputs: 100M requests/month, 20 KB average JSON response, 4:1 edge compression, 60% hit ratio, $0.000002 origin compute per request. Placeholder rates: origin egress $0.09/GB, CloudFront egress $0.085/GB, CloudFront requests $1.00 per million, origin-to-edge transfer $0 (confirm this for your origin type).
| Scenario | Egress | Request fees | Origin compute | Total |
|---|---|---|---|---|
| Origin-direct, uncompressed | $180.00 | $0 | $200.00 | $380.00 |
| CloudFront, 60% hits, compressed | $42.50 | $100.00 | $80.00 | $222.50 |
| Origin-direct, origin already compresses | $45.00 | $0 | $200.00 | $245.00 |
| CloudFront, 0% hits (uncacheable) | $42.50 | $100.00 | $200.00 | $342.50 |
The model has two separate levers. The egress lever is fewer billed bytes. Edge gzip or Brotli applies only to eligible content types and size ranges, and only when the client sends Accept-Encoding. JSON compresses well because it repeats keys, whitespace, and a small character set. If your origin already compresses, this lever mostly disappears. The offload lever is the share of requests that never reach origin compute, which scales with the hit ratio.
The last row shows the risk. With nothing cacheable, request fees are added on top and nothing is offset.
The break-even hit ratio per request, with B as response size in GB, is:
h* = (B_edge·P_cf + P_req − B_origin·P_origin) / C_origin
In spreadsheet form: =(B_edge*P_cf + P_req - B_origin*P_origin)/C_origin
For the compressed-origin case, h* ≈ 0.49, so CloudFront needs roughly a 49% hit ratio to break even. A negative h* means CloudFront is cheaper at any hit ratio.
# Illustrative estimate: placeholder rates, replace with your own pricing.
# Assumes origin-to-edge transfer is $0 and 1 GB = 1,000,000 KB (decimal).
REQS = 100_000_000 # requests per month
RESP_KB = 20 # average uncompressed JSON response
COMPRESSION = 4 # 4:1 edge compression (eligible types only)
HIT = 0.60 # cache hit ratio
C_ORIGIN = 0.000002 # origin compute cost per request ($)
P_ORIGIN = 0.09 # origin egress $/GB (placeholder)
P_CF = 0.085 # CloudFront egress $/GB (placeholder)
P_REQ = 1.00 / 1_000_000 # CloudFront request fee per request (placeholder)
B_raw = RESP_KB / 1_000_000 # GB per response, uncompressed
B_comp = B_raw / COMPRESSION # GB per response, compressed
def origin_direct(b):
# Every request hits origin compute and is billed as origin egress.
return REQS * (b * P_ORIGIN + C_ORIGIN)
def cloudfront(b_edge, hit):
# Egress lever: billed bytes at edge. Offload lever: only misses reach compute.
return REQS * (b_edge * P_CF + P_REQ + (1 - hit) * C_ORIGIN)
def break_even_hit(b_edge, b_origin):
# h* = (B_edge*P_cf + P_req - B_origin*P_origin) / C_origin
return (b_edge * P_CF + P_REQ - b_origin * P_ORIGIN) / C_ORIGIN
print(f"Origin-direct, uncompressed: ${origin_direct(B_raw):,.2f}")
print(f"CloudFront, {HIT:.0%} hits, compressed: ${cloudfront(B_comp, HIT):,.2f}")
print(f"Origin-direct, origin compresses: ${origin_direct(B_comp):,.2f}")
print(f"CloudFront, 0% hits: ${cloudfront(B_comp, 0.0):,.2f}")
h = break_even_hit(B_comp, B_comp)
# Negative h* means CloudFront wins at any hit ratio; above 1 means it never wins.
print(f"Break-even hit ratio vs compressed origin: {h:.2%}")
A plug-in-your-own-rates Python script that reproduces the four illustrative scenarios and computes the break-even hit ratio. With the placeholder inputs, the break-even comes out to about 48.75%.
How do you implement and measure origin offload safely?
Lock down the origin first
Offload only saves money if clients can't skip the CDN. If the origin stays publicly reachable, scrapers and misconfigured clients will hit it directly, and you pay origin egress and compute at full rate. For supported origins such as S3, use origin access control. For custom origins like load balancers or API gateways, combine two controls. First, restrict inbound traffic to the AWS-managed prefix list for CloudFront origin-facing addresses. Second, have CloudFront add a secret custom header that the origin validates and that you rotate. The prefix list alone is not enough, because any CloudFront distribution, including someone else's, sends traffic from those same addresses.
Roll out narrowly
Enable caching one cache behavior at a time, starting with the path patterns you classified as cacheable. Set error caching TTLs on purpose. A long TTL on a 5xx keeps an outage cached after the origin recovers. A TTL of zero sends every retry during an incident straight to a struggling origin.
Prefer versioned URLs or correctly sized TTLs over invalidations. Invalidations become billable beyond a monthly free allowance. They also take time to propagate, so stale data can still be served after you issue one.
Measure against the origin
Track the cache hit ratio and origin request counts from CloudFront metrics, plus standard or real-time logs. In the logs, group requests by path and count those whose x-edge-result-type is Hit or RefreshHit, then divide by the total requests for that path. That gives the hit ratio for each endpoint.
Then compare against the break-even h* calculated above, using origin-side data from before and after rollout: request volume, compute utilization, and database load. A high edge hit ratio is meaningless if origin load doesn't fall, because that usually points to a bypass path or a cache key that fragments.
-- Athena query over CloudFront standard logs, using the table layout from the AWS docs.
-- In that layout the result_type column holds the x-edge-result-type field.
-- Rename columns to match your own table definition.
SELECT
-- Collapse numeric IDs so /v1/items/123 and /v1/items/456 count as one endpoint
regexp_replace(uri, '/[0-9]+', '/{id}') AS path,
count(*) AS total_requests,
-- Served from the edge cache without contacting the origin
sum(CASE WHEN result_type = 'Hit' THEN 1 ELSE 0 END) AS hits,
-- Cached but expired; the origin was asked to revalidate it, which is a cheap request
-- but still an origin request
sum(CASE WHEN result_type = 'RefreshHit' THEN 1 ELSE 0 END) AS refresh_hits,
-- Hit ratio as defined in the text: (Hit + RefreshHit) / total
round(
CAST(sum(CASE WHEN result_type IN ('Hit', 'RefreshHit') THEN 1 ELSE 0 END) AS double)
/ count(*), 4) AS hit_ratio,
-- Stricter ratio: only requests that fully avoided the origin
round(
CAST(sum(CASE WHEN result_type = 'Hit' THEN 1 ELSE 0 END) AS double)
/ count(*), 4) AS full_offload_ratio
FROM cloudfront_logs
-- Pick a window that matches your before/after comparison of origin metrics
WHERE "date" BETWEEN DATE '2026-10-01' AND DATE '2026-10-14'
AND uri LIKE '/api/%'
GROUP BY 1
HAVING count(*) > 1000 -- drop low-traffic paths whose ratios are noise
ORDER BY total_requests DESC
LIMIT 50;
An Athena query over CloudFront standard logs that computes the per-endpoint hit ratio from the x-edge-result-type field, reporting a separate stricter ratio because RefreshHit responses still reach the origin.
When should you avoid CloudFront in front of an API, and what are the risks?
The biggest risk is correctness, not cost. A cache key defines which requests CloudFront treats as identical. If a response varies by the Authorization header, a tenant ID, or a session cookie, and that value is not in the cache key, CloudFront can serve one user's response to another. This is a data leak, and no error will flag it. Either keep personalized routes uncached or include the varying value in the key. Then confirm the key matches how the origin actually varies its responses.
Staleness is the quieter risk. Invalidations take time to propagate and are billed beyond a free allowance, so most teams rely on short TTLs instead. A short TTL still allows outdated responses for its full duration. Endpoints that clients read right after writing will show that lag.
Debugging also gets harder. Edge and origin each have their own timeouts. CloudFront adds or strips headers, and it can briefly cache origin error responses. As a result, one 5xx can look like an ongoing outage. Header-handling rules and policy limits may also force changes to your API, such as moving variation from custom headers to query strings.
A mostly uncacheable API can still benefit from CloudFront for three reasons:
- TLS handshakes complete at an edge location close to the user.
- CloudFront reuses persistent connections back to the origin, which cuts connection setup overhead.
- It gives you a single place to attach AWS WAF and to absorb attacks with Shield.
If you need none of these, and clients sit near your region or call server-to-server, every request pays CloudFront's per-request and transfer fees on top of origin costs. In that case CloudFront adds cost without offloading anything from the origin.
What are the alternatives, and how do they affect engineering time and cost?
For those workloads, and often before reaching for a CDN at all, cheaper levers exist. Each one shifts cost between your bill and engineering time differently.
- Application-level caching (an in-process cache or a managed cache in front of the database) cuts database load and latency but not egress. You also own invalidation logic in code, which grows with every new query path.
- API Gateway response caching, where your API type supports it, is a provisioned cache billed by the hour whether or not it gets hits. It suits steady, moderate read traffic in one region.
- ETag and conditional requests let clients revalidate and receive a 304 with no body. Bytes drop sharply, but the origin still handles every request.
- Compression and smaller payloads (field selection, pagination, dropping unused fields) lower egress for every response, including uncacheable ones.
Cache-friendly design is not free. Teams need agreed Cache-Control semantics, an explicit cache-key policy, and tests that prove a response for one user or tenant can never be served to another. The payoff is operational. Once a meaningful share of reads never reach the origin, the scaling footprint shrinks, and read spikes stop driving capacity planning and incident work.
| Traffic profile | Recommended approach |
|---|---|
| Global clients, shared public reads | CloudFront with explicit cache keys |
| Regional, server-to-server, personalized | App cache + compression |
| Moderate steady reads, single region | API Gateway caching (if supported) |
| Large, slowly changing per-user resources | ETag / conditional requests |
| Mostly writes or unique responses | Shrink payloads; skip caching |
How OneEnv can help
Disclosure: OneEnv is the product behind this blog.
OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.
Applied to cloudfront api caching costs, this is where it helps:
Saves time
- Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
- One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
Saves cost
- Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
- Less duplicated configuration to maintain: one shared definition inherited by many services.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.
These are qualitative benefits, not measured results — how much you save depends on how many services share the value.
Want to try it? Start at oneenv.io.