Which part of your AWS data transfer bill can CloudFront actually reduce?

Open Cost Explorer, filter Service to EC2-Other, EC2, S3 and Elastic Load Balancing, and group by Usage Type. Data transfer appears as usage types with a region prefix, and the suffix tells you which kind it is. For finer detail, query the Cost and Usage Report by line_item_usage_type and line_item_resource_id. That shows which buckets, load balancers or instances generate the bytes, which is what you need to decide what to put behind a distribution.

Charge Typical usage type pattern Can CloudFront reduce it?
Internet Data Transfer Out *-DataTransfer-Out-Bytes Yes. This is the target.
Inter-AZ (same region) *-DataTransfer-Regional-Bytes No. This traffic stays inside your VPC topology.
Inter-region <src>-<dst>-AWS-Out-Bytes No, unless the traffic is really user-facing and routed oddly.
NAT gateway processing *-NatGateway-Bytes No. This charge comes from outbound calls made by private subnets.

CloudFront only sits between your origins and clients on the internet. It does nothing for traffic between your own services, replication between regions, or workloads pulling packages and calling third-party APIs through a NAT gateway. The first row is your addressable spend. The other rows need architectural fixes such as AZ-aware routing, VPC endpoints, or fewer cross-region calls.

If internet egress is a small share of the total, stop here. Configuring a CDN will not change the bill much. This work pays off for teams whose data transfer line is dominated by bytes served to browsers, mobile apps and API clients.

Who should use CloudFront to cut egress costs?

CloudFront is worth the setup effort if your Cost and Usage Report shows internet data transfer out as a large share of your data transfer spend, and that traffic comes from a few identifiable origins. These workloads usually fit:

  • Frontend and web teams serving single-page apps, JS and CSS bundles, fonts and images from S3 or from an application server. The objects are mostly shared between users and can be cached for a long time.
  • Teams distributing large files such as installers, firmware, media, datasets or downloadable reports. Large objects get the most benefit from the per-GB rate difference, and repeated downloads of the same file are served from cache.
  • API owners with read-heavy public endpoints such as catalogs, configuration, feature flags or public metadata. Many clients request the same responses within a short window.
  • Platform and infrastructure teams that own the shared edge layer, meaning TLS termination, domains and request filtering, and want one place to manage caching and egress for many services.
  • Services with a geographically spread audience, where serving from edges near users improves latency and lowers cost at the same time.

It is a weaker fit for teams whose traffic is mostly internal (service-to-service, inter-AZ, cross-region replication), for APIs dominated by small personalized responses, and for workloads where nearly every response is unique. The cost and break-even sections below show how to check this with your own numbers.

How does CloudFront work?

CloudFront is a reverse proxy and cache that runs in AWS edge locations. You create a distribution, which has one or more origins (an S3 bucket, an Application Load Balancer, an EC2 instance or any HTTP server) and one or more cache behaviors. Each behavior matches a path pattern such as /static/* or /api/* and sets which origin to use, which cache policy and origin request policy apply, which HTTP methods are allowed and whether compression is enabled.

A request goes through these steps:

  1. Routing to an edge. The client resolves your distribution's domain name, or your custom domain aliased to it, and DNS sends it to a nearby edge location. TLS terminates at the edge.
  2. Behavior matching. CloudFront picks the first cache behavior whose path pattern matches the request URL. If none match, it uses the default behavior.
  3. Cache key lookup. CloudFront builds a cache key from the host and path, plus whatever headers, cookies and query strings the cache policy includes. If a fresh object exists under that key, the edge returns it. That is a cache hit.
  4. Miss handling. On a miss, the edge checks a regional edge cache, a larger mid-tier cache shared by several edges. If Origin Shield is enabled, the request then goes to the single Shield location you picked for that origin. The request reaches the origin only if every layer misses.
  5. Origin fetch and storage. The origin responds. CloudFront decides how long to keep the object based on the origin's Cache-Control or Expires headers, limited by the minimum, default and maximum TTLs in the cache policy. It then stores the object at each layer the request passed through and returns it to the client.

Requests that can't be cached, such as authenticated API calls behind a caching-disabled policy, follow the same path but always go to the origin. They still pass through CloudFront's network, which matters for the billing model described next.

How does CloudFront reduce AWS egress costs?

CloudFront lowers the bill through two independent mechanisms.

Origin fetches are not billed as data transfer out. When the origin is an AWS service such as S3, EC2 or an Application Load Balancer, bytes moving from that origin to CloudFront are not charged at the internet egress rate. This applies to every request, including uncacheable API calls with a TTL of zero. The bytes still cross the network, but they show up on the CloudFront line instead of the EC2 or S3 data transfer line.

Cache hits never reach the origin. A hit is served from the edge, so the origin sends fewer bytes and handles fewer requests. That reduces compute, load balancer capacity and S3 GET charges, and these savings are separate from the transfer rate.

CloudFront does not make delivery free. It bills its own transfer to viewers plus a per-request fee:

Viewer ⇐ billed: CloudFront transfer out + per-request fee ⇐ Edge location ⇐ billed: Origin Shield request fee only, if enabled ⇐ Origin Shield (optional) ⇐ not billed as DTO from AWS origins ⇐ Origin (S3 / EC2 / ALB)

Uploads such as POST and PUT bodies that CloudFront forwards to the origin are billed separately.

The transfer saving depends on the rate difference and the volume sent. The origin saving depends on the hit ratio.

Illustrative estimate (assumed numbers, not a benchmark):

Net transfer saving = GB × (DTO rate − CloudFront rate) − (requests ÷ 10,000) × request fee

Assumed inputs:

  • 10,000 GB per month
  • Direct egress rate of $0.09/GB
  • CloudFront rate of $0.06/GB
  • 50 million requests at $0.01 per 10,000

Result: 10,000 × $0.03 − 5,000 × $0.01 = $300 − $50 = $250/month, before counting any origin savings from cache hits.

+--------------------------+
|          Viewer          |
+--------------------------+
             ^
             |  BILLED: CloudFront data transfer out to viewer
             |          + CloudFront per-request fee
             |
+--------------------------+
|   CloudFront edge cache  |---> cache HIT: served from edge,
+--------------------------+     origin not contacted
             ^
             |  cache MISS or uncacheable (TTL 0) only
             |  BILLED: Origin Shield request fee, if enabled
             |
+--------------------------+
|  Origin Shield (optional)|---> shield HIT: origin not contacted
+--------------------------+
             ^
             |  shield MISS (or edge MISS when Shield is off)
             |  NOT BILLED as data transfer out from AWS origins
             |
+--------------------------+
|  Origin: S3 / EC2 / ALB  |
+--------------------------+

  ^ = response bytes flowing toward the viewer
  Uploads (POST/PUT bodies) forwarded to the origin are billed separately.

Response path from an AWS origin through the optional Origin Shield and the CloudFront edge to the viewer: CloudFront transfer and request fees apply at the viewer hop, origin-to-CloudFront bytes are not billed as data transfer out, and cache hits stop the request before it reaches the origin.

When does moving traffic behind CloudFront save money, and when does it cost more?

The previous result holds only when objects are large enough for the per-GB discount to outweigh the request fees. To find where that stops, express both costs per request.

Illustrative estimate (assumed numbers, not a benchmark). These are the same placeholder rates as above. Replace them with current pricing-page values for your regions:

  • E_direct = $0.09/GB
  • E_cf = $0.06/GB
  • R = $0.01 per 10,000 requests
  • 50 million requests/month

The formulas:

  • Direct cost = GB × E_direct
  • CloudFront cost = GB × E_cf + (requests ÷ 10,000) × R
  • Break-even object size = (R ÷ 10,000) ÷ (E_direct − E_cf)

With these inputs, break-even is $0.000001 ÷ $0.03 ≈ 33 KB per response.

Avg object size Monthly GB Direct CloudFront Origin requests at 90% hit ratio
2 KB (JSON) 100 $9 $56 5M
30 KB 1,500 $135 $140 5M
500 KB (images) 25,000 $2,250 $1,550 5M

Small JSON responses are dominated by request fees. At 2 KB, the per-GB saving is negligible, so CloudFront costs about six times more on transfer alone.

The cache hit ratio does not change the CloudFront bill in this model, because every request is billed at the edge whether it hits or misses. The hit ratio affects the origin side instead: fewer load balancer requests, less compute, and lower database load. For small API payloads, those origin savings are often the only real justification. Price them explicitly rather than assuming they exist.

Rates vary by region, volume tier, and negotiated contract. Rebuild this model from current rates and your account's actual request and byte counts before deciding.

How do you configure CloudFront caching for static assets?

Start with filenames that change whenever content changes. Have your build tool emit names like app.3f9a1c.js and logo.8b21e0.svg, then serve them with Cache-Control: public, max-age=31536000, immutable. The one-year max-age lets edges and browsers keep the object as long as it is useful. immutable tells browsers not to revalidate it on reload. Because a new deploy produces new URLs, stale content can't be served, and you rarely need to run an invalidation.

This matters for both cost and deploy time. CloudFront charges per invalidation path beyond a free monthly allotment. Wildcard-heavy invalidations on every release also slow deploys and push cache-miss traffic back to the origin. Versioned URLs avoid both problems.

The HTML entry point can't be hashed, because users reach it by a fixed URL. Give it a short lifetime, or use Cache-Control: no-cache so clients revalidate on each request. That way new asset references reach users quickly.

For text assets (JS, CSS, JSON, SVG), enable automatic compression on the cache behavior. Then allow gzip and Brotli in the cache policy so the Accept-Encoding variants are cached separately. Compressed responses reduce the bytes you pay for per request and load faster for users.

Keep the S3 bucket private and attach an origin access control (OAC) to the distribution. Clients can then reach your objects only through CloudFront, so nobody can bypass the cache and the caching savings hold. A minimal bucket policy grants s3:GetObject on the bucket's objects to the cloudfront.amazonaws.com service principal. It adds a condition that AWS:SourceArn must equal your distribution's ARN. With that condition, other distributions can't use your bucket as their origin.

#!/usr/bin/env bash
set -euo pipefail

BUCKET="example-assets-bucket"
ACCOUNT_ID="111122223333"
DIST_ID="EDFDVBD6EXAMPLE"

aws s3 sync ./dist "s3://${BUCKET}/" \
  --exclude "index.html" \
  --cache-control "public, max-age=31536000, immutable"

aws s3 cp ./dist/index.html "s3://${BUCKET}/index.html" \
  --cache-control "no-cache"

cat > bucket-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AllowCloudFrontOACReadOnly",
      "Effect": "Allow",
      "Principal": { "Service": "cloudfront.amazonaws.com" },
      "Action": "s3:GetObject",
      "Resource": "arn:aws:s3:::${BUCKET}/*",
      "Condition": {
        "StringEquals": {
          "AWS:SourceArn": "arn:aws:cloudfront::${ACCOUNT_ID}:distribution/${DIST_ID}"
        }
      }
    }
  ]
}
EOF

aws s3api put-bucket-policy --bucket "${BUCKET}" --policy file://bucket-policy.json

A deploy script that uploads content-hashed assets with a one-year immutable Cache-Control header, serves index.html with no-cache, and applies a minimal bucket policy so only your CloudFront distribution can read the bucket through OAC.

How should you cache API responses without leaking user data?

API traffic needs a different model from assets. Treat each endpoint as either shared or personal, and design the cache key around that decision.

Endpoint type Origin response header Cache key contents
Public, read-heavy GET (catalog, config) Cache-Control: public, s-maxage=30, max-age=0 Path plus the query strings that change output
Authenticated or personalized Cache-Control: private, no-store Irrelevant; use a caching-disabled policy

Personalized endpoints still save money behind CloudFront, even when nothing is cached. Data transfer from AWS origins to CloudFront is not billed, so you pay CloudFront's egress rates instead of the origin's internet egress rates.

Build the key from a cache policy that includes only the values that change the response. Use a separate origin request policy to forward everything else the origin needs, such as User-Agent or a correlation ID. Values in an origin request policy reach the origin without splitting the cache. Drop tracking parameters like utm_* from both policies, or every campaign link becomes a cache miss.

Leaks happen when the response depends on something the key omits. Common examples are a tenant ID header, a session cookie or the Authorization header. CloudFront only forwards Authorization on cacheable requests if the cache policy includes it, so excluding it can break auth or serve one user's data to another.

Also check error caching. CloudFront caches 5xx responses for a short default period, so lower the error caching minimum TTL on fragile APIs.

To test the key, send the same request twice with different tokens or tenant IDs. Then inspect X-Cache (Hit from cloudfront versus Miss from cloudfront) and Age. A hit on the second identity means the key is missing a value the response depends on.

#!/usr/bin/env bash
set -euo pipefail

DIST=""   # placeholder distribution
URL="$DIST/api/v1/account/summary"
TOKEN_A="example-token-user-a"                   # placeholder, not a real secret
TOKEN_B="example-token-user-b"

probe() {
  curl -s -o /dev/null -D - "$@" | grep -iE '^(x-cache|age|cache-control):' || true
}

echo "== User A, first request (expect Miss) =="
probe -H "Authorization: Bearer $TOKEN_A" "$URL"

echo "== User A, repeat (Hit only if the endpoint is meant to be cacheable) =="
probe -H "Authorization: Bearer $TOKEN_A" "$URL"

echo "== User B, same URL (a Hit here means one user's data can reach another) =="
probe -H "Authorization: Bearer $TOKEN_B" "$URL"

probe -H "X-Tenant-Id: tenant-alpha" "$DIST/api/v1/catalog?page=1"
echo "== Different tenant (expect Miss if tenant changes the response) =="
probe -H "X-Tenant-Id: tenant-beta" "$DIST/api/v1/catalog?page=1"

probe "$DIST/api/v1/catalog?page=1"
echo "== Same path with utm_source (expect Hit if utm_* is excluded from the key) =="
probe "$DIST/api/v1/catalog?page=1&utm_source=newsletter"

A curl-based script that sends the same request with different tokens, tenant IDs, and tracking parameters, then prints X-Cache, Age, and Cache-Control so you can see whether the cache key separates identities and ignores utm_ noise.*

What CloudFront pricing levers and extra features affect total cost?

Once the cache key is correct, the remaining cost levers sit in distribution settings and add-on features.

Price classes limit which edge locations serve your traffic. A cheaper class excludes higher-cost regions, so users there are routed to a more distant edge. That adds latency for them but does not block them. Check where your users actually are before you choose one.

Volume tiers and negotiated pricing change your per-GB rate as usage grows. Confirm the current tiers and any committed-use terms on the pricing page or with your account team. Do not carry figures over from an older estimate.

Origin Shield adds one more caching layer between the regional edge caches and your origin. It merges requests for the same object from many edges into a single origin fetch. This raises the effective hit ratio when traffic is spread across many regions or arrives in bursts. Shield requests are billed separately, so enable it only when origin fetches are measurably expensive, for example from compute-heavy APIs, cross-region origins or bursty cache misses.

Feature What adds cost When it pays off
Standard logs Storage and query of log files Almost always; cheap visibility
Real-time logs Per-record charges plus the stream consumer Live incident analysis only
CloudFront Functions Per invocation Lightweight header and URL rewrites
Lambda@Edge Invocations plus duration Logic that needs network or body access
WAF Per rule and per request Public APIs facing abuse

The operational surface also grows:

  • Header rewriting and CORS: forwarded headers have to match the cache policy, or you get cache misses or wrong responses.
  • TLS: certificates for custom domains have to be provisioned and renewed in the region CloudFront requires.
  • Origin timeouts: must fit your slowest API calls.
  • WebSockets and long-lived streaming: these pass through without caching, so they add per-request and transfer charges but no offload.

How can CloudFront save engineering time?

The billing change is the visible benefit, but a well-configured distribution also removes recurring work from the teams that own the origins.

Less origin capacity work. Cache hits never reach your load balancers, instances or buckets, so traffic spikes on cacheable content, such as a release, a marketing push or a popular download, mostly land on the edge. The origin's request rate depends more on cache misses than on total demand. That means less time spent sizing autoscaling, pre-warming capacity or handling incidents caused by read-heavy load.

Simpler deploys. With content-hashed asset names and a no-cache entry point, a release is an upload followed by an HTML update. You don't need an invalidation step in the pipeline, you don't have to wait for invalidations to finish, and you avoid the "users still see the old bundle" support tickets that come from long-lived caches on fixed URLs.

One place for edge concerns. TLS termination, custom domains, HTTP-to-HTTPS redirects, compression, CORS headers and request filtering can all be configured once in the distribution. Each service then doesn't need its own implementation. CloudFront Functions handle small header and URL rewrites without changing or redeploying application code.

Reusable policies. Cache policies and origin request policies are separate resources that many behaviors and distributions can share. Once you have a reviewed policy for "hashed static assets" and one for "public API, 30-second shared cache", new services can attach them instead of designing cache keys from scratch. That also reduces the risk of the cache-key leaks described above.

Faster debugging of delivery issues. The X-Cache and Age response headers, standard logs and cache statistics reports show whether a request was a hit or a miss and what status the client received. This is often quicker than tracing the same question through origin logs on many instances.

These gains come with an upfront cost. Someone has to design cache keys per endpoint, test for identity leaks and keep distribution configuration in version control alongside the services it fronts. The time is recovered when the same small set of policies and patterns is reused across many services. It is not recovered if every distribution is configured by hand with one-off settings.

When should you avoid CloudFront, and what are the alternatives?

CloudFront only reduces cost when it serves bytes from cache that would otherwise leave AWS directly. Without that, it becomes an extra hop that bills you per request.

The clearest bad fit is low-hit-ratio, small-response traffic, such as personalized JSON of a few hundred bytes per call. The per-request fee stays the same no matter how small the response is, while the byte savings shrink with payload size. At high request volume, request charges can exceed what you saved on transfer.

Cache key fragmentation causes the same problem. If you forward every header, cookie, or query string, nearly every request becomes a unique cache entry. Each one misses and goes to the origin, so you pay CloudFront request fees on top of your origin load. In practice CloudFront is then working as a paid proxy rather than a cache.

CloudFront also has no effect on transfer that never reaches the internet:

Bill line item Does CloudFront help? Better lever
Inter-AZ transfer No Same-AZ placement, AZ-aware routing
NAT gateway processing No VPC endpoints for AWS services
Cross-region replication No Fewer regions, compress before transfer
Service-to-service calls No Payload trimming, batching
Large internet responses Often Origin compression, client-side caching

At the origin, compressing responses and removing unused fields shrinks every byte you send, whether it goes through a CDN or not. Client-side caching with Cache-Control and ETag stops requests before they reach any network hop.

After rollout, track three things for each cache behavior: hit ratio, bytes served from cache versus from the origin, and status codes. CloudFront cache statistics reports or standard logs provide all three. Then compare those numbers against the actual billing line items over a full billing cycle before you claim any savings.

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 reduce aws egress 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.