Sub topic 1
How a CDN and Edge Caching Work
This chapter explains what a content delivery network (CDN) does, how Amazon CloudFront handles a request from a viewer to an S3 origin, and why a cache hit or miss changes what the viewer experiences. Later chapters build on this model when they configure distributions, cache policies, and invalidations.
Prerequisites
This chapter assumes you already know:
- Basic Amazon S3 concepts: buckets, objects, and keys.
- How HTTP requests, responses, and status codes work, including headers such as
Cache-Control. - How to read a simple IAM or JSON policy.
- How to run AWS CLI commands.
You do not need a CloudFront distribution yet. This chapter is conceptual, with a few commands you can try once you have one.
The problem a CDN solves
An S3 bucket lives in one AWS Region. If your bucket is in us-east-1 and a viewer is in Sydney, every request travels across the world and back. Three things go wrong as traffic grows:
- Latency. Distance adds round-trip time to every connection and every object.
- Origin load. Every viewer request becomes an S3 request, even for a file that has not changed in months.
- Cost and limits. You pay S3 request and data transfer charges for each repeated download.
A CDN is a network of servers placed close to viewers. It keeps copies of your content and answers requests from those copies. The original source of the content is called the origin. In this tutorial the origin is an S3 bucket.
Key terms
| Term | Meaning |
|---|---|
| Viewer | The client making the request, such as a browser or mobile app. |
| Origin | The server that holds the authoritative copy of the content. Here, an S3 bucket. |
| Edge location | A CloudFront site that is geographically close to viewers and answers requests directly. |
| Regional edge cache | A larger, intermediate cache that sits between edge locations and the origin. |
| Cache hit | The cache already holds a fresh copy and returns it without contacting the origin. |
| Cache miss | The cache has no fresh copy and must fetch the object from the next layer. |
| TTL | Time to live. How long a cached copy counts as fresh. |
| Cache key | The values CloudFront uses to decide whether two requests are asking for the same object. |
The request flow
CloudFront uses a tiered design. A viewer is routed to a nearby edge location. If that edge does not have the object, it asks a regional edge cache. If that cache does not have it either, the request goes to the origin.
Step by step:
- The viewer looks up your distribution's domain name (for example
d111111abcdef8.cloudfront.net). DNS directs the viewer to a nearby edge location. - The edge location builds a cache key from the request and checks its local cache.
- On a hit, it returns the stored object immediately. The origin is never contacted.
- On a miss, it forwards the request toward the origin through the regional edge cache.
- S3 returns the object. Each cache layer stores a copy according to its TTL, and the edge returns the object to the viewer.
- Later requests for the same cache key are served from the edge until the TTL expires.
Regional edge caches matter for content that is requested rarely. An edge location may evict an object that few viewers ask for, but the larger regional cache is more likely to still have it. That keeps those requests off S3.
Fresh, stale, and revalidation
A cached object is fresh while its age is below its TTL. Once the TTL passes, the object is stale. CloudFront does not necessarily discard a stale object. If the object is still in cache, CloudFront can send a conditional request to the origin using If-None-Match (with the stored ETag) or If-Modified-Since.
- If S3 answers
304 Not Modified, CloudFront keeps the cached body and resets the freshness clock. Only headers cross the network, so this is cheap. - If S3 answers
200 OKwith a new body, CloudFront replaces the cached copy.
This is why an object you overwrite in S3 does not appear immediately for viewers. Until the cached copy expires or you remove it, viewers keep receiving the old version. Later chapters cover the two ways to handle this: invalidations and versioned file names.
What decides the TTL
CloudFront chooses a TTL from three inputs: the minimum, default, and maximum TTL set in the cache policy, and the Cache-Control or Expires headers on the object that S3 returns.
- If the object has
Cache-Control: max-age=Nors-maxage=N, CloudFront uses that value, limited to the range between the minimum and maximum TTL. - If the object has no caching header, CloudFront uses the default TTL. The managed CachingOptimized policy uses a default of 86,400 seconds (24 hours).
- If the object says
no-storeorprivateand the minimum TTL is 0, CloudFront does not cache it for reuse.
You set caching headers on S3 objects when you upload them. This command stores a fingerprinted asset for one year:
aws s3 cp ./dist s3://amzn-s3-demo-bucket/assets/ --recursive --cache-control "public,max-age=31536000,immutable"The max-age value is in seconds. The immutable directive tells browsers they never need to revalidate the file while it is fresh. This is safe only when the file name changes whenever the content changes.
Two caches, two sets of rules
There are two places a copy of your object can live: the browser and CloudFront. They share the Cache-Control header but are separate caches.
max-ageapplies to both the browser and CloudFront.s-maxageapplies to shared caches such as CloudFront and overridesmax-agethere. Use it when you want a short browser lifetime but a longer edge lifetime.- Invalidating an object in CloudFront does not clear copies already stored in viewers' browsers.
The cache key
The cache key decides whether two requests share one cached object. By default, the key includes the distribution, the URL path, and the host. Query strings, cookies, and headers are included only if the cache policy says so.
This has two practical effects:
- Too narrow a key (for example, including every query string) means near-identical requests create separate cache entries. The hit ratio drops and S3 receives more requests.
- Too wide a key (for example, ignoring a query string that actually changes the content) means viewers can receive the wrong object.
For static files in S3, the default of path only is usually correct. Later chapters on cache policies cover how to change this deliberately.
Reading the result: cache headers
CloudFront adds response headers that show what happened. You can inspect them with curl:
curl -sI https://d111111abcdef8.cloudfront.net/logo.png | grep -iE "x-cache|age|via"Typical output on a second request:
x-cache: Hit from cloudfront
age: 42
via: 1.1 abc123.cloudfront.net (CloudFront)| Header | What it tells you |
|---|---|
| `X-Cache` | `Hit from cloudfront`, `Miss from cloudfront`, `RefreshHit from cloudfront` (stale object revalidated), or `Error from cloudfront`. |
| `Age` | Seconds the object has been in the cache. |
| `Via` | Confirms the response passed through CloudFront. |
A Hit with a small Age shows the edge is serving a stored copy. A Miss on the first request is normal. If you see only misses for a file that should be cached, check for Cache-Control: no-store, a very short TTL, or a query string that varies per request.
Common errors and misunderstandings
- "I uploaded a new file but viewers still see the old one." The cached copy has not expired. Either wait for the TTL, invalidate the path, or publish under a new file name.
- "The first request is always slow." A miss goes to the origin. The cost is paid once per cache layer and per cache key, then later requests are fast.
- "A CDN makes every request fast." Only cacheable responses benefit. Content that changes per request and is marked uncacheable still goes to the origin each time, though CloudFront can still shorten the network path.
- "Caches are shared across all edges." Each edge location keeps its own copy. A hit in Frankfurt does not warm the cache in Tokyo, although the regional edge cache can help nearby edges.
- "Setting a long TTL is always better." A long TTL improves hit ratio but delays updates. Match the TTL to how often the content changes.
Choosing TTLs by content type
| Content | Changes how often | Reasonable approach |
|---|---|---|
| Fingerprinted JS and CSS (`app.3f9a1c.js`) | Never, because a change creates a new name | Very long TTL, such as one year, with `immutable` |
| Images and fonts with stable names | Rarely | Long TTL, such as days or weeks, and invalidate when you replace them |
| `index.html` | At each deploy | Short TTL, such as minutes, or invalidate on deploy |
| Per-user or private data | Per request | Do not cache at the edge, or use signed URLs and cookies |
What to take forward
CloudFront answers from the nearest cache when it can and goes to S3 only when it must. The TTL, the cache key, and the Cache-Control headers you set on S3 objects determine how often that happens and how quickly updates reach viewers. The next chapters set up S3 as the origin and then configure these behaviors in a real distribution.
Exercise
A viewer in Tokyo requests /app.css for the first time. Another viewer in Paris requested the same file an hour ago. The TTL is 24 hours. Which requests reach S3, and what does X-Cache likely show for the Tokyo viewer's second request a minute later?
Show answer
The Paris request reached S3 (through the regional edge cache serving Paris). The Tokyo edge location has its own cache, so its first request is a miss at that edge. It may be answered by a regional edge cache if that cache already holds the file, otherwise it goes to S3. The Tokyo viewer's second request a minute later is a hit at the Tokyo edge, so X-Cache shows "Hit from cloudfront".
Exercise
You upload logo.png with Cache-Control: max-age=31536000, then replace the file in S3 the next day with a new design under the same key. Why do viewers still see the old logo, and name two ways to fix it?
Show answer
CloudFront (and browsers) hold a copy that stays fresh for one year, so they never ask S3 for the new version. Fix it by invalidating the path in CloudFront (this does not clear copies already in browsers) or, better, by publishing the new image under a new file name such as logo.v2.png and updating the references. A shorter max-age for files that change would also reduce the problem.
Exercise
A request for /photo.jpg?session=8841 always shows "Miss from cloudfront", even though the file never changes. What is the likely cause and the fix?
Show answer
The cache policy includes the query string in the cache key, and the session value is different for each viewer, so every request has a unique key. Change the cache policy so the query string is not part of the cache key for static files, or remove the session parameter from those URLs.