CDN Performance Optimization: The Complete Guide to Faster Global Delivery

Optimize CDN performance with caching strategies, edge computing, image optimization, and multi-CDN architectures for faster global content delivery.

E
ECOSIRE Research and Development Team
|March 16, 20267 min read1.6k Words|

Part of our Performance & Scalability series

Read the complete guide

CDN Performance Optimization: The Complete Guide to Faster Global Delivery

Every 100ms of latency improvement increases eCommerce conversion rates by 1.1%. For a store doing $1 million per month, that 100ms improvement translates to $132,000 per year in additional revenue. CDN optimization is not a technical nice-to-have --- it is a direct revenue lever.

This guide covers CDN architecture, caching strategies, edge computing, and performance tuning for web applications, eCommerce stores, and ERP systems.

Key Takeaways

  • Proper cache headers alone can reduce origin server load by 60-80%
  • Image optimization through CDN transforms reduces page weight by 40-60% with zero code changes
  • Edge computing moves API logic closer to users, cutting latency from 200ms to 20ms for cached responses
  • Multi-CDN strategies provide failover and geographic optimization for global audiences

CDN Architecture Fundamentals

How CDNs Work

A CDN is a network of servers distributed globally that cache and serve content from locations closest to the user.

User in Tokyo --> CDN Edge (Tokyo, 5ms) --> [Cache HIT] --> Response
User in London --> CDN Edge (London, 5ms) --> [Cache MISS] --> Origin (US-East, +120ms) --> Cache + Response
User in London --> CDN Edge (London, 5ms) --> [Cache HIT] --> Response (subsequent requests)

What to Cache

Content TypeCache DurationCache-Control Header
Static assets (JS, CSS)1 year (immutable)public, max-age=31536000, immutable
Images30 dayspublic, max-age=2592000
Fonts1 yearpublic, max-age=31536000, immutable
HTML pages (static)5 minutespublic, max-age=300, s-maxage=3600
API responses (public)1-5 minutespublic, max-age=60, s-maxage=300
API responses (private)Do not cacheprivate, no-store

Cache Control Headers

Next.js Cache Configuration

// next.config.ts
const nextConfig = {
  async headers() {
    return [
      {
        source: '/_next/static/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=31536000, immutable',
          },
        ],
      },
      {
        source: '/images/:path*',
        headers: [
          {
            key: 'Cache-Control',
            value: 'public, max-age=2592000',
          },
        ],
      },
    ];
  },
};

Nginx Cache Headers

location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff2)$ {
    expires 365d;
    add_header Cache-Control "public, immutable";
    add_header Vary "Accept-Encoding";
}

location ~* \.html$ {
    expires 5m;
    add_header Cache-Control "public, must-revalidate";
}

# API responses - let the application control caching
location /api/ {
    proxy_pass http://backend;
    proxy_cache_bypass $http_authorization;
}

Image Optimization

Images account for 50-70% of page weight on most websites. CDN-based image optimization eliminates the need for build-time image processing.

Cloudflare Image Transformations

<!-- Original: 2.4 MB JPEG -->
<!-- Optimized: 180 KB WebP, properly sized -->
<img
  src="/cdn-cgi/image/width=800,quality=80,format=auto/images/product-hero.jpg"
  alt="Product"
  width="800"
  height="600"
  loading="lazy"
/>

Next.js Image Component with CDN

// next.config.ts
const nextConfig = {
  images: {
    loader: 'custom',
    loaderFile: './lib/image-loader.ts',
  },
};

// lib/image-loader.ts
export default function cloudflareLoader({
  src,
  width,
  quality,
}: {
  src: string;
  width: number;
  quality?: number;
}) {
  const params = [`width=${width}`, `quality=${quality || 80}`, 'format=auto'];
  return `/cdn-cgi/image/${params.join(',')}${src}`;
}

Image Optimization Impact

MetricBefore CDN OptimizationAfter CDN Optimization
Average image size850 KB120 KB
Page weight (images)4.2 MB680 KB
LCP (Largest Contentful Paint)3.8s1.4s
Total page load time5.2s2.1s

Edge Computing

Cloudflare Workers for API Caching

// worker.js - Cache API responses at the edge
addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

async function handleRequest(request) {
  const url = new URL(request.url);

  // Only cache GET requests to public API endpoints
  if (request.method !== 'GET' || !url.pathname.startsWith('/api/public/')) {
    return fetch(request);
  }

  const cache = caches.default;
  const cacheKey = new Request(url.toString(), request);

  // Check cache
  let response = await cache.match(cacheKey);
  if (response) {
    return response;
  }

  // Fetch from origin
  response = await fetch(request);

  // Clone and cache successful responses
  if (response.ok) {
    const cachedResponse = new Response(response.body, response);
    cachedResponse.headers.set('Cache-Control', 'public, max-age=300');
    cachedResponse.headers.set('X-Cache-Status', 'MISS');
    event.waitUntil(cache.put(cacheKey, cachedResponse.clone()));
    return cachedResponse;
  }

  return response;
}

Edge Use Cases for eCommerce

Use CaseLatency ImprovementImplementation
Product catalog API200ms to 5msCache at edge for 5 minutes
Geolocation redirect100ms to 1msEdge worker with IP lookup
A/B testing50ms to 0msEdge worker assigns variant
Bot detection100ms to 5msEdge challenge before origin
Price localization150ms to 5msEdge worker with currency conversion

CDN Provider Comparison

FeatureCloudflareAWS CloudFrontFastlyBunny CDN
Global PoPs310+450+80+114+
Free tierGenerous1 TB/month (12 months)NoneNone
Edge computeWorkersLambda@EdgeCompute@EdgeEdge Scripting
Image optimizationBuilt-inRequires LambdaBuilt-inBuilt-in
WebSocket supportYesYesYesYes
DDoS protectionIncludedAWS Shield (extra)IncludedBasic
Starting priceFreePay-per-use$50/month$1/month

Recommendation: Cloudflare for most businesses. The free tier is generous, the edge network is the largest, and Workers provide powerful edge computing without additional infrastructure.


Multi-CDN Strategies

Why Multi-CDN

No single CDN has the best performance in every region. A multi-CDN strategy routes users to the best-performing CDN for their location:

ApproachComplexityCostBenefit
Primary + failoverLow1.1xReliability
Geographic routingMedium1.3xLatency optimization
Performance-based routingHigh1.5xBest possible latency

Implementation

Use DNS-level routing to direct users to the optimal CDN:

User request -> DNS (Cloudflare/Route53)
    |
    +--> US/EU traffic -> Cloudflare (best PoP coverage)
    |
    +--> APAC traffic -> AWS CloudFront (strong APAC presence)
    |
    +--> China traffic -> Alibaba CDN (required for China performance)

For most businesses, a single CDN (Cloudflare) with a failover CDN configured at the DNS level provides sufficient redundancy without the complexity of full multi-CDN routing.


Common CDN Pitfalls

Pitfall 1: Caching Authenticated Content

Never cache responses that contain user-specific data. A cached response for User A served to User B is a security breach. Use Cache-Control: private, no-store for all authenticated API responses.

Pitfall 2: Ignoring Cache Busting for Deployments

When you deploy new JavaScript or CSS, users may receive cached old versions. Solutions:

  • Content hashing: Include a hash in the filename (app.a1b2c3d4.js). Next.js does this automatically.
  • Cache purge on deploy: Purge CDN cache as part of your deployment pipeline.
  • Versioned URLs: /v2/styles.css instead of /styles.css.

Pitfall 3: CDN Misconfiguration for Dynamic Content

If your CDN caches dynamic content that should not be cached (API responses, HTML pages with user state), you will serve stale or incorrect data. Audit your CDN cache rules regularly and use Vary headers to prevent caching conflicts.


Performance Measurement

Core Web Vitals Targets

MetricGoodNeeds ImprovementPoor
LCP (Largest Contentful Paint)<2.5s2.5-4.0s>4.0s
INP (Interaction to Next Paint)<200ms200-500ms>500ms
CLS (Cumulative Layout Shift)<0.10.1-0.25>0.25

Monitoring Cache Performance

# Check CDN cache hit ratio
curl -sI https://example.com/page | grep -i "cf-cache-status\|x-cache\|age"

# Expected output for a cached response:
# cf-cache-status: HIT
# age: 3600

Track cache hit ratio over time. Target: above 85% for static assets, above 50% for dynamic content.


Frequently Asked Questions

Do we need a CDN if our users are in one country?

Yes, but the benefits shift. Instead of geographic latency reduction, you gain: DDoS protection, SSL termination offload, image optimization, and origin server load reduction. Even for single-country audiences, a CDN reduces server costs and improves reliability. The Cloudflare free tier makes this a zero-cost improvement.

How do we handle cache invalidation for dynamic content?

Three strategies: (1) short TTLs (1-5 minutes) for content that changes frequently, (2) cache tags with purge-by-tag for content updates, (3) stale-while-revalidate headers that serve cached content while fetching fresh content in the background. Use s-maxage for CDN cache and max-age for browser cache independently.

Should we use a CDN for our ERP system?

CDN is beneficial for ERP static assets (JavaScript, CSS, images) and public-facing portals. Do not cache authenticated API responses or session-dependent content. ECOSIRE configures CDN caching as part of our Odoo implementation services to ensure optimal caching without security risks.

How does CDN interact with server-side rendering?

For Next.js SSR pages, configure the CDN to cache based on the full URL (including query parameters) with short TTLs (1-5 minutes). Use stale-while-revalidate to serve slightly stale content while Next.js regenerates in the background. ISR (Incremental Static Regeneration) works naturally with CDN caching.


What Comes Next

CDN optimization pairs naturally with load testing to validate performance under load and monitoring to track cache hit ratios and latency. For the full infrastructure optimization roadmap, see our DevOps guide for small businesses.

Contact ECOSIRE for CDN setup and performance optimization consulting.


Published by ECOSIRE -- helping businesses deliver content faster worldwide.

E

Written by

ECOSIRE Research and Development Team

Building enterprise-grade digital products at ECOSIRE. Sharing insights on Odoo integrations, e-commerce automation, and AI-powered business solutions.

Chat on WhatsApp