00:00

What Is a CDN and How Does It Work?

Last updated:

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.

A website without a CDN compared with a website using a CDN On the left, without a CDN, users in Europe, Asia and America all send long-distance requests to one origin server. On the right, with a CDN, each user is served by a nearby edge server, and only the edge servers occasionally fetch files from the origin server. WITHOUT A CDN WITH A CDN Originone server User · Europe User · Asia User · America every request travels far and hits the same server Originrarely contacted Edge serverEurope Edge serverAsia Edge serverAmerica users nearby users nearby users nearby short trips for users · origin fetched only on a cache miss
Figure 1: Without a CDN, every visitor travels to one distant server. With a CDN, visitors are served by a nearby edge server, which only contacts the origin when it does not have a file yet.

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

ComponentWhat it does
Origin serverYour real server, where the original files and application live.
Edge serversThe 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.
CacheThe storage on each edge server that holds copies of your files.
Routing systemDecides which edge server each visitor should use, through DNS or anycast.
Control panel and APIWhere 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:

  1. 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.
  2. The edge server checks whether it already has that photo in its cache.
  3. If it does, this is a cache hit: the photo is sent immediately, and your origin is not involved at all.
  4. 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.
  5. The next visitor in that region gets the stored copy, so only the very first request makes the long trip.
Cache miss and cache hit at an edge server Top row, cache miss: the first user asks the edge server for a file, the edge server does not have it, fetches it from the origin, returns it to the user and keeps a copy. Bottom row, cache hit: the next user asks for the same file and the edge server returns its stored copy immediately without contacting the origin. First visitor: cache miss User 1 Edge serverfile not in cache Origin 1. request 2. fetch file 3. file + cache rules 4. response (copy kept) Next visitor nearby: cache hit User 2 Edge serverfile in cache Originnot contacted 1. request 2. instant response from cache
Figure 2: Only the first request for a file in a region travels to the origin. Every later request in that region is a fast cache hit.

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 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:

HTTP response header
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:

DirectiveMeaningTypical use
publicAny cache, including the CDN, may store the responseImages, CSS, JavaScript, public pages
privateOnly the user's browser may store it, not the CDNPages personalised for one user
no-storeDo not store the response anywhereAccount pages, payment details
no-cacheMay be stored, but must be checked with the origin before each reuseHTML pages that change often
max-age=NReuse for N secondsControls the browser and CDN TTL
s-maxage=NReuse for N seconds in shared caches such as CDNs onlyCache longer on the CDN than in browsers
stale-while-revalidate=NServe the old copy for up to N seconds while fetching a new one in the backgroundKeeping pages fast while content refreshes
immutableThe file will never change at this URLVersioned 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.js or style.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

AspectPull CDNPush CDN
How files arriveThe CDN fetches them from your origin the first time someone asksYou upload them to the CDN yourself
Setup effortLow, mostly automaticHigher, you manage what is stored
First requestSlightly slower (a cache miss)Fast, files are already there
Good forAlmost every website and appLarge 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:

application.properties
# 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:

ProductController.java
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:

AssetUrlBuilder.java
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:

CdnCachePurger.java
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 doesWhere it sits
Web hostingRuns your site and stores the original filesOne location, or a few, that you control
Load balancerSpreads requests across several of your servers so none is overloadedIn front of your servers, usually in one region
CDNStores and serves copies of content close to users worldwideSpread 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

  1. Pick a provider with good coverage where your visitors live, and check pricing for your expected traffic.
  2. Connect your domain, either by changing your DNS records or by pointing a subdomain such as cdn.example.com at the CDN.
  3. Turn on HTTPS.
  4. Set caching rules, and make sure your origin sends sensible Cache-Control headers.
  5. Protect your origin so it only accepts traffic from the CDN.
  6. Test a few pages and inspect the response headers to confirm files come from the cache.
  7. 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

MistakeWhat goes wrongBetter approach
Caching pages that should not be sharedOne user's account page could be shown to anotherSend private or no-store for anything personal
Ignoring cookiesMany CDNs skip caching requests with cookies, quietly lowering the hit ratioServe static files from a cookie-free path or domain
Leaving the origin exposedAttackers who learn its IP address can bypass the CDNAllow only the CDN's addresses to reach the origin
TTLs that are far too shortFiles that rarely change keep hitting the originUse long TTLs with versioned file names
Changing query strings on every requestEvery URL looks new, so nothing is reusedKeep URLs stable, or configure which query strings matter
Never checking that caching worksYou pay for a CDN that rarely serves from cacheCheck 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-cache for HTML, so content updates appear quickly.
  • Mark personal responses private or no-store, and double-check every page that shows user data.
  • Send ETag or Last-Modified headers 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-Control headers such as public, private, no-store, max-age and s-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 CacheControl builder 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.