A print works and its newsstands
Imagine a print works that makes the pages everyone wants to read. It's in one town, so a reader on the far side of the country would wait ages for a page to come by post.
So the print works sets up a newsstand in every neighbourhood. You walk to the stand down the road and ask for a page. If the stand has a stack of copies, you get one straight away. If it hasn't, it sends a runner, who stops at a bigger district depot on the way and only goes on to the print works if the depot hasn't got it either. The stand gets a copy, keeps a stack for the next reader and hands one to you.
The print works is the origin. The stands are CloudFront.
What a CDN does
A content delivery network (CDN) is a large set of servers spread around the world that sit between viewers and your servers. Amazon CloudFront is AWS's CDN.
| Term | Meaning |
|---|---|
| Viewer | The browser or app making HTTP requests |
| Edge location | A CloudFront data centre near viewers that terminates connections and caches responses |
| Regional edge cache | A larger, mid-tier cache between edge locations and origins |
| Origin | Where the real content lives: an S3 bucket, a load balancer, any HTTP server |
| Distribution | Your CloudFront configuration, with its own domain such as d111111abcdef8.cloudfront.net |
DNS for the distribution's domain answers with addresses of a nearby edge location, so the viewer's TCP and TLS handshakes travel a short distance. The edge serves from its cache when it can and otherwise fetches from the origin (usually through a regional edge cache), stores the response and returns it.
Each edge location caches independently, so the first request for an object in each place is a miss. The win is lower latency for viewers and far fewer requests reaching the origin. CloudFront speaks plain HTTP semantics (see HTTP), and its caching follows the same ideas as distributed caching.
Different doors at the print works
The print works has more than one door. Finished pages that never change, like maps and pictures, sit in the storeroom. Things made fresh for each reader, like a personal receipt, come from the order desk, where staff make them on the spot. And some pages come from a partner printer across town.
Every stand keeps a list that says which door each kind of page comes from: "pictures from the storeroom, receipts from the order desk". Receipts are made for one reader, so the stand never keeps a stack of them.
Origins and cache behaviors
A distribution can have several origins:
- an S3 bucket (see S3), for static files such as images, CSS, JavaScript and whole single-page apps;
- an Application Load Balancer (or API Gateway, or a Lambda function URL), for dynamic responses;
- a custom origin: any HTTP server reachable by a domain name, on AWS or not.
Cache behaviors route requests to origins by path pattern, such as /images/* or /api/*, checked in
order, with a default behavior * last. Each behavior has its own settings: which origin, which HTTP methods
are allowed, the viewer protocol policy, a cache policy and optional edge functions.
Dynamic or personalised paths usually get the managed CachingDisabled policy, so every request goes to the
origin. Even then CloudFront helps: TLS ends near the viewer and the edge reuses warm connections to the origin
over the AWS network. An origin group pairs a primary and a secondary origin for failover.
Fresh copies and good-until stamps
When the runner brings a page back, the print works stamps it "good until four o'clock". Until then, the stand hands out copies from its stack: that's a hit. When the stand hasn't got the page, it has to send the runner: that's a miss.
When the stamp runs out, the stand doesn't throw the stack away. It asks the print works "is this page still the latest?" If it is, the print works just says "yes, good for another hour", which is much quicker than printing it again. If the print works forgot to stamp a page, the stand uses its own house rule for how long to keep it.
Hits, misses and TTLs
How long an object stays fresh in the cache is its TTL. Two things decide it:
- The origin's response headers:
Cache-Control: max-age=3600,s-maxage(which applies to shared caches such as CloudFront, so the browser can usemax-ageand the CDN a different value), orExpires. - The behavior's cache policy, which sets a minimum, default and maximum TTL. The default TTL applies only
when the origin sends no
max-age,s-maxageorExpires. The maximum caps what the origin asks for. A minimum above 0 makes CloudFront cache even responses markedno-cache,no-storeorprivate, so keep it at 0 unless you mean that.
The managed CachingOptimized policy, a common choice for static files, has a minimum TTL of 1 second, a
default of 24 hours and a maximum of one year. Because its minimum is above 0, use CachingDisabled for paths
whose responses must never be cached. If all three TTLs are 0, caching is off.
When a cached object expires, CloudFront revalidates it with a conditional request (If-None-Match with the
ETag, or If-Modified-Since). An unchanged object comes back as 304 Not Modified with no body, and the edge
keeps serving its copy. The response header X-Cache shows Hit from cloudfront, Miss from cloudfront or
RefreshHit from cloudfront (revalidated),
and Age shows how long the copy has been cached.
When are two orders the same page?
Readers ask for pages on order slips. The stand has to decide when two slips mean the same page, so it can hand out a copy from the same stack. The parts of the slip it looks at make up the page's shelf label, called the cache key.
"The menu, in English" and "the menu, in French" are different pages, so the language belongs on the label. But "which advert you saw" doesn't change the page at all, so the stand ignores it. If the stand put each reader's own name on the label, every reader would get their own stack, and the stand would end up sending the runner for almost everyone.
Cache keys
The cache key is what decides whether two requests get the same cached object. By default it contains only the distribution's domain name and the URL path. Query strings, headers and cookies are left out unless the cache policy adds them.
- Include what really changes the response: a
langquery string, or theAccept-Encodingnormalisation that lets CloudFront cache gzip and Brotli versions separately. - Leave out what doesn't: tracking parameters like
utm_source, most cookies, theUser-Agentheader.
Every value you add to the key splits the cache into more variants and lowers the cache hit ratio. Adding the session cookie, for example, gives each visitor a private copy and turns the CDN into a pass-through.
If the origin needs a value that shouldn't affect caching, forward it with an origin request policy instead: those values reach the origin but stay out of the cache key. Anything in the cache key is forwarded to the origin automatically.
Changing a page that's already out there
Say the print works fixes a mistake on a page. The stands still have stacks of the old copy, each stamped good until tomorrow, and they'll keep handing them out.
You can send every stand a recall notice, called an invalidation: "bin your copies of this page". That works, but it takes a little while to reach every stand, and after the first thousand each month you pay for every one.
The smarter way is to give every new version a new name, like "map, edition 7". The new page has never been in any stack, so every stand fetches it fresh, and nobody can mix up edition 6 and edition 7. Only the front page, which tells readers which edition to ask for, needs a short stamp.
Invalidations versus versioned file names
Replacing a file at the origin doesn't change what the edges already hold. Until the TTL runs out, viewers keep getting the old object.
An invalidation removes objects from every edge cache before they expire. You submit paths such as
/index.html or /static/*; the next request for them is a miss. Invalidations take time to propagate, and the
first 1,000 paths per month (per account) are free, then each path is charged. A path with a * wildcard
counts as one path however many files it matches.
Versioned file names avoid invalidations for most files. Build tools put a content hash in the name
(app.3f9c1a.js), so a new build has new URLs that no cache has seen. Those files can have a very long TTL
(Cache-Control: public, max-age=31536000, immutable). Only the small entry point that references them, such as
index.html, gets a short TTL or an invalidation on deploy. Old and new versions never mix, and rolling back is
just pointing back at the old names.
An invalidation clears CloudFront's caches, not copies already in viewers' browsers.
A locked back door and sealed envelopes
If readers could walk into the print works storeroom, they'd skip the stands entirely, and nothing the stands check would matter. So the storeroom door stays locked, and only the stands' own runners carry the staff pass that opens it. The storeroom checks the pass belongs to these stands, not just any stand.
Between the reader and the stand, every page travels in a sealed envelope, and the stand shows an ID card that proves it really works for the print works. A reader who asks for an open, unsealed page is politely told to ask again for a sealed one.
Origin access control and HTTPS at the edge
Origin access control (OAC) keeps an S3 origin private. The bucket stays non-public (Block Public Access
on), and CloudFront signs its requests to S3 with SigV4. The bucket policy allows s3:GetObject for the service
principal cloudfront.amazonaws.com with a condition that AWS:SourceArn equals your distribution's ARN, so
only that distribution can read it. OAC replaces the older origin access identity (OAI), which AWS now calls
legacy; OAC also works with SSE-KMS encrypted objects. Direct requests to the bucket get 403 Access Denied.
For HTTPS between viewer and edge, attach a certificate for your domain (for example cdn.example.com) from
AWS Certificate Manager. CloudFront only accepts ACM certificates from the US East (N. Virginia) Region,
us-east-1, wherever your origin is. Edges serve it using SNI. The behavior's viewer protocol policy is
redirect-to-https (HTTP GET and HEAD get a 301 to HTTPS), https-only (HTTP is refused with 403) or allow-all. The
connection from edge to origin is configured separately by the origin protocol policy.
A helper at the counter
Sometimes a slip needs a small fix before the stand looks for the page: a reader asks for "the docs" and means "the docs, front page", or asks for a page that has moved. So each stand has a quick counter helper, an edge function, who can tidy a slip, send a reader to the right page, or add a note to a page on its way out.
For bigger jobs, like asking someone else before deciding which door the runner should use, there's a slower helper at the district depot who can make phone calls.
Edge functions
CloudFront runs your code at four points: viewer request, origin request (only on a miss), origin response and viewer response.
| CloudFront Functions | Lambda@Edge | |
|---|---|---|
| Runs at | Edge locations | Regional edge caches |
| Language | JavaScript | Node.js or Python |
| Triggers | Viewer request and viewer response | All four |
| Good for | URL rewrites, redirects, header changes, cache key normalisation, simple token checks | Network calls, choosing an origin, longer work, reading the request body |
CloudFront Functions are tiny and very cheap but have tight time and memory limits and no network access.
Lambda@Edge functions are created in us-east-1 and replicated by CloudFront.
The print works writes the stamps
The stands only follow the stamps they're given. So in your own workshop, the print works itself writes the good-until stamps, and its printing press gives each edition a new name. Long stamps go on editions that will never change, and a short stamp goes on the front page that tells readers which edition to ask for.
The origin's side in Spring
The origin still decides most caching. In Spring Boot, set Cache-Control on responses and let Spring put a
content hash into static resource URLs:
1spring.web.resources.chain.strategy.content.enabled=true2spring.web.resources.chain.strategy.content.paths=/**3spring.web.resources.cache.cachecontrol.max-age=365d4spring.web.resources.cache.cachecontrol.cache-public=true
These properties apply to every static resource, so give index.html its own short policy, for example a
WebMvcConfigurer resource handler for /index.html with CacheControl.noCache(). Spring only rewrites links
to hashed names in templates that resolve them through ResourceUrlProvider, such as Thymeleaf @ link
expressions; a single-page app's build tool does its own hashing.
1@GetMapping("/api/products/{id}")2ResponseEntity<Product> product(@PathVariable long id) {3return ResponseEntity.ok()4.cacheControl(CacheControl.maxAge(Duration.ofSeconds(60)) // browsers: 1 minute5.sMaxAge(Duration.ofMinutes(10)) // CloudFront: 10 minutes6.cachePublic())7.body(service.find(id));8}
For the files that keep their names, invalidate on deploy with the AWS SDK for Java v2:
1try (CloudFrontClient cf = CloudFrontClient.builder().region(Region.AWS_GLOBAL).build()) {2cf.createInvalidation(r -> r3.distributionId("E1ABCDEF234567")4.invalidationBatch(b -> b5.callerReference("deploy-" + System.currentTimeMillis())6.paths(p -> p.quantity(1).items("/index.html"))));7}
Origin Shield: an optional extra cache layer in one chosen region. All regional edge caches go through it, so a popular object is fetched from the origin about once, not once per region.
Errors are cached too: CloudFront caches some 4xx and 5xx responses for a short time (configurable per
status code), so a brief origin failure can linger. It can also serve stale objects when the origin is down if
the origin sent stale-if-error.
Compression: with compression enabled, CloudFront gzips or Brotli-compresses eligible responses itself,
and the normalised Accept-Encoding is part of the cache key.
Signed URLs and signed cookies restrict who can fetch content through CloudFront (paid downloads, private video), which OAC alone doesn't do: OAC protects the origin, not the edge.