Back to blog

CloudFront vs. Fastly for APIs: How to Test Cache Control and Origin Paths

CdnChart EngineeringPublished on 2026-12-0318 min read3,200
CloudFront vs. Fastly for APIs: How to Test Cache Control and Origin Paths

Putting APIs behind a CDN often leads to two mistaken conclusions: a public endpoint is fast on a cache hit, so authenticated endpoints must benefit just as much; or an edge response reports MISS, so every request must have reached the application origin. Either assumption can steer procurement in the wrong direction.

If your APIs run primarily on AWS and your team wants to retain its existing infrastructure and operational practices, CloudFront deserves an early evaluation. If your business depends on frequently updated shared responses and developers need fine-grained control over caching, invalidation, and request handling, Fastly CDN deserves focused testing. This is not a performance ranking. For entirely uncacheable APIs, compare the full path from target users to the edge, from the edge to the origin, and through application processing, with particular attention to failure rates and tail latency.

This article compares HTTP delivery and cache control in Amazon CloudFront distribution services and Fastly CDN. Fastly Compute is a separate product path that requires programming and deployment. Neither vendor's security products, edge computing services, or other additional capabilities should be treated as configurations already enabled in the base CDN service. The available documentation does not provide measurements under identical conditions or complete account policies. What follows is therefore a set of selection hypotheses, configuration principles, and validation methods—not an unmeasured declaration of a winner.

Classify Your APIs First: There Is No Single Answer to “Which Is Better?”

APIs do not all have the same caching characteristics. Product catalogs, search suggestions, account balances, and order submissions may all return JSON, but their correctness requirements are very different.

API category

Main constraints

What the CDN should address

What to verify before choosing

Public read-only endpoints

Responses can be shared across users; brief staleness is acceptable

Reduce origin requests, absorb bursts, and lower response times

Cache keys, TTL, and update propagation

Read-only endpoints that vary by language or tenant

Sharing is limited to specific groups

Reuse responses while maintaining correct isolation

Whether all variants are properly represented in cache isolation

Personal data after login

Privacy and freshness take priority

Secure forwarding, connection optimization, and routing optimization

No cross-user reuse and no loss of authentication information

Write and transaction endpoints

Idempotency, ordering, and deterministic outcomes

Reliable forwarding and timeout management

Methods, request bodies, retries, and error semantics

Long-polling or streaming endpoints

Long-lived connections and continuous transmission

Maintain connections and deliver data promptly

Protocol support, timeouts, buffering, and disconnect behavior

First measure request volume, response size, update frequency, acceptable staleness, and origin processing cost for each group, then define the pilot scope. A high request cache hit ratio does not necessarily mean substantial bandwidth savings. Many small JSON cache hits can raise the request hit ratio while the byte hit ratio remains low if large responses continue to come from the origin. Conversely, a small number of database-intensive queries may be the most valuable caching targets even if their responses are small.

For orders, balances, and permission checks, do not broaden the sharing scope just to improve hit ratios. For the initial deployment, enable caching only for explicitly listed public GET paths. Keep all other endpoints out of shared caching, and confirm that forwarding, error handling, and timeouts preserve application semantics. Expand cache coverage only after correctness tests pass.

Evaluate Product Differences Through Control Models and Application Paths

CloudFront: First Check Whether Your Existing AWS Architecture Reduces Integration Work

The CloudFront Developer Guide explains that CloudFront can distribute static and dynamic content, with either AWS services or your own HTTP servers as origins. The claim that CloudFront cannot be used outside AWS is therefore incorrect. However, the origin's network, access controls, and your team's configuration practices affect the actual integration effort.

The AWS CloudFront product page lists dynamic content and APIs as use cases and describes capabilities such as edge termination, gRPC, and WebSockets. This establishes the product's scope, not that your account, origin protocols, and specific behaviors are already configured correctly. If your application uses these protocols, test them separately. A standard JSON GET performance test cannot replace long-lived connection acceptance testing.

CloudFront is a good candidate for an initial pilot when the origin is already on AWS, the team can incorporate distribution configuration into its existing release, logging, and permission management processes, and caching requirements can be clearly expressed through path categories, request variants, and freshness rules. The next question is not whether it has CDN functionality, but which cache and forwarding policies actually apply to each API and whether those policies change application semantics.

Do not apply generic object-caching examples from the documentation directly to APIs. In particular, check whether TTL constraints allow the origin's intent to prohibit shared caching to be honored, and exactly how authorization headers, cookies, and query parameters are handled. These are account configuration acceptance checks; a product homepage is not a substitute.

Fastly: Cache Control Has Value, but Rule Maintenance Has a Cost

The Fastly caching documentation explicitly distinguishes the readthrough, simple, and core interfaces. The CDN service uses a readthrough HTTP cache; simple and core are programming interfaces available in Compute. When evaluating Fastly CDN, do not fold Compute's direct cache programming capabilities into the same solution while ignoring development and operating costs.

The documentation states that the readthrough cache supports mechanisms including request collapsing, client and backend revalidation, and cache purging. For popular public APIs, these capabilities can reduce duplicate fetches. However, request collapsing depends on conditions such as object cacheability. It does not imply that all authenticated requests will be collapsed or guarantee that a particular origin will receive only one request during a burst.

The Fastly CDN product page highlights programmable control, configuration rollback, logging, and Origin Shield use cases. These capabilities warrant dedicated testing for endpoints such as inventory displays, content aggregation, and catalogs, where updates are frequent but responses can be shared briefly. Purge claims on a product page cannot be translated directly into an end-to-end update commitment for your application: database commits, application caches, CDN invalidation, and client caches can all determine when users see a new value.

Fastly is a good candidate for an initial pilot when the team genuinely needs fine-grained control and has people responsible for maintaining rules, testing variants, and managing releases. Greater rule flexibility requires stronger version control and regression testing. More control does not automatically mean lower cost. If almost all endpoints are uncacheable, complex caching logic may not deliver enough value.

Cache Control Starts with “Which Requests Can Share the Same Answer?”

Define the Response Contract Before Writing Vendor Configuration

Consider a public catalog endpoint. Suppose the application allows shared caches to retain a response for 30 seconds, while clients must revalidate before each reuse. The origin could return the following response headers. This is an example contract, not a default for either vendor:

Cache-Control: public, max-age=0, s-maxage=30
ETag: "catalog-v42"
Content-Type: application/json

The intent is to give shared caches a freshness lifetime of 30 seconds without giving clients the same period of direct reuse. ETag provides a validator for conditional requests, but it does not itself guarantee that the CDN will cache the response or mean that every request must reach the origin. Confirm the actual behavior against enabled policies and observed responses.

For personal information that should not be stored, start with a more conservative response contract:

Cache-Control: private, no-store
Content-Type: application/json

private restricts shared caching, while no-store instructs caches not to store the response. Do not interpret no-cache as “do not store”: it requires validation before reuse, which is not the same as prohibiting storage. Response headers are not the only line of defense, either. Edge rules that override origin intent can still cause incorrect caching. Check both origin responses and final edge responses, and use actual reuse tests for acceptance.

One Missing Cache-Key Dimension Can Leak Data; One Extra Dimension Can Erase the Benefit

Suppose the content at /v1/catalog depends on language, currency, and tenant. Those dimensions must be represented in the cache key, path partitioning, or reliable edge normalization logic. Reusing responses by path alone could return the same data to different tenants. Including every cookie and query parameter in the cache key, however, could fragment a shared object into many entries with little reuse.

Create a contract table for each candidate endpoint:

Input dimension

Does it change the response?

Handling principle

Validation method

lang, currency

If they change content

Explicitly include them in variants

Different values should return the corresponding content

Pagination, sorting, filtering

Usually change content

Do not ignore them arbitrarily

Compare result sets and ordering

Advertising tracking parameters

When confirmed not to change content

Consider excluding them from the key

Changing the parameters should leave body semantics unchanged

Authorization

May change permissions and content

Prohibit sharing initially; design exceptions separately

Responses must not be mixed across identities

Session cookies

May change personalized content

Define forwarding and caching boundaries explicitly

Test login, logout, and account switching

Forwarding a value to the origin does not mean it is included in the cache key. If a tenant header is forwarded to the application but does not participate in cache isolation, the application may return the correct result initially, only for the edge to reuse it for other tenants. Conversely, including a field in the cache key without forwarding it to the origin as intended can create many separate cache entries with identical content.

Vary can express which request headers a response depends on, but its presence alone does not prove that the vendor configuration implements every intended behavior. Test authentication, cookies, and multitenant APIs with synthetic identities in an isolated environment rather than taking chances with real user data. Any cross-identity reuse should block deployment immediately; performance gains do not offset it.

TTL, Revalidation, and Invalidation Are Three Different Mechanisms

TTL determines how long a response can be reused directly. Revalidation checks whether a response is still valid after expiration or when confirmation is required. Proactive invalidation stops reuse before expiration. None is a substitute for the others.

For example, a product description may tolerate brief staleness, while a transaction price must be checked again at submission. The display API can use short-lived caching, but the order service must still read the authoritative price. Fast CDN purging does not make an edge cache responsible for transaction consistency.

The Fastly documentation also notes that caches are temporary storage and objects may be evicted before expiration. TTL therefore does not guarantee residency. A cold object being fetched from the origin again is normal, and the origin must be able to handle it. For frequently updated content, the value and limits of instant cache control can help further separate invalidation requirements, but you still need to test the current service configuration before adopting it.

Use the Same curl Experiments to Distinguish Cache Hits, Revalidation, and Uncacheable Requests

Fix the Test Conditions Before Running Repeated Requests

Set up isolated test services running the same version for both vendors. The examples use api.example.com; replace it with each test hostname when running them. Keep certificates, paths, origins, data versions, compression, and authentication conditions consistent. To compare different edge entry points under the same hostname, use controlled DNS or connection targeting while keeping Host and TLS SNI consistent.

Prepare at least four request types: a public cacheable GET, a public GET with variants, a personal-data GET, and a test write with no side effects. Do not repeatedly benchmark writes against production payment, order, or message-sending endpoints.

The following request saves response headers and the body while reporting connection and transfer timings:

curl --silent --show-error \
  --connect-timeout 5 --max-time 20 \
  --dump-header /tmp/api-edge.headers \
  --output /tmp/api-edge.json \
  --write-out 'code=%{http_code} remote=%{remote_ip} http=%{http_version} dns=%{time_namelookup} connect=%{time_connect} tls=%{time_appconnect} pre=%{time_pretransfer} ttfb=%{time_starttransfer} total=%{time_total}\n' \
  'https://api.example.com/v1/catalog?lang=zh&currency=CNY'

These times are reported in seconds and mostly represent cumulative time from the start of the request to a particular stage. They are not independent durations that can simply be added together. For this simple HTTPS request, which uses a new curl process and does not explicitly follow redirects:

  • Use time_namelookup as a reference for DNS lookup time.

  • Approximate the TCP stage by subtracting time_namelookup from time_connect.

  • Approximate the TLS stage by subtracting time_connect from time_appconnect.

  • time_starttransfer is cumulative TTFB, not origin processing time.

  • Subtracting time_pretransfer from time_starttransfer still includes request transmission, network waiting, edge processing, and upstream processing. It cannot be labeled directly as origin fetch time.

  • Subtracting time_starttransfer from time_total roughly represents the receive phase after the first byte.

Proxies, connection reuse, and protocol negotiation affect interpretation. Starting a separate process for each request primarily measures the new-connection path; it does not represent the real distribution for a mobile app that reuses connections. If you encounter a 3xx response, record the status and destination first, then design a separate redirect experiment. Do not silently enable redirect following and continue using the simplified differences above to explain the entire path.

Repeated Requests Provide Clues, Not Standalone Proof of a Cache Hit

Record the first response, then repeat the request from the same client with identical parameters and headers. Check the status code, Cache-Control, Age, validators, and any available vendor cache diagnostic headers, and compare the body version.

Interpret the results as follows:

  • If diagnostic headers report a hit, the body version is correct, and origin logs show no corresponding new request, the evidence supports that the request was served from cache.

  • If the response reports MISS but the origin shows no new request, investigate intermediate caches, shielding layers, or logging boundaries. Do not immediately assume logs are missing.

  • If responses are fast but every request appears at the origin, the connection or path may simply be good. That is not a caching benefit.

  • If Age is absent or consistently low, that alone does not prove there is no caching. Correlate it with other signals.

Do not add a random query parameter to every request to “ensure a realistic test” and then claim to have measured a warm cache. Random parameters may change the cache key, turning the experiment into a continuous series of cold requests. Conversely, if the policy ignores those parameters, they do not guarantee a cold cache either. Use controlled new resource versions or explicit invalidation for cold-cache tests, and record the method.

Check Response Bodies, Not Just Headers, for Variants and Conditional Requests

Run cross-variant sequences for language, currency, and tenant: request A, then B, then A again, checking business fields in every response body. For tracking parameters that should be equivalent, check whether they cause unnecessary cache fragmentation. Body comparisons should ignore fields explicitly known not to affect semantics, such as certain timestamps. Different raw bytes alone do not prove successful variant isolation.

For conditional requests, use the ETag actually returned by the first response:

curl --silent --show-error \
  --dump-header /tmp/api-revalidate.headers \
  --output /tmp/api-revalidate.body \
  -H 'If-None-Match: "catalog-v42"' \
  'https://api.example.com/v1/catalog?lang=zh&currency=CNY'

This example is meaningful only if the first response actually returned that validator. A 304 response means the client's existing representation passed validation, but it does not prove that the request reached the origin. The Fastly caching documentation explains that readthrough can handle client conditional requests and may also perform backend revalidation. Use edge and origin logs to distinguish what actually happened.

Temporary files may contain response data or sensitive headers. Store only synthetic data on an isolated test machine and delete it afterward. For authentication tests, do not put tokens directly into shared scripts, command screenshots, or release logs.

Testing the Origin Path Requires Origin Evidence, Not Just Client-Side Timing Differences

Establish a Direct-Origin Baseline That Preserves Host and SNI

Accessing an origin IP directly often reaches the default virtual host or causes certificate validation to fail, so it does not test the same service. If the origin actually uses api.example.com as its HTTPS virtual host and controlled testing has been authorized, you can use:

curl --silent --show-error \
  --resolve 'api.example.com:443:203.0.113.10' \
  --connect-timeout 5 --max-time 20 \
  --dump-header /tmp/api-origin.headers \
  --output /tmp/api-origin.json \
  --write-out 'code=%{http_code} ttfb=%{time_starttransfer} total=%{time_total}\n' \
  'https://api.example.com/v1/catalog?lang=zh&currency=CNY'

203.0.113.10 is a documentation example address and must be replaced with an authorized test address. --resolve preserves the Host and TLS SNI associated with the URL hostname, without disabling certificate validation. If the CDN uses a different hostname, specific authentication headers, or other access controls when contacting the origin, design the comparison around the actual origin access contract rather than copying this command blindly.

If the origin permits only CDN access, prefer measurements from an authorized probe location or an internal network. Do not expose it to the entire internet for an experiment. If a temporary change is necessary, allow only the designated test egress address for a limited window, then restore and verify the restrictions afterward.

This experiment compares end-to-end results for “client directly to origin” and “client through CDN.” The paths differ. Subtracting their TTFBs does not give CDN-to-origin fetch time or pure edge processing overhead.

Correlate Requests to Explain Where the Delay Occurs

Add a random correlation identifier containing no identity information to test requests, such as X-Test-Request-ID. First confirm that it is forwarded, does not change the response, and is excluded from the cache key. Then use it to correlate client records, available edge logs, and origin access logs. At the origin, also record receipt time, processing duration, status code, and a summary of dependency calls.

For cache hits, the absence of new origin logs may be exactly what you expect. For MISS requests, origin records can confirm whether the request actually reached the application entry point, but may not expose every internal cache layer before it. Do not echo a client-supplied correlation identifier into a response that can be shared by everyone; the cache could return an old identifier to subsequent requests.

Narrow the investigation according to the evidence:

Observation

Investigate first

Next step

Even hits are slow, with high connection-establishment time

User-to-edge path or connection establishment

Group by ISP, protocol, and new versus reused connections

Hits are fast, misses are slow, and application processing is also slow

Application, database, or downstream dependencies

Optimize the origin and assess the value of cache coverage

Misses are slow, but application processing is consistently short

Origin connections, transfer, queuing, or intermediate layers

Correlate edge and ingress logs to locate the delay

Origin requests surge when objects expire together

Cache fragmentation, collapsing conditions, or cold-start pressure

Run controlled concurrency and invalidation load tests

Averages improve but timeouts increase

Tail-path behavior or timeout configuration

Include failures in acceptance criteria and pause rollout expansion

Fastly documentation confirms that request collapsing exists, but the actual number of origin requests under concurrency still needs to be counted. Measure CloudFront behavior in the current account using the same method. The fact that the available material does not elaborate on a mechanism does not mean the other vendor lacks it.

Updates, Errors, and Traffic Bursts Reveal More Than a Single Warm-Cache Hit

Measure When Users See the New Value, Not Just Whether the Invalidation Call Succeeds

Add an explicit data version to a public test endpoint. First populate caches with the old version at multiple test locations, then update the origin, and finally execute the planned invalidation process or wait for expiration. Record the times of the origin commit, availability of the new version for reading, completion of the invalidation operation, and the first observation of the new version at each test location.

Do not treat a successful invalidation API response as proof that propagation is complete. Client caches, application caches, and read-replica lag can all return old values even after the CDN has been purged. First prove that the authoritative origin read has been updated, then assess whether edge updates meet the application's timing budget.

Also observe the origin request peak after the update. A very fast purge that sends all requests to the database at once is not necessarily better than a stable short-TTL approach. If brief staleness is acceptable, evaluate the relevant policies further. The available material is insufficient to confirm the specific conditions for every related option from both vendors; use the capabilities configurable in the current service as your reference.

Validate Error Responses and Write Requests Separately

In an isolated environment, introduce 404, 429, transient 5xx, connection timeouts, and slow responses in sequence. Observe whether errors are cached, for how long, and whether stale errors continue to be returned after recovery. Pay particular attention to whether 429 responses contain user-specific information and whether error caching turns a localized rate limit into failures for all users.

For write endpoints, verify that the request body, Content-Type, and authentication information reach the origin intact, and check the business outcome after a timeout. A client not receiving success does not mean the transaction was not committed. Retries require application-level idempotency design. Do not assume edge failover or retries automatically guarantee “exactly once” execution.

For long-lived connections, separately test establishment, prolonged idle periods, periodic heartbeats, server-initiated disconnects, and recovery. Low TTFB for an ordinary GET does not prove that streaming responses will avoid buffering or that long-lived connection timeouts meet application requirements.

Turn Test Results into Purchasing and Deployment Criteria

Compare Under Identical Conditions and Keep Failures in the Statistics

Report public warm-cache requests, public cold-cache requests, and uncacheable requests separately. Further group them by country or region, ISP, residential broadband or mobile network, IPv4 or IPv6, and new or reused connections. Samples from mainland China, Hong Kong, Macao, Taiwan, and overseas must not be combined into a single “Asia speed” figure. Cloud-hosted egress does not represent residential networks either.

Use the same resource sizes, request methods, headers, data versions, and sampling periods for both vendors. Alternate samples or collect them in parallel to avoid comparing peak-period results with off-peak results. Record statuses, failures, and timeouts for every attempt, then calculate latency distributions for successful requests. Showing only the P95 of successful samples can hide a reliability regression. Group-level P95 values cannot simply be averaged to produce an overall P95.

Teams can use CdnChart's measurement methodology to standardize definitions, then organize candidate requirements with the vendor comparison. These pages do not replace application-specific authentication checks, cache correctness testing, or origin log verification.

Before Quotes Are Available, Define Which Costs You Will Compare

The CloudFront Developer Guide explains that charges include edge data transfer out and HTTP or HTTPS requests, and vary by region, usage type, and features. For the AWS origins listed in the documentation, it also describes applicable exemptions for data transfer from the origin to CloudFront. This does not make the entire API origin path free: application compute, databases, load balancers, and other resources still need to be accounted for.

The available material does not include enough Fastly pricing information for a like-for-like unit-price comparison. Procurement should ask both vendors to itemize regions, currencies, request counts, and traffic units, as well as logging, security, edge computing, support, minimum commitments, and overage charges. Small JSON APIs may be more sensitive to per-request charges. For low-hit-ratio endpoints, also check whether origin resource usage actually decreases.

Include the labor required to maintain rules, handle invalidation, store logs, perform integration testing, and roll back failures. Only quotes based on the same business volume and feature scope can support a conclusion about which option is cheaper.

Practical Selection Rules

Pilot CloudFront first when the origin and primary operations are already on AWS, public API caching rules are relatively straightforward, authentication isolation can be preserved after integration, and uncacheable requests from target users show no regression in failure rate or tail latency.

Pilot Fastly CDN first when shared responses change frequently, the team needs fine-grained control over cache logic, invalidation, and logs, and it can maintain versioned rules. You must also prove that update propagation meets the application's timing budget and that cold starts and bulk invalidation do not overwhelm the origin.

Do not adopt either based solely on cache-hit performance if most traffic is personalized or transactional. Make the uncacheable path the primary acceptance target. If neither improves the experience in critical regions, revisit origin location, application processing, databases, and API gateway architecture rather than increasing cache TTLs to hide the problem.

Define Staged Rollout and Rollback Triggers Before Deployment

Use a test domain first to validate certificates, Host/SNI, path matching, request bodies, expected caching behavior, and security rules. Then run a small-traffic staged rollout for low-risk public APIs. Adjust TTL appropriately before a DNS switch, accounting for resolver caches and existing long-lived connections. Configuration switch time is not the time at which every user has completed migration.

The observation window should cover peak traffic, at least one normal update, and one controlled invalidation. Set its exact length according to the endpoint's operating cycle. Retain the old entry point and sufficient origin capacity behind it, so rollback does not encounter a cold old cache and an origin with no spare capacity.

Treat the following as hard requirements, not a post-launch optimization checklist:

  • Private responses must not be reused across identities or tenants. Pause the staged rollout after a single occurrence.

  • Public endpoints must return correct language, currency, pagination, and sorting results.

  • Update visibility must meet the agreed business timing budget, and origin load after invalidation must remain manageable.

  • Failure rates, timeouts, and tail latency in critical regions must meet thresholds. A faster average does not offset failures.

  • Writes, errors, rate limiting, and long-lived connections must behave according to the application contract.

  • Rollback configurations, certificates, security rules, and DNS restoration paths must be rehearsed.

Ultimately, the better API fit between CloudFront and Fastly is not determined by HIT in a response header or the lowest TTFB in a single test. Three conditions must hold together: shared caching remains correct, the complete path for non-shared requests meets requirements, and updates and failures can still be brought back to a controlled state. Establish those three conditions first, then compare bills and maintenance costs. Only then does the choice have business value.

  • CloudFront and Fastly
  • API CDN selection
  • API cache control
  • CDN origin path testing

Related posts