How does CloudFront change the way API data transfer out is billed?
Putting CloudFront in front of an API means clients resolve your API hostname to a CloudFront distribution instead of your load balancer or API endpoint. CloudFront terminates TLS at an edge location, serves cacheable responses itself, and forwards the rest to your origin over AWS's network. Teams usually do this for latency and TLS offload. The billing change matters just as much.
Without CloudFront, every response byte leaving your origin to a client is billed as internet data transfer out from the origin's region. With CloudFront, data transfer from AWS origins such as an Application Load Balancer, EC2, or S3 to CloudFront is generally not charged. CloudFront then bills its own per-GB data transfer out plus a per-request fee. A cache hit avoids origin compute entirely. A cache miss still avoids origin egress, but you pay CloudFront's rate for the bytes instead.
| Cost component | Direct from origin | Through CloudFront |
|---|---|---|
| Bytes to clients | Regional internet egress rate | CloudFront per-GB rate, varies by edge geography |
| Origin to edge | Not applicable | Generally not charged for AWS origins |
| Requests | Origin compute and load balancer usage | CloudFront per-request fee, plus origin cost on misses |
| Uploads (POST/PUT bodies) | Inbound, typically free | CloudFront charges data transfer to origin |
CloudFront rates depend on where clients are served from. Price classes restrict which edge regions are used. A lower price class excludes the more expensive regions, which reduces cost but can increase latency for users there. Rates change over time, so confirm current figures on the AWS pricing page. Committed-use or negotiated pricing can shift the comparison in either direction.
A) DIRECT FROM ORIGIN
+---------+ +-----------+
| Clients |<--------------------------------------------------| Origin |
| | internet data transfer out, regional egress rate | ALB/EC2/S3|
| |-------------------------------------------------->| |
+---------+ requests: origin compute + LB usage; uploads free +-----------+
B) THROUGH CLOUDFRONT
+---------+ CF per-GB, varies +--------------+ responses +-----------+
| Clients |<-------------------| CloudFront |<--------------| AWS origin|
| | by edge geography | edge (TLS, | origin->edge: | ALB, EC2, |
| |------------------->| cache) |-------------->| or S3 |
+---------+ requests, uploads +--------------+ generally not +-----------+
| charged
v
cache hit: served at edge, no origin call
cache miss: forwarded to origin
CloudFront billing:
- per-GB data transfer out to clients (rate set by edge region)
- per-request fee on every request, hit or miss
- data transfer to origin for upload bodies (POST/PUT)
- price class limits which edge regions, and therefore rates, apply
- origin compute applies only on cache misses
Direct origin egress is billed at the region's internet rate. Through CloudFront, AWS-origin-to-edge transfer is generally not charged, and CloudFront per-GB, per-request, and upload fees apply instead.
How do you estimate whether CloudFront will cut your API costs?
break-even point, so run the model with your own contract rates, not list prices.
The cost model
Monthly cost behind CloudFront = (edge egress GB × edge rate) + (edge requests × per-request rate) + (origin requests from cache misses × origin compute/LB cost per request) + (cache-miss GB × origin-to-edge transfer rate, often zero for AWS origins).
Compare that with your current bill: (origin egress GB × data transfer out rate) + (all requests × origin compute/LB cost per request).
CloudFront charges for every request it serves, including cache hits. The edge rate on GB may be lower than the origin's data transfer out rate, but a lower GB rate only helps if bytes dominate the bill. When requests dominate, the per-request fee can cost more than the GB savings.
Worked example
Illustrative estimate (assumed numbers, not a benchmark). The placeholder rates are $0.09/GB origin egress, $0.08/GB edge egress, $1.00 per million edge requests, $2.00 per million origin requests (compute plus load balancer), and $0 for origin-to-edge transfer.
| Scenario | Assumed traffic | Hit ratio | Direct to origin | Behind CloudFront |
|---|---|---|---|---|
| Chatty JSON API | 100M req × 2 KB ≈ 200 GB | 10% | $18 + $200 = $218 | $16 + $100 + $180 = $296 |
| Large catalog responses | 20M req × 200 KB ≈ 4,000 GB | 80% | $360 + $40 = $400 | $320 + $20 + $8 = $348 |
In the first scenario, 90% of requests miss the cache and still reach the origin. CloudFront adds a request fee on top of most of the original origin cost. In the second scenario, large payloads and a high hit ratio make the GB savings larger than the new request fees.
Which API responses can you cache safely?
Cacheability depends on whether one response body is correct for every caller who sends the same cache key. Public and semi-static GET endpoints such as product catalogs, feature-flag configuration and reference data (currencies, regions, tax tables) meet that test. They are also usually the endpoints with the largest payloads and the most repeated reads. Near-real-time data such as prices, inventory counts and leaderboards can still be cached if the TTL is a few seconds. Under heavy concurrent load, a 5-second TTL turns thousands of identical origin reads into roughly one per edge cache per interval.
Let the origin set the cache policy. Send Cache-Control with s-maxage for shared caches, and use stale-while-revalidate-style directives where your cache policy honors them. The service team then owns freshness decisions, and you avoid hard-coding a TTL in CloudFront that drifts from what the data needs.
| Endpoint type | Cache? | Typical TTL | Main risk |
|---|---|---|---|
| Catalog, reference data | Yes | Minutes to hours | Stale after a deploy |
| Prices, inventory | Yes, briefly | Seconds | Visible lag |
| Authenticated, per-user | Rarely | None | Cross-user leakage |
| Writes (POST/PUT) | No | — | Not applicable |
Per-user caching rarely pays off. Every user gets their own cache entry, each entry is read only a few times, and the hit ratio stays low. Routing that traffic through CloudFront can still be worth it for pricing alone: origin-to-CloudFront transfer is not billed as internet egress, so compare CloudFront's per-GB rate and request fees against your regional data transfer out rate.
Incorrect headers are the largest risk. If a missing private directive or an overly long max-age reaches a high-traffic route, every edge location serves the wrong or stale response until the TTL expires or you invalidate the cache.
// Origin-controlled caching: each route declares its own freshness policy,
// so CloudFront (configured to honor origin headers) needs no hard-coded TTLs.
const express = require('express');
const app = express();
// Reference data: identical for every caller, changes rarely.
// Browsers keep it 5 min; shared caches (s-maxage) keep it 1 hour and may
// serve a stale copy for 60s while refetching in the background.
app.get('/api/v1/currencies', (req, res) => {
res.set('Cache-Control', 'public, max-age=300, s-maxage=3600, stale-while-revalidate=60');
res.json(getCurrencies());
});
// Near-real-time data: a 5-second shared TTL collapses bursts of identical
// reads into roughly one origin request per edge cache per interval.
// max-age=0 stops browsers from holding it longer than the edge does.
app.get('/api/v1/prices/:sku', (req, res) => {
res.set('Cache-Control', 'public, max-age=0, s-maxage=5');
res.json(getPrice(req.params.sku));
});
// Per-user data: must never land in a shared cache. 'private' keeps it out
// of CloudFront; 'no-store' also keeps it out of browser storage.
app.get('/api/v1/me/orders', requireAuth, (req, res) => {
res.set('Cache-Control', 'private, no-store');
res.json(getOrdersFor(req.user.id));
});
// Writes are never cached; be explicit anyway so a misconfigured
// behavior cannot store the response.
app.post('/api/v1/orders', requireAuth, express.json(), (req, res) => {
res.set('Cache-Control', 'no-store');
res.status(201).json(createOrder(req.user.id, req.body));
});
app.listen(8080);
An Express origin sets Cache-Control per route: long s-maxage with stale-while-revalidate for reference data, a 5-second shared TTL for prices, and private/no-store for per-user responses and writes.
How do cache keys determine your hit ratio, and how can they leak user data?
Each request that misses the cache is billed twice: once as CloudFront data transfer out and again as an origin fetch, with origin compute on top. The cost model from earlier sections therefore depends on hit ratio more than on any rate card, and the cache key is what sets the hit ratio. Each header, cookie or query string you add to the key multiplies the number of distinct objects. If you key on Accept-Language, a session cookie and an unsorted tracking parameter, a route that should hold one cached object per edge can hold thousands, and most of them are requested only once.
Separate what the origin needs from what the key needs
A cache policy defines the key and the TTLs. An origin request policy forwards extra values to the origin without adding them to the key. Use the cache policy only for inputs that actually change the response body, and send everything else, such as tracing headers or a client version used for logging, through the origin request policy. Some values, notably Authorization, can only reach the origin on cached behaviors if they are part of the key. That makes the cache per-user, which is safe, but it gives a low hit ratio.
Treat key mistakes as data exposure
If a response varies by user and the key omits the user identity, CloudFront will serve one user's private data to another. Test for this explicitly in staging. Request the same URL as two different users and confirm that the bodies differ. Check the X-Cache response header to see whether the second response was a hit. Run this test in CI whenever a cache policy changes.
#!/usr/bin/env bash
# CI check: fail if CloudFront serves user A's private response to user B.
# Run against staging after any cache policy change.
set -euo pipefail
# Endpoint must return user-specific data (e.g. the caller's profile).
URL="${URL:-"
TOKEN_A="${TOKEN_A:?set TOKEN_A to a staging token for test user A}"
TOKEN_B="${TOKEN_B:?set TOKEN_B to a staging token for test user B}"
TMP=$(mktemp -d)
trap 'rm -rf "$TMP"' EXIT
# Save the body and headers separately so we can compare bodies and read X-Cache.
fetch() {
curl -sS --fail -o "$TMP/$1.body" -D "$TMP/$1.headers" \
-H "Authorization: Bearer $2" "$URL"
}
xcache() {
grep -i '^x-cache:' "$TMP/$1.headers" | tr -d '\r' | cut -d' ' -f2- || true
}
# Warm the edge cache as user A, then request the same URL as user B.
fetch a1 "$TOKEN_A"
fetch a2 "$TOKEN_A"
fetch b "$TOKEN_B"
echo "User A, 2nd request: X-Cache=$(xcache a2)"
echo "User B, 1st request: X-Cache=$(xcache b)"
# Identical bodies for different users means the cache key omits user identity.
if cmp -s "$TMP/a2.body" "$TMP/b.body"; then
echo "FAIL: user B received user A's response (X-Cache=$(xcache b))" >&2
exit 1
fi
echo "PASS: responses differ per user"
A CI script that warms the cache as one user, requests the same URL as a second user, and fails if the bodies match, printing the X-Cache header so you can see whether the second user's response was a cache hit.
When do Origin Shield, request collapsing and short TTLs reduce origin load?
…new route or cache policy ships.
Origin Shield
Without Origin Shield, each regional edge cache that misses fetches from your origin independently, so a single popular response can be requested once per region every time its TTL expires. Origin Shield adds one more caching layer, in a region you pick (ideally the one closest to your origin). All regional caches miss into it, so the origin sees roughly one fetch per object per TTL instead of one per region.
This helps most when traffic is spread across many regions and the origin is expensive per request, such as database-backed endpoints or autoscaled compute. It does not reduce what you pay for data transfer out to viewers. You also pay a separate per-request charge for requests that reach Origin Shield. On a full miss, the request makes an extra hop before reaching the origin, which adds latency. If your traffic is concentrated in one region, you may pay the shield fee without getting much additional collapsing.
Request collapsing and short TTLs
When many requests for the same cache key arrive at a CloudFront location while a fetch for that key is already in progress, CloudFront sends one request to the origin and serves the result to all of them. Collapsing only works for responses that CloudFront is allowed to cache. On a hot endpoint, a TTL of one to five seconds is therefore enough to turn a traffic spike into a small, steady trickle of origin requests. The saving is origin compute, not egress.
Compression and payload size
Gzip or Brotli on JSON responses directly reduces the bytes you are billed for. Trimming unused fields and paginating large lists reduces them further. Compress in one place only. If the origin already returns a Content-Encoding header, CloudFront serves the response as it is, so also enabling compression at the origin spends origin CPU for no extra benefit. Also normalize Accept-Encoding in the cache key rather than forwarding the raw header. Forwarding it raw splits the cache into many variants and lowers your hit ratio.
When should you avoid putting CloudFront in front of an API, and what are the alternatives?
CloudFront pays off for read-heavy APIs with a high share of identical responses, clients spread across regions, and large or frequently repeated payloads such as catalogs, configuration documents or public reference data. In those cases each cache hit avoids both origin compute and origin egress.
It does little for write-heavy APIs, because writes are never cached and still traverse the edge to the origin. Streaming, long-polling and WebSocket traffic can pass through CloudFront, but nothing is reused, so you pay for an extra hop and gain no offload. Request-heavy APIs with low hit ratios are the hardest to spot. When most responses are user-specific, per-request charges can rival what you save on transfer.
Edge functions add compute charges on every invocation, including cache hits. A function that runs on every request to rewrite headers or check tokens can erase the savings. Another layer also has operational costs:
- Cache misses add latency.
- The edge returns its own error responses, which your origin logs never record.
- CloudFront may add, strip or rewrite headers.
- Its origin timeouts may not match your origin's, so slow endpoints fail differently than they do when called directly.
| Alternative | Reduces egress | Reduces origin load | Main trade-off |
|---|---|---|---|
| Application-level caching | No | Yes | Memory and invalidation logic in your service |
| Smaller payloads (compression, trimmed fields) | Yes | Slightly | Requires API changes |
| Pagination or field selection | Yes | Yes | Clients must adopt new parameters |
| Serve clients directly from origin | No | No | Simplest setup; no extra layer to debug |
How do you measure savings and manage invalidation without wasting engineering time?
Before changing anything, record a baseline for at least a full weekly traffic cycle. Capture three numbers: requests reaching the origin, bytes the origin sends out, and the matching line items in the Cost and Usage Report. After the rollout, compare the same three. Use CloudFront's cache statistics report for a quick hit-ratio view. Use standard or real-time logs to find out why requests miss. The x-edge-result-type field separates hits, misses, and refresh hits per path, which shows which endpoints are dragging the ratio down.
The origin-side count is the one that matters. A high edge hit ratio means little if the origin load balancer's request count hasn't dropped. In the Cost and Usage Report, group by usage type. This keeps origin data transfer out, origin-to-CloudFront transfer, and CloudFront's own transfer and request charges in separate lines, so a saving in one isn't hiding an increase in another.
For invalidation, put a version in the path or cache key (/v2/catalog, or a content hash) when a response must change immediately. Each version gets its own cache entry, so you never have to purge anything. If you find yourself invalidating many times a day, your TTLs are longer than the data's real freshness requirement. Shorten them.
Let the origin set Cache-Control and s-maxage per endpoint, and configure the cache policy to honor them. This puts freshness rules in code that gets reviewed and versioned. During an incident, engineers can then read a response header and compare it against the baseline. That is faster than reverse-engineering edge settings that someone tuned by trial and error months earlier.
-- Query 1: which paths drag the hit ratio down?
-- Assumes a table named cloudfront_logs built from standard logs using the
-- Athena DDL in the AWS docs, where x-edge-result-type maps to result_type.
SELECT
uri,
COUNT(*) AS requests,
SUM(CASE WHEN result_type = 'Hit' THEN 1 ELSE 0 END) AS hits,
SUM(CASE WHEN result_type = 'RefreshHit' THEN 1 ELSE 0 END) AS refresh_hits,
SUM(CASE WHEN result_type = 'Miss' THEN 1 ELSE 0 END) AS misses,
ROUND(100.0 * SUM(CASE WHEN result_type = 'Hit' THEN 1 ELSE 0 END) / COUNT(*), 1) AS hit_pct
FROM cloudfront_logs
WHERE "date" BETWEEN DATE '2026-10-01' AND DATE '2026-10-07' -- one full weekly cycle
GROUP BY uri
ORDER BY misses DESC -- most origin load first, not lowest ratio
LIMIT 20;
-- Query 2: run once for the baseline week and once after rollout.
-- Assumes a Cost and Usage Report table named cur. Grouping by usage type keeps
-- origin egress, origin-to-CloudFront transfer, and CloudFront transfer and
-- request charges on separate lines, so a drop in one cannot hide a rise in another.
SELECT
line_item_product_code,
line_item_usage_type,
SUM(line_item_usage_amount) AS usage_amount,
ROUND(SUM(line_item_unblended_cost), 2) AS cost
FROM cur
WHERE line_item_usage_start_date >= TIMESTAMP '2026-10-01 00:00:00'
AND line_item_usage_start_date < TIMESTAMP '2026-10-08 00:00:00'
AND line_item_product_code IN ('AmazonCloudFront', 'AmazonEC2', 'AWSDataTransfer')
GROUP BY line_item_product_code, line_item_usage_type
ORDER BY cost DESC;
Two Athena queries: one ranks paths by cache misses from CloudFront standard logs, the other splits a week of Cost and Usage Report charges by usage type for the before-and-after comparison (table names and dates are placeholders).
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 egress cost, 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.