正在加载,请稍候…

CDN and Edge Caching: Strategies for Global Performance

Leverage CDNs for global performance. Learn cache-control headers, cache invalidation, edge functions, origin shielding, and strategies for static and dynamic content.

CDN and Edge Caching Guide

Cache-Control Headers

// Static assets with content hash (cache forever)
res.setHeader('Cache-Control', 'public, max-age=31536000, immutable');

// HTML pages (short TTL, revalidate)
res.setHeader('Cache-Control', 'public, max-age=0, must-revalidate');

// Personalized API responses
res.setHeader('Cache-Control', 'private, no-store');

// CDN-cacheable API responses
res.setHeader('Cache-Control', 'public, s-maxage=300, max-age=60');
// s-maxage: CDN TTL (5 min), max-age: browser TTL (1 min)

// Serve stale while revalidating in background
res.setHeader('Cache-Control', 'public, max-age=60, stale-while-revalidate=3600');

ETag and Conditional Requests

app.get('/api/products', async (req, res) => {
  const products = await productRepo.findAll();
  const etag = crypto.createHash('md5').update(JSON.stringify(products)).digest('hex');

  res.setHeader('ETag', `"${etag}"`);

  if (req.headers['if-none-match'] === `"${etag}"`) {
    return res.status(304).end(); // Not Modified - saves bandwidth
  }

  res.json(products);
});

Cache Invalidation

# Cloudflare: Purge by URL
curl -X POST "https://api.cloudflare.com/client/v4/zones/${ZONE_ID}/purge_cache"   -H "Authorization: Bearer ${CF_TOKEN}"   --data '{"files": ["https://example.com/api/products"]}'

# Purge by cache tag (targeted invalidation)
curl -X POST "..." --data '{"tags": ["products", "category:electronics"]}'
// Tag responses for targeted invalidation
app.get('/products/:id', async (req, res) => {
  const product = await productRepo.findById(req.params.id);
  res.setHeader('Cache-Tag', `product:${product.id}`);
  res.setHeader('Cache-Control', 'public, s-maxage=3600');
  res.json(product);
});

async function updateProduct(id: string, data: UpdateProductDto): Promise<void> {
  await productRepo.update(id, data);
  await cloudflare.purgeByTag([`product:${id}`]); // Instant invalidation
}

Edge Functions (Cloudflare Workers)

export default {
  async fetch(request: Request, env: Env): Promise<Response> {
    const url = new URL(request.url);
    const country = request.headers.get('CF-IPCountry') || 'US';

    // Geo-routing
    if (country === 'DE') {
      url.hostname = 'eu.api.example.com';
    }

    const response = await fetch(url.toString(), request);
    const headers = new Headers(response.headers);
    headers.set('X-Served-Country', country);
    return new Response(response.body, { headers });
  }
};

Origin Shielding

Without shielding:
  100 CDN edge nodes -> all miss -> 100 requests to origin

With shielding:
  100 CDN edges -> shield node (single miss) -> 1 request to origin
  Reduces origin traffic by 90%+

Aggressive edge caching is the highest-leverage performance optimization for global services.