What does CloudFront in front of an API actually cost and save?

The setup is a CloudFront distribution placed in front of an existing API origin, such as an Application Load Balancer, a regional API Gateway endpoint, or EC2 instances. Clients connect to the nearest edge location. CloudFront either answers from cache or forwards the request to the origin over AWS's network. The bill changes in two ways: some origin-side charges move to CloudFront, and cache hits remove some origin charges entirely.

Cost line Without CloudFront With CloudFront (cache miss) With CloudFront (cache hit)
Data transfer out to internet Billed at origin's regional egress rate Billed by CloudFront instead; origin→CloudFront generally not billed Billed by CloudFront
Origin compute per request Paid Paid Avoided
ALB / API Gateway per-request charges Paid Paid Avoided
CloudFront request fees None Paid Paid
CloudFront→origin transfer (request bodies, uploads) None Billed None

The egress row matters most. Data transfer from AWS origins to CloudFront is generally not billed as internet egress. You pay CloudFront's transfer rate instead of the origin's, so the egress math changes even at a zero hit ratio. Whether that is cheaper depends on your regions, the price class, and your volume tier.

Savings from cache hits follow this formula:

saved ≈ hit requests × (origin compute + LB/gateway cost per request) − CloudFront request fees on all requests

Treat everything above as structure, not pricing. Confirm current terms, regional rates, price classes, free-tier allowances, and any committed or negotiated pricing on the AWS pricing pages before you model your own traffic.

+-----------+  request   +---------------------------+  $ CF request fee
|  Client   |----------->|   CloudFront edge         |    (every request)
|           |<-----------|   location (cache)        |  $ CF transfer out
+-----------+  response  +---------------------------+    (replaces origin
                           |        ^        |            egress rate)
                    MISS   |        |        |  HIT
                 forward   |        |        +--> served from cache:
                           v        |             origin charges avoided
               +--------------------+------+
               |  AWS network              |  $ CF->origin transfer
               |                           |    (request bodies) billed
               |  origin->CloudFront       |  origin->CF transfer
               |  generally not billed     |    generally not billed
               +---------------------------+
                           |        ^
                           v        |
               +---------------------------+
               |  ALB / API Gateway        |  $ per-request charge
               +---------------------------+    (misses only)
                           |        ^
                           v        |
               +---------------------------+
               |  Origin compute (EC2 ...) |  $ per-request compute
               +---------------------------+    (misses only)

Where each cost line lands with CloudFront in front of an API: hits stop at the edge, misses also incur load balancer or gateway and compute charges.

How does it work? The path of an API request through CloudFront

Every cost line above maps to a step in how CloudFront handles an API request:

  1. Edge selection. The client resolves the distribution's domain name and connects to a nearby edge location. TLS terminates at the edge, so the long round trips of the handshake stay short for the client.
  2. Behavior matching. CloudFront compares the request path against the distribution's cache behaviors in order. The first path pattern that matches wins, and the default * behavior catches anything left over. The matched behavior decides which origin to use, which methods are allowed, and which cache policy and origin request policy apply.
  3. Cache key construction. The cache policy builds a key from the host, the path, and whatever headers, cookies and query strings it lists. Two requests share a stored response only if their keys are identical.
  4. Lookup. If a fresh object exists for that key, the edge returns it. No origin, load balancer or compute charge occurs, but the CloudFront request fee and transfer out still apply.
  5. Miss or revalidation. If no object exists, CloudFront forwards the request to the origin. It can go through a regional edge cache or Origin Shield if those layers apply. Requests using methods such as POST, PUT and DELETE are proxied to the origin and are not cached. If a stale object exists and the origin supplied an ETag or Last-Modified, CloudFront sends a conditional request, and a 304 refreshes the entry without transferring the body again.
  6. Storage. CloudFront stores the origin's response under the cache key for a lifetime set by the origin's Cache-Control headers. The cache policy's minimum, default and maximum TTLs bound that lifetime. Responses marked no-store or private are not stored when the minimum TTL is zero.

Connections from edge locations to the origin are reused across requests. This is why misses can still be somewhat faster than direct requests. It does not reduce origin per-request charges. Only steps 3 and 4 do that, which is why the rest of this article concentrates on cache keys and TTLs.

How does hit ratio change the cost model? A worked example

Illustrative estimate (assumed numbers, not a benchmark). Assume 100 million requests per month, a 20 KB average response (about 2,000 GB out), $2.00 per million requests of origin compute, $0.80 per million requests in load balancer charges, $0.09/GB direct origin egress, $0.085/GB CloudFront data transfer out, $1.00 per million CloudFront requests, and no charge for origin-to-CloudFront transfer. These rates are placeholders. They are not current AWS prices.

  • Direct cost: compute + LB + origin egress = $200 + $80 + $180 = $460
  • CloudFront cost at hit ratio h: CF requests + CF egress + (compute + LB) × (1 − h) = $100 + $170 + $280 × (1 − h)
Hit ratio Origin offload (requests) Origin compute + LB Total with CloudFront vs. direct ($460)
0% 0 $280 $550 +$90
30% 30M $196 $466 +$6
~32% 32M $190 $460 break-even
50% 50M $140 $410 −$50
80% 80M $56 $326 −$134
95% 95M $14 $284 −$176

CloudFront charges the request fee on every request, including the ones it serves from cache. That fee is the fixed cost the hit ratio has to pay off. When the hit ratio is near zero, the API still pays its full origin bill plus CloudFront's fees. This is typical of per-user responses and write-heavy traffic. The only offsets are the gap between the two egress rates and the latency gained from reusing warm connections to the origin. Those offsets rarely cover the request fees.

The break-even hit ratio depends on your actual per-request origin cost, so it moves with your workload. Rebuild the model with your current rates and measured response sizes before you treat CloudFront as a cost saving.

Who should use CloudFront caching for an API?

Edge caching for APIs suits teams who meet most of these conditions:

  • They run read-heavy APIs on AWS where many callers request the same responses. Examples include public catalogs, configuration or feature data, pricing, search results, and reference datasets.
  • They pay meaningful origin costs per request. The savings scale with the compute and load balancer or gateway cost of each avoided request. An origin that is cheap per request has little to offload.
  • They control the origin code. Correct caching depends on the origin sending accurate Cache-Control, ETag and Last-Modified headers. It also depends on knowing exactly which inputs change each response, and that knowledge lives with the team that owns the code.
  • They can own the edge configuration. Someone has to maintain cache behaviors and policies, check cache keys on authenticated paths, and debug problems that may come from the edge or the origin.
  • They serve clients spread across regions. Users far from the origin region gain the most latency benefit from edge termination and cache hits.

Teams whose APIs serve mostly per-user data, or that have no one to review cache key changes for data-exposure risk, are poor candidates. The worked example above shows how a low hit ratio turns CloudFront into a net cost.

When should you put CloudFront in front of an API?

Use it when the numbers and the data model support it:

  • A large share of GET traffic is shareable. Inventory your endpoints by cacheability class, as described below, and estimate the share of requests that fall into the public and large-tenant classes. If that share cannot plausibly clear your break-even hit ratio, the cost case fails.
  • Seconds of staleness are acceptable. Even a 5-second shared TTL can collapse repeated requests for a hot key into a small number of origin fetches.
  • Traffic spikes concentrate on the same objects. Launches, price updates and popular search terms benefit from cache hits and request collapsing.
  • Egress is a significant part of the bill. The difference between origin egress and CloudFront transfer rates applies to every byte, cached or not. Compare the rates for your regions and volume tier.
  • You already want CloudFront for other reasons, such as edge TLS termination or attaching WAF rules at the distribution. The request fees are then partly a cost you would pay anyway, and caching shareable endpoints adds offload on top.

When should you avoid it?

Skip edge caching, or limit it to a few endpoints, when:

  • Most traffic is per-user or writes. These requests reach the origin regardless. CloudFront adds a request fee to each one with little offload in return.
  • Responses must be fresh to the second. The required staleness bound caps the TTL. A very short TTL on low-traffic keys yields almost no hits.
  • Responses vary on many inputs. If correct output depends on several headers, cookies or query parameters, the cache key fragments into many entries and the hit ratio falls.
  • Request volume is low. The per-request fee and the engineering overhead of behaviors and policies may exceed what the hit ratio saves. Run the cost model with your own volumes first.
  • Clients are inside AWS or private networks. Internal service-to-service APIs reached over VPC networking gain little from edge locations. An origin-side cache is usually a better fit.
  • You cannot audit cache keys on authenticated paths. If no one can confirm that identity-dependent responses are keyed correctly or not cached at all, the risk of serving one user's data to another outweighs the savings.

Which API endpoints should you cache? Classifying by cacheability

Start with an endpoint inventory instead of a global cache setting. Hit ratio comes from how many requests share an identical response, and that varies widely across a typical API.

Class Example paths Shared by Cache key adds Edge caching fit
Public reference data /v1/catalog/*, /v1/config/* All callers Selected query strings Strong
Per-tenant shareable reads /v1/tenants/*/plans Users in one tenant Tenant identifier Good if tenants are large
Per-user reads /v1/me/* One user User identity Poor
Writes POST/PUT/DELETE anywhere Nobody n/a None

Give each class its own cache behavior with a path pattern. Each behavior then gets a cache policy that matches how its responses are shared. Per-tenant reads only pay off when many users in a tenant request the same object within the TTL. Small tenants spread requests across many cache keys and gain little. Per-user responses produce one cache entry per user, so most requests miss and still reach the origin.

Send everything else to a behavior with caching disabled, including the default * behavior. CloudFront does not cache responses to write methods, but per-user GETs on a caching behavior still create entries that are rarely reused. They take up cache space and lower the reported hit ratio, which makes the reference-data savings harder to see. With separate behaviors, you can also read cache statistics for each class.

This approach fits read-heavy APIs where a few response shapes serve many callers. Skip it if most traffic is per-user or writes. Those requests go to the origin either way, so CloudFront adds request charges with little origin offload in return.

DistributionConfig:
  CacheBehaviors:
    # Public reference data: shared by all callers, keyed on selected query strings.
    - PathPattern: /v1/catalog/*
      TargetOriginId: api-origin
      ViewerProtocolPolicy: https-only
      AllowedMethods: [GET, HEAD, OPTIONS]
      CachePolicyId: !Ref ReferenceDataCachePolicy   # custom policy, query string allowlist
    - PathPattern: /v1/config/*
      TargetOriginId: api-origin
      ViewerProtocolPolicy: https-only
      AllowedMethods: [GET, HEAD, OPTIONS]
      CachePolicyId: !Ref ReferenceDataCachePolicy
    # Per-tenant reads: tenant ID is already in the path, so it is part of the cache key.
    - PathPattern: /v1/tenants/*/plans
      TargetOriginId: api-origin
      ViewerProtocolPolicy: https-only
      AllowedMethods: [GET, HEAD, OPTIONS]
      CachePolicyId: !Ref TenantReadsCachePolicy     # shorter TTL, no user-level key
    # Per-user reads: explicit no-cache behavior so they never create edge entries.
    - PathPattern: /v1/me/*
      TargetOriginId: api-origin
      ViewerProtocolPolicy: https-only
      AllowedMethods: [GET, HEAD, OPTIONS, PUT, PATCH, POST, DELETE]
      CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad          # managed CachingDisabled
      OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac  # managed AllViewerExceptHostHeader
  # Everything else, including writes: caching disabled, viewer headers forwarded to origin.
  DefaultCacheBehavior:
    TargetOriginId: api-origin
    ViewerProtocolPolicy: https-only
    AllowedMethods: [GET, HEAD, OPTIONS, PUT, PATCH, POST, DELETE]
    CachePolicyId: 4135ea2d-6df8-44a3-9df3-4b5a84be39ad
    OriginRequestPolicyId: b689b0a8-53d0-40ab-baf2-68738e2966ac

A CloudFormation distribution fragment that maps reference-data and per-tenant paths to dedicated cache policies, while per-user paths and the default behavior use the managed CachingDisabled policy so writes and per-user reads always go to the origin.

How do cache keys, cache policies and origin request policies work?

The cache key decides whether two requests share one stored response, so it is the main lever on hit ratio. CloudFront splits this across two objects attached to each cache behavior, which matches a path pattern such as /v1/catalog/*.

A cache policy sets the TTL bounds and lists the headers, cookies and query strings that go into the key. Anything in the key is also forwarded to the origin. An origin request policy forwards extra values to the origin without adding them to the key. Use it for data the origin needs for logging or routing that does not change the response body, such as a request ID or a CloudFront-Viewer-Country header used only for analytics.

Every value you add to the key multiplies the number of cache entries:

  • Language headers: keying on Accept-Language can split one product listing into dozens of variants.
  • Session cookies: keying on a session cookie gives every user a private copy, and the hit ratio falls toward zero.
  • Forwarding all headers or cookies: this is the most common mistake. In practice it makes the behavior uncacheable while you still pay CloudFront request charges.

For query strings, use an allowlist. If /search responses vary only on q, page and sort, include only those three. Tracking parameters like utm_source or a cache-busting timestamp then hit the same entry.

The tension is that leaving out a parameter that does change the response serves wrong data to some callers. Start from the origin's code: list every input that changes the output, put those in the cache policy, and send everything else through the origin request policy or drop it.

Resources:
  SearchCachePolicy:
    Type: AWS::CloudFront::CachePolicy
    Properties:
      CachePolicyConfig:
        Name: api-search-cache
        MinTTL: 0
        DefaultTTL: 60
        MaxTTL: 300
        ParametersInCacheKeyAndForwardedToOrigin:
          EnableAcceptEncodingGzip: true
          EnableAcceptEncodingBrotli: true
          # No headers or cookies in the key. Each one would multiply cache entries.
          HeadersConfig:
            HeaderBehavior: none
          CookiesConfig:
            CookieBehavior: none
          # Allowlist only the parameters that change the response.
          # utm_source, cache-busting timestamps and similar values are ignored.
          QueryStringsConfig:
            QueryStringBehavior: whitelist
            QueryStrings: [q, page, sort]

  SearchOriginRequestPolicy:
    Type: AWS::CloudFront::OriginRequestPolicy
    Properties:
      OriginRequestPolicyConfig:
        Name: api-search-origin
        # These go to the origin for logging and analytics but stay out of the key.
        HeadersConfig:
          HeaderBehavior: whitelist
          Headers: [CloudFront-Viewer-Country, X-Request-Id]
        CookiesConfig:
          CookieBehavior: none
        # Values already in the cache key are forwarded automatically.
        QueryStringsConfig:
          QueryStringBehavior: none

A CloudFormation cache policy keys /search responses only on q, page and sort, and a separate origin request policy forwards a viewer-country header and a request ID to the origin without adding them to the cache key.

How should you set TTLs and Cache-Control headers for API responses?

Set freshness at the origin, where the code knows how stale each response can be, and use CloudFront's TTL settings as guardrails. A cache policy defines minimum, default and maximum TTLs. When the origin sends max-age or s-maxage, CloudFront uses that value, clamped between the minimum and maximum. s-maxage applies only to shared caches, so you can give CloudFront 30 seconds while browsers get max-age=0. The default TTL applies only when the origin sends no freshness header.

Origin Cache-Control CloudFront behavior (minimum TTL = 0)
s-maxage=30, max-age=0 Caches 30s at the edge, clamped to min/max
max-age=60 Caches 60s at the edge and in browsers
No header Uses the default TTL
no-store / private Does not cache

A minimum TTL above zero overrides no-store and private. Keep it at zero unless every response on that behavior is public.

Short TTLs still work on hot endpoints. Illustrative estimate: a key requested 200 times per second with a 5-second TTL reaches the origin roughly once per 5 seconds per edge cache location, not 1,000 times. When an entry expires, CloudFront revalidates with If-None-Match or If-Modified-Since. If the origin returns ETag or Last-Modified and answers 304, it still runs the check but sends no body.

Prefer short TTLs or versioned paths over invalidations. Invalidations beyond the monthly free allowance are billed per path, and they take time to reach all locations. Your staleness requirements set the limit on savings. An endpoint that must be fresh to the second will offload little.

const express = require("express");
const crypto = require("crypto");

const app = express();
app.set("etag", false); // we set ETag explicitly below

// Hot, shared endpoint: CloudFront may serve it for 5s. Browsers revalidate every time.
app.get("/api/prices/:sku", async (req, res) => {
  const body = JSON.stringify(await loadPrice(req.params.sku));
  const etag = `"${crypto.createHash("sha256").update(body).digest("hex")}"`;

  res.set("Cache-Control", "public, s-maxage=5, max-age=0");
  res.set("ETag", etag);

  // Revalidation from the edge: the lookup still runs, but no body is sent.
  // Exact match only. A full implementation would parse a list of ETags.
  if (req.get("If-None-Match") === etag) return res.status(304).end();
  res.type("application/json").send(body);
});

// Per-user data: must never be cached at the edge.
// Keep the cache policy's minimum TTL at 0, or CloudFront ignores this header.
app.get("/api/me", (req, res) => {
  res.set("Cache-Control", "private, no-store");
  res.json({ user: "example-user" });
});

// Versioned path: content at a given version never changes, so cache it
// for a long time and publish a new version instead of invalidating.
app.get("/api/catalog/:version", (req, res) => {
  res.set("Cache-Control", "public, s-maxage=86400, max-age=3600, immutable");
  res.json({ version: req.params.version, items: [] });
});

async function loadPrice(sku) {
  return { sku, price: 1999, currency: "USD" }; // placeholder data source
}

app.listen(8080);

An Express origin that sets the cache lifetime for each endpoint: a short shared-cache TTL with ETag-based 304 responses on a hot endpoint, no-store on per-user data, and long TTLs on versioned paths so they never need invalidation.

Is it safe to cache authenticated API responses?

Yes, but treat every caching mistake on an authenticated endpoint as a data-exposure incident, not a performance bug. CloudFront returns whatever object matches the cache key. If a response depends on who is asking, and the identity isn't part of the key, the first user's response is stored and served to every later caller whose request maps to the same key.

The typical failure looks like this. /v1/account reads the caller's identity from the Authorization header. The cache policy keys only on path and query string, and an origin request policy forwards the header so the origin can authenticate. User A's request populates the cache. User B gets A's account until the TTL expires. Nothing errors and the hit ratio looks healthy.

If a response varies by user or tenant, the value it varies on must be in the cache key. That could be the Authorization header, a tenant header, or a cookie. Keying on a per-user token produces roughly one object per user, though, so the hit ratio tends toward zero while the leak risk remains. Per-user responses usually belong in a behavior that uses a caching-disabled policy. Tenant-level data shared by many users is a better candidate, keyed on the tenant identifier.

Origin protection is part of this work. If the origin is publicly reachable, clients can skip CloudFront entirely. That bypasses the egress savings, the edge controls, and any WAF rules attached to the distribution. Restrict the origin to CloudFront-only access:

  • S3 and Lambda function URLs: use origin access control.
  • Load balancers: use security groups that allow only CloudFront's origin-facing IP ranges, and add a secret custom header that the origin validates.

How do you measure savings, and what are the alternatives to edge caching?

Measuring hit ratio and origin offload

Measure each cache behavior separately. A site-wide hit ratio can look healthy because static assets inflate it while API paths still miss on most requests. CloudFront's cache statistics report hit ratio by distribution. For per-path detail, use standard logs and group by cs-uri-stem and x-edge-result-type. Hit and RefreshHit were served without a full origin fetch. Miss went to the origin.

Check the result against the origin's own request count. If origin traffic did not fall, the hit ratio is not saving money. Use the hit ratio as an input to the cost model:

origin requests avoided = total requests × hit ratio

Features that cut origin load without caching more

  • Request collapsing: when several requests for the same uncached object arrive together, CloudFront sends one to the origin. This helps during traffic spikes.
  • Origin Shield: adds a per-request charge and an extra network hop. It is only worth it if it raises the hit ratio enough to offset both.
  • Compression: reduces the bytes CloudFront delivers to clients. Origin load stays the same unless the origin also compresses its responses.

Alternatives to edge caching

Option Cuts compute Cuts egress Added complexity
CloudFront Yes Yes Behaviors, policies, edge debugging
Origin cache (e.g., in-memory store) Yes No Invalidation logic in app
API Gateway caching Yes No Hourly cache charge
No CDN No No None

Engineering cost

Each new behavior adds work. Debugging means working out whether a problem came from the edge or the origin, and every config change takes minutes to propagate. To keep this manageable, define one cache policy per cacheability class rather than one per endpoint. Then assign each new route to an existing class.

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 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.
  • Changing a shared variable is one edit and one review instead of editing every service's .env by hand.

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.
  • A wrong or stale value is caught at review time by the services it affects, not by a failed deploy.
  • 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.