Skip to content

CDN Caching: Content Delivery Networks and Edge Caching

DodaTech Updated 2026-06-28 4 min read

In this tutorial, you will learn about CDN Caching: Content Delivery Networks and Edge Caching. We cover key concepts, practical examples, and best practices to help you master this topic.

A Content Delivery Network (CDN) caches responses across geographically distributed edge servers. When a user requests content, the CDN serves it from the nearest edge location, dramatically reducing latency and offloading traffic from the origin server.

flowchart TB
    User1[User - US East] --> CDN1[US East Edge]
    User2[User - Europe] --> CDN2[Europe Edge]
    User3[User - Asia] --> CDN3[Asia Edge]
    CDN1 --> Origin[Origin Server]
    CDN2 --> Origin
    CDN3 --> Origin
    CDN1 -.->|Cache Miss| Origin
    CDN1 -.->|Cache Hit| Cache

What You'll Learn

  • How CDNs cache and serve content from edge locations
  • Cache key design: query parameters, cookies, headers, and Vary
  • Purging and invalidating CDN caches
  • Origin shielding and cache hierarchies

Why It Matters

A CDN can serve cached content in 10-50ms versus 100-500ms from a single origin. It also absorbs DDoS attacks by distributing traffic across thousands of edge nodes and reduces bandwidth costs at the origin.

Real-World Use

A global e-learning platform uses CloudFront to cache course thumbnails, video metadata, and API responses. Cache hit rate exceeds 95%, allowing a single small origin server to serve 10 million daily users across 6 continents.

CDN Cache Key Design

Normalizing Cache Keys in Express

const url = require('url');

app.use((req, res, next) => {
  const parsed = url.parse(req.url, true);
  const normalizedParams = Object.keys(parsed.query).sort().map(k => `${k}=${parsed.query[k]}`).join('&');
  res.set('X-CDN-Key', `${req.method}:${parsed.pathname}?${normalizedParams}`);
  res.set('Cache-Control', 'public, max-age=300');
  next();
});

Expected output:

CDN uses the normalized URL as cache key, so ?a=1&b=2 and ?b=2&a=1 map to the same cache entry.

Vary Header for Multi-Version Caching

app.get('/api/content', (req, res) => {
  const locale = req.headers['accept-language']?.split(',')[0]?.split('-')[0] || 'en';
  const content = getLocalizedContent(locale);

  res.set('Vary', 'Accept-Language');
  res.set('Cache-Control', 'public, max-age=3600');
  res.json(content);
});

Expected output:

CDN caches separate copies for each Accept-Language value. Spanish users get Spanish content, French users get French.

CDN Purge Request Handling

app.post('/api/purge', async (req, res) => {
  const { url } = req.body;
  const apiToken = req.headers['x-api-key'];

  if (apiToken !== process.env.CDN_API_TOKEN) {
    return res.status(403).json({ error: 'Unauthorized' });
  }

  try {
    await cloudfront.createInvalidation({
      DistributionId: process.env.CLOUDFRONT_DIST_ID,
      InvalidationBatch: {
        Paths: { Quantity: 1, Items: [url] },
        CallerReference: Date.now().toString()
      }
    }).promise();

    res.json({ success: true, invalidated: url });
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

Expected output:

POST /api/purge with valid API key triggers CDN invalidation for that path. Subsequent requests miss cache and fetch from origin.

Common Mistakes

  • Caching authenticated content at the CDN without varying by Authorization header, leaking user data between sessions.
  • Using a single distribution for both static assets and dynamic API responses with different caching needs.
  • Not purging CDN cache after content updates, serving stale data for hours or days.
  • Ignoring query parameter order in cache keys — ?id=1&type=2 and ?type=2&id=1 should map to the same cache entry.
  • Forgetting to enable origin shielding, causing every edge miss to hit the origin simultaneously (cache stampede at scale).

Practice Questions

  1. How does a CDN edge location reduce latency?
  2. What is the difference between a CDN cache hit and a cache miss?
  3. Why is cache key normalization important for CDNs?
  4. How does origin shielding prevent cache stampedes?
  5. What is the cost trade-off between purging individual URLs and wildcard /* purges?

Challenge

Design a CDN caching Strategy for an e-commerce site. Product pages should be cached for 1 hour, cart pages never cached, and API search results cached for 5 minutes. Implement origin shielding and a purge endpoint that accepts product IDs and invalidates related paths.

FAQ

What is the difference between a CDN and a reverse proxy?

A CDN is a geographically distributed network of reverse proxy servers at edge locations. A reverse proxy is typically a single server or cluster in one datacenter.

How do CDNs handle SSL/TLS?

CDNs terminate SSL at the edge and re-encrypt to the origin. This allows them to inspect and cache HTTPS traffic. You install your SSL certificate on the CDN.

What is origin shielding?

Origin shielding routes all edge misses for a region through a single intermediate cache before hitting the origin. This collapses many misses into one request, preventing a stampede.

How do I purge the CDN cache when content changes?

Use the CDN provider's API to create an invalidation or purge request for specific paths. Some CDNs support instant purge; others take minutes to propagate.

Can CDNs cache POST responses?

Most CDNs cache only GET responses by default. Some support caching POST responses if explicitly configured, using the request body as part of the cache key.

Mini Project

Set up a local simulation: use Nginx as a reverse proxy cache to simulate CDN behavior. Create three origin endpoints with different cache policies. Implement a purge endpoint. Write a load test showing the difference in latency and origin load between cached and uncached responses.

What's Next

Continue with Redis Cache to master Redis-based caching with advanced data structures and cluster configurations.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro