What Is a CDN and How Does It Work?
When you open a website, your browser downloads dozens of files: the HTML page, stylesheets, scripts, fonts and images. If all of them come from one server far away, the page loads slowly, and a sudden rush of visitors can overload that server. A CDN (Content Delivery Network) solves both problems by keeping copies of your files on servers close to your visitors.
This beginner-friendly guide explains what a CDN is, how it works step by step, how caching is controlled with HTTP headers, how to clear old content, the difference between pull and push CDNs, and what else a modern CDN does. It also shows how to use a CDN with a Spring Boot application, with ready-to-use Java examples.
1. What Is a CDN?
A CDN, or Content Delivery Network, is a group of servers spread across many cities and countries. These servers store copies of your website's files and deliver them to each visitor from the closest location.
A shipping analogy makes this easy to picture. Imagine an online store that ships every order from a single warehouse in one city. Nearby customers get their parcels quickly, but customers on the other side of the world wait for days. Now imagine the store keeps its best-selling items in regional warehouses. Most orders now ship from a warehouse a few hours away, and the main warehouse only handles rare items. A CDN does exactly this for web content.
2. Why Websites Need a CDN
Every website has an origin server, the machine where your files and application actually live. When everything is served from that one place, two problems appear:
- Distance adds delay. Data travels fast, but every request still crosses many network hops, and each round trip costs time. A visitor 10,000 km from your server waits noticeably longer than one 100 km away, and a page that needs dozens of files multiplies that delay.
- One server takes all the load. If a thousand people request the same product image, your origin serves it a thousand times. When traffic climbs high enough, pages slow down or the server stops responding.
A CDN fixes both. It shortens the distance between users and content, and it answers most repeat requests itself so they never reach your origin. The result is:
- Faster pages for visitors everywhere.
- Lower load and bandwidth costs on your own servers.
- Better resilience during traffic spikes, such as a sale or a viral article.
- Extra security, because attacks hit the CDN's large network first.
3. Key Components of a CDN
| Component | What it does |
|---|---|
| Origin server | Your real server, where the original files and application live. |
| Edge servers | The CDN's servers close to users. They keep cached copies and answer requests directly. |
| Points of Presence (PoPs) | The physical locations, usually data centres, that house edge servers. Large CDNs have hundreds of them. |
| Cache | The storage on each edge server that holds copies of your files. |
| Routing system | Decides which edge server each visitor should use, through DNS or anycast. |
| Control panel and API | Where you configure caching rules, security settings and purges, and view analytics. |
4. How a CDN Works: Step by Step
Here is the journey of a single file, such as a product photo:
- The visitor's browser looks up your domain. Because your site is connected to the CDN, the lookup leads to a nearby edge server instead of your origin.
- The edge server checks whether it already has that photo in its cache.
- If it does, this is a cache hit: the photo is sent immediately, and your origin is not involved at all.
- If it does not, this is a cache miss: the edge server requests the photo from your origin, sends it to the visitor and keeps a copy.
- The next visitor in that region gets the stored copy, so only the very first request makes the long trip.
5. Cache Hit, Cache Miss and Hit Ratio
The share of requests answered from the cache is called the cache hit ratio:
cache hit ratio = cache hits / total requests x 100
Example: 9,500 hits out of 10,000 requests = 95%
Only 500 requests (5%) reached the origin server
It is the most important number for judging whether your CDN is doing its job. A high ratio, often 90% or more for static files, means your origin is mostly resting. A low ratio usually points to short cache times, cookies that stop caching, or URLs with changing query strings.
6. Controlling Caching with HTTP Headers
A CDN does not guess how long to keep a file. Your server tells it, mainly through the Cache-Control header sent with each response:
Cache-Control: public, max-age=86400
This says the file may be stored by anyone, including the CDN and the browser, and reused for 86,400 seconds, which is one day. This period is called the TTL (time to live). When it expires, the edge server checks with your origin for a fresh version. The most useful directives are:
| Directive | Meaning | Typical use |
|---|---|---|
public | Any cache, including the CDN, may store the response | Images, CSS, JavaScript, public pages |
private | Only the user's browser may store it, not the CDN | Pages personalised for one user |
no-store | Do not store the response anywhere | Account pages, payment details |
no-cache | May be stored, but must be checked with the origin before each reuse | HTML pages that change often |
max-age=N | Reuse for N seconds | Controls the browser and CDN TTL |
s-maxage=N | Reuse for N seconds in shared caches such as CDNs only | Cache longer on the CDN than in browsers |
stale-while-revalidate=N | Serve the old copy for up to N seconds while fetching a new one in the background | Keeping pages fast while content refreshes |
immutable | The file will never change at this URL | Versioned files such as app.4f2a9c.js |
When a cached copy expires, the CDN can ask the origin whether it changed instead of downloading it again. It sends the file's ETag or Last-Modified value, and if nothing changed, the origin replies with a tiny 304 Not Modified response.
7. Updating Content: Purging and Versioning
Caching is great until you change a file and visitors keep seeing the old one. There are two ways to deal with this:
- Purge (invalidate) the cache. Every serious CDN lets you remove a file, a folder or everything from its edge servers, through the dashboard or an API. The next request then fetches the fresh version from your origin.
- Version your file names. Include a version or a content hash in the name, such as
app.4f2a9c.jsorstyle.v2.css. When the content changes, the name changes, so it is simply a new file and no purge is needed. Versioned files can safely be cached for a year.
A common, reliable pattern is: versioned names with a long TTL for CSS, JavaScript, fonts and images, and a short TTL (or no-cache) for HTML pages, so updated pages that point to the new file names appear quickly.
8. Static vs Dynamic Content
Static content is the same for every visitor: images, videos, CSS, JavaScript, fonts and downloadable files. It is the perfect fit for caching.
Dynamic content changes per request or per user, such as search results, a logged-in dashboard or live prices. A CDN cannot simply store and replay it, but it still helps:
- It keeps fast, already-open connections to your origin, so each request travels a quicker route.
- It handles the secure HTTPS handshake close to the visitor, saving round trips.
- It compresses responses on the way.
- It can cache public API responses for a few seconds, which can cut origin load dramatically during busy periods.
Many CDNs also offer edge computing: small pieces of code that run on the edge servers themselves to redirect users, add headers, check simple rules or personalise responses without going back to your server.
9. Pull CDN vs Push CDN
| Aspect | Pull CDN | Push CDN |
|---|---|---|
| How files arrive | The CDN fetches them from your origin the first time someone asks | You upload them to the CDN yourself |
| Setup effort | Low, mostly automatic | Higher, you manage what is stored |
| First request | Slightly slower (a cache miss) | Fast, files are already there |
| Good for | Almost every website and app | Large files that rarely change, such as installers and video libraries |
Most sites use a pull CDN, because the cache fills itself and you do not need to change how you publish content.
10. How Users Reach the Nearest Edge Server
CDNs use two main techniques to send each visitor to a nearby, healthy edge server:
- DNS-based routing: when the browser looks up your domain, the CDN's DNS returns the address of an edge server close to the visitor.
- Anycast: the same IP address is announced from many locations at once, and the internet's own routing delivers each request to the nearest one. If a location goes offline, traffic automatically flows to the next closest.
Large CDNs often add tiered caching: edge servers that miss a file first ask a bigger regional cache instead of the origin, which raises the overall hit ratio and protects the origin even more.
11. More Than Caching: What Else a CDN Does
Modern CDNs have grown well beyond storing files. Depending on the provider and plan, you can get:
- HTTPS and TLS handling, often including free certificates.
- DDoS protection, absorbing floods of malicious traffic across a huge network.
- A web application firewall (WAF) that blocks common attacks such as SQL injection and cross-site scripting.
- Bot management to filter scrapers and abusive crawlers.
- Image optimisation, resizing images and converting them to formats like WebP or AVIF on the fly.
- Compression with Gzip or Brotli, and support for HTTP/2 and HTTP/3.
- Signed URLs that give temporary access to private files, such as paid videos.
- Analytics showing traffic, cache performance and errors by region.
12. Using a CDN with a Spring Boot Application
A CDN caches only what your application allows, so the most important work happens in your code: sending the right Cache-Control headers. Spring Boot makes this straightforward.
12.1 Cache headers for static files
Spring Boot serves files from src/main/resources/static. These properties give them a long cache time and add a content hash to their URLs, so a changed file automatically gets a new name:
# Let browsers and the CDN cache static files for one year
spring.web.resources.cache.cachecontrol.max-age=365d
spring.web.resources.cache.cachecontrol.cache-public=true
# Add a content hash to file names, e.g. /css/style-8f3a2c.css
spring.web.resources.chain.strategy.content.enabled=true
spring.web.resources.chain.strategy.content.paths=/**
With Thymeleaf, write links as th:href="@{/css/style.css}", and Spring inserts the versioned URL automatically.
12.2 Cache headers for API responses
For controllers, use Spring's CacheControl builder. Public data can be cached, and personal data must not be:
package com.example.shop.web;
import java.time.Duration;
import java.util.List;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/api")
public class ProductController {
private final ProductService productService;
private final OrderService orderService;
public ProductController(ProductService productService, OrderService orderService) {
this.productService = productService;
this.orderService = orderService;
}
// Public catalogue: browsers may cache for 1 minute, the CDN for 5 minutes
@GetMapping("/products/{id}")
public ResponseEntity<Product> getProduct(@PathVariable Long id) {
Product product = productService.findById(id);
return ResponseEntity.ok()
.cacheControl(CacheControl.maxAge(Duration.ofMinutes(1))
.sMaxAge(Duration.ofMinutes(5))
.cachePublic())
.eTag(String.valueOf(product.version())) // enables 304 Not Modified
.body(product);
}
// Personal data: never store it in the CDN or the browser
@GetMapping("/orders/my")
public ResponseEntity<List<Order>> myOrders() {
return ResponseEntity.ok()
.cacheControl(CacheControl.noStore())
.body(orderService.findForCurrentUser());
}
}
The first endpoint sends Cache-Control: max-age=60, s-maxage=300, public, so the CDN can answer most product requests itself. The second sends Cache-Control: no-store, so one customer's orders can never be served to another.
12.3 Serving static files from a CDN domain
Many teams serve assets from a separate CDN hostname, such as https://cdn.example.com. A small helper keeps the base URL in one configurable place:
package com.example.shop.web;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class AssetUrlBuilder {
private final String cdnBaseUrl;
// Set app.cdn.base-url=https://cdn.example.com in application.properties
public AssetUrlBuilder(@Value("${app.cdn.base-url:}") String cdnBaseUrl) {
this.cdnBaseUrl = cdnBaseUrl.endsWith("/")
? cdnBaseUrl.substring(0, cdnBaseUrl.length() - 1)
: cdnBaseUrl;
}
// "/images/logo.png" -> "https://cdn.example.com/images/logo.png"
public String url(String path) {
String cleanPath = path.startsWith("/") ? path : "/" + path;
return cdnBaseUrl + cleanPath;
}
}
If the property is empty, for example in local development, the helper falls back to relative URLs served by your own application.
13. Clearing the CDN Cache from Java
After a deployment you may need to remove old copies from the CDN. Most providers offer an API for this. The example below uses the AWS SDK for Java 2.x to create an invalidation in Amazon CloudFront. Add the software.amazon.awssdk:cloudfront dependency first:
package com.example.shop.cdn;
import java.util.List;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudfront.CloudFrontClient;
import software.amazon.awssdk.services.cloudfront.model.CreateInvalidationRequest;
import software.amazon.awssdk.services.cloudfront.model.CreateInvalidationResponse;
import software.amazon.awssdk.services.cloudfront.model.InvalidationBatch;
import software.amazon.awssdk.services.cloudfront.model.Paths;
public class CdnCachePurger {
private final CloudFrontClient cloudFront;
private final String distributionId;
public CdnCachePurger(String distributionId) {
// CloudFront is a global service, so it uses the AWS_GLOBAL region
this.cloudFront = CloudFrontClient.builder()
.region(Region.AWS_GLOBAL)
.build();
this.distributionId = distributionId;
}
/** Removes the given paths, e.g. "/index.html" or "/images/*", from all edge servers. */
public String purge(List<String> paths) {
InvalidationBatch batch = InvalidationBatch.builder()
.paths(Paths.builder()
.quantity(paths.size())
.items(paths)
.build())
.callerReference("purge-" + System.currentTimeMillis()) // must be unique
.build();
CreateInvalidationResponse response = cloudFront.createInvalidation(
CreateInvalidationRequest.builder()
.distributionId(distributionId)
.invalidationBatch(batch)
.build());
return response.invalidation().id();
}
public static void main(String[] args) {
CdnCachePurger purger = new CdnCachePurger("E1234567890ABC");
String id = purger.purge(List.of("/index.html", "/css/*"));
System.out.println("Invalidation started: " + id);
}
}
The SDK reads AWS credentials from the usual places, such as environment variables or an IAM role. Purges take a short while to reach every edge server, and some providers charge for very frequent purges, which is another reason to prefer versioned file names for CSS and JavaScript.
14. Where CDNs Are Used in the Real World
- Video streaming: Netflix built its own CDN, called Open Connect, and places servers inside internet providers' networks so popular shows travel a much shorter path.
- Online shopping: product images and scripts load quickly, and sale-day rushes do not overwhelm the site.
- News and blogs: when an article suddenly goes viral, the CDN absorbs the surge instead of the origin.
- Software and games: large downloads and updates come from nearby servers, so they finish faster.
- APIs and mobile apps: public API responses can be cached for a few seconds to cut load.
Well-known providers include Cloudflare, Amazon CloudFront, Akamai, Fastly, Google Cloud CDN and Azure Front Door.
15. CDN vs Load Balancer vs Web Hosting
These three are often confused, but they do different jobs:
| What it does | Where it sits | |
|---|---|---|
| Web hosting | Runs your site and stores the original files | One location, or a few, that you control |
| Load balancer | Spreads requests across several of your servers so none is overloaded | In front of your servers, usually in one region |
| CDN | Stores and serves copies of content close to users worldwide | Spread across the globe, in front of your whole setup |
They work well together. A typical large site has a CDN in front, a load balancer behind it, and several application servers behind that. A CDN does not replace hosting, because something still has to produce the original content.
16. How to Set Up a CDN
- Pick a provider with good coverage where your visitors live, and check pricing for your expected traffic.
- Connect your domain, either by changing your DNS records or by pointing a subdomain such as
cdn.example.comat the CDN. - Turn on HTTPS.
- Set caching rules, and make sure your origin sends sensible
Cache-Controlheaders. - Protect your origin so it only accepts traffic from the CDN.
- Test a few pages and inspect the response headers to confirm files come from the cache.
- Watch the analytics for a week or two, then tune your cache times and rules.
To check a file, look at the response headers in your browser's developer tools or with curl -I https://example.com/logo.png. Headers such as cf-cache-status: HIT on Cloudflare or x-cache: Hit from cloudfront on CloudFront show the file came from the cache.
17. Do You Actually Need a CDN?
Probably yes if your visitors come from several regions, your pages contain many images or videos, you expect traffic spikes, or you want extra protection against attacks. Free plans mean even a small blog can benefit.
The gain is smaller if your audience lives in one city right next to your server and your site is tiny. Even then, the free HTTPS and security features can be worth having.
18. Common Mistakes to Avoid
| Mistake | What goes wrong | Better approach |
|---|---|---|
| Caching pages that should not be shared | One user's account page could be shown to another | Send private or no-store for anything personal |
| Ignoring cookies | Many CDNs skip caching requests with cookies, quietly lowering the hit ratio | Serve static files from a cookie-free path or domain |
| Leaving the origin exposed | Attackers who learn its IP address can bypass the CDN | Allow only the CDN's addresses to reach the origin |
| TTLs that are far too short | Files that rarely change keep hitting the origin | Use long TTLs with versioned file names |
| Changing query strings on every request | Every URL looks new, so nothing is reused | Keep URLs stable, or configure which query strings matter |
| Never checking that caching works | You pay for a CDN that rarely serves from cache | Check response headers and the hit ratio regularly |
19. Best Practices
- Version static files and cache them for a long time, ideally with
immutable. - Use short TTLs or
no-cachefor HTML, so content updates appear quickly. - Mark personal responses
privateorno-store, and double-check every page that shows user data. - Send
ETagorLast-Modifiedheaders so expired files can be revalidated cheaply. - Enable compression and modern image formats to reduce the amount of data sent.
- Lock down the origin and turn on the CDN's DDoS protection and WAF.
- Automate purges in your deployment pipeline for the few files that are not versioned.
- Monitor the hit ratio, errors and latency by region, and act on drops.
20. Summary
- A CDN is a network of servers worldwide that stores copies of your content and serves each visitor from a nearby location.
- It makes pages faster, reduces load and bandwidth on your origin, handles traffic spikes and adds security.
- Edge servers answer cache hits directly and fetch from the origin only on a cache miss; the hit ratio shows how well this works.
- Your server controls caching with
Cache-Controlheaders such aspublic,private,no-store,max-ageands-maxage. - Keep content fresh with versioned file names, short TTLs for HTML and purges when needed.
- Pull CDNs fill their caches automatically; push CDNs are loaded in advance.
- In Spring Boot, set cache headers with properties for static files and the
CacheControlbuilder for APIs, and purge through your provider's API. - A CDN works alongside hosting and load balancers; it does not replace them.
Used well, a CDN is one of the simplest ways to make a website faster, cheaper to run and more reliable for visitors everywhere. Open the FAQ tab for answers to common questions about CDNs.
Frequently Asked Questions (FAQ)
Q1. What is a CDN in simple words?
A CDN (Content Delivery Network) is a group of servers around the world that keep copies of your website's files and deliver them to each visitor from the nearest server.
Instead of everyone fetching everything from your one main server, most people get files from a server close to them, so pages load faster and your main server has much less work.
Q2. How does a CDN make a website faster?
It speeds things up in several ways:
- Shorter distance: files travel from a nearby edge server instead of a distant origin.
- Fewer trips to the origin: cached files are answered instantly.
- Faster connections: HTTPS is set up close to the visitor, and modern protocols like HTTP/2 and HTTP/3 are used.
- Smaller files: compression and image optimisation reduce the data sent.
Q3. What is an edge server and a Point of Presence (PoP)?
An edge server is a CDN server placed close to users, at the "edge" of the network. It stores cached copies of your files and answers requests directly.
A Point of Presence (PoP) is the physical location, usually a data centre, where a group of edge servers lives. Large CDNs operate hundreds of PoPs worldwide.
Q4. What is the origin server?
The origin server is your own server, where the original files and application live. The CDN fetches content from it whenever an edge server does not have a valid cached copy.
With good caching, the origin handles only a small fraction of all requests.
Q5. What is the difference between a cache hit and a cache miss?
- Cache hit: the edge server already has the file and sends it immediately.
- Cache miss: the edge server does not have it, so it fetches the file from the origin, sends it and keeps a copy.
The cache hit ratio is the share of requests that are hits. For static files, 90% or more is a healthy target.
Q6. What is TTL in a CDN?
TTL (time to live) is how long a CDN may reuse a cached file before checking the origin for a fresh version. It is usually set with the Cache-Control header, for example:
Cache-Control: public, max-age=86400
This means the file can be reused for 86,400 seconds, which is 24 hours.
Q7. What is the difference between max-age and s-maxage?
max-age applies to every cache, including the browser and the CDN. s-maxage applies only to shared caches such as CDNs and overrides max-age there.
For example, max-age=60, s-maxage=600 lets browsers keep a file for one minute while the CDN keeps it for ten minutes, so you can purge the CDN and update content quickly.
Q8. How do I clear or purge the CDN cache?
Every major CDN lets you purge (invalidate) cached content through its dashboard or API. You can usually remove a single file, a folder or everything.
To avoid manual purges, many developers add a version or hash to file names, such as app.4f2a9c.js. A changed file gets a new name, so visitors receive it straight away.
Q9. Why do I still see old content after updating my site?
An old copy is still cached, either on the CDN or in your browser. To fix it now:
- Purge the changed files on the CDN.
- Do a hard refresh in your browser.
To prevent it in future, use a short TTL or no-cache for HTML pages and versioned names for CSS and JavaScript files.
Q10. Can a CDN cache dynamic content?
Not fully, because pages like a shopping cart or account dashboard are different for every user. A CDN still helps dynamic content by:
- Using fast, already-open connections to your origin.
- Handling HTTPS close to the visitor.
- Compressing responses.
- Caching public API responses for a few seconds.
Edge computing features can also personalise some responses without going back to your server.
Q11. What is the difference between a pull CDN and a push CDN?
A pull CDN fetches files from your origin automatically the first time someone requests them. A push CDN requires you to upload files to the CDN in advance.
Pull CDNs are simpler and suit almost every website. Push CDNs suit large files that rarely change, such as software installers or video libraries.
Q12. Is a CDN the same as web hosting?
No. Web hosting is where your website actually runs and where content is created. A CDN only stores and delivers copies of that content.
You still need hosting; the CDN sits in front of it to make delivery faster and safer.
Q13. What is the difference between a CDN and a load balancer?
A load balancer spreads requests across several of your own servers, usually within one region, so none is overloaded. A CDN serves copies of content from servers around the world, close to users.
Large sites usually use both: the CDN in front and a load balancer behind it. See Load Balancing for more.
Q14. Does a CDN protect against DDoS attacks?
It helps a lot. A CDN spreads attack traffic across its huge global network, so floods that would crush a single server are absorbed. Many CDNs also offer a web application firewall and bot filtering.
It is not a complete shield on its own: if attackers learn your origin server's IP address they can bypass the CDN, so configure the origin to accept traffic only from the CDN.
Q15. Does using a CDN affect SEO?
Usually in a good way. Search engines consider page speed and user experience, and a CDN makes pages faster and more reliable for visitors everywhere. Free HTTPS from a CDN also helps.
Make sure the CDN serves the same content as your origin and that canonical tags point to your main domain, so search engines do not see duplicate copies.
Q16. Is a CDN free?
Some providers offer free plans; Cloudflare is a well-known example. Others, such as Amazon CloudFront and Google Cloud CDN, charge mainly for the data delivered, often with a free allowance.
Paid plans add features like advanced security, image optimisation and support. Pricing changes over time, so check each provider's current plans.
Q17. Can a CDN reduce my hosting costs?
Often, yes. Cached files are served by the CDN, so your origin uses far less bandwidth and CPU. For sites heavy with images or video, the saving can be significant.
It also means you may not need a bigger server just to survive busy periods, because the CDN absorbs most of the extra traffic.
Q18. How can I tell if a website is using a CDN?
Look at the response headers in your browser's developer tools (Network tab) or run curl -I on a file. Common signs include:
cf-cache-statusandserver: cloudflarefor Cloudflare.x-cache: Hit from cloudfrontandviaheaders for Amazon CloudFront.x-served-byorageheaders for many other CDNs.
Q19. How do I set cache headers in a Spring Boot application?
For static files, use properties such as spring.web.resources.cache.cachecontrol.max-age=365d together with content versioning (spring.web.resources.chain.strategy.content.enabled=true).
For controllers, return a ResponseEntity with Spring's CacheControl builder, for example CacheControl.maxAge(Duration.ofMinutes(5)).cachePublic() for public data and CacheControl.noStore() for personal data.
Q20. Does a small website need a CDN?
It is not essential, but it usually helps. A CDN is worth it if:
- Your visitors come from different countries.
- Your pages use many images or videos.
- You want free HTTPS and protection against attacks.
If everyone visits from one city near your server and the site is tiny, the speed gain will be modest, though the security features can still be worthwhile.