Edge Caching Implementation for Website Speed

Our company is engaged in the development, support and maintenance of sites of any complexity. From simple one-page sites to large-scale cluster systems built on micro services. Experience of developers is confirmed by certificates from vendors.
Development and maintenance of all types of websites:
Informational websites or web applications
Business card websites, landing pages, corporate websites, online catalogs, quizzes, promo websites, blogs, news resources, informational portals, forums, aggregators
E-commerce websites or web applications
Online stores, B2B portals, marketplaces, online exchanges, cashback websites, exchanges, dropshipping platforms, product parsers
Business process management web applications
CRM systems, ERP systems, corporate portals, production management systems, information parsers
Electronic service websites or web applications
Classified ads platforms, online schools, online cinemas, website builders, portals for electronic services, video hosting platforms, thematic portals

These are just some of the technical types of websites we work with, and each of them can have its own specific features and functionality, as well as be customized to meet the specific needs and goals of the client.

Our competencies:
Development stages
Latest works
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1161
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1041
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    822
  • image_crm_chasseurs_493_0.webp
    CRM development for Chasseurs
    847
  • image_website-sbh_0.png
    Website development for SBH Partners
    999
  • image_website-_0.png
    Website development for Red Pear
    451

Edge Caching and Website Speed

Edge caching is storing content on CDN servers near the user. Instead of requesting from origin in Europe, a user in Asia gets a response from the nearest edge node in 10–30ms instead of 200–300ms.

Cloudflare: Cache Configuration

# Cache Rules via Cloudflare API
curl -X POST "https://api.cloudflare.com/client/v4/zones/{zone_id}/rulesets" \
  -H "Authorization: Bearer {token}" \
  -H "Content-Type: application/json" \
  --data '{
    "name": "Cache Rules",
    "kind": "zone",
    "phase": "http_request_cache_settings",
    "rules": [
      {
        "expression": "(http.request.uri.path matches \"^/api/\")",
        "action": "set_cache_settings",
        "action_parameters": {
          "cache": true,
          "edge_ttl": {
            "mode": "override_origin",
            "default": 60
          },
          "browser_ttl": {
            "mode": "override_origin",
            "default": 0
          }
        },
        "description": "Cache API responses 60s"
      },
      {
        "expression": "(http.request.uri.path matches \"\.(js|css|woff2|png|webp|avif)$\")",
        "action": "set_cache_settings",
        "action_parameters": {
          "cache": true,
          "edge_ttl": {
            "mode": "override_origin",
            "default": 2592000
          },
          "browser_ttl": {
            "mode": "override_origin",
            "default": 31536000
          }
        },
        "description": "Static assets: 30 days edge, 1 year browser"
      }
    ]
  }'

HTTP Cache-Control Headers

Proper headers at origin are the foundation for effective CDN caching:

# Nginx: static resources (with hash in name → forever caching)
location ~* \.(js|css|woff2|ico)$ {
  add_header Cache-Control "public, max-age=31536000, immutable";
  add_header Vary "Accept-Encoding";
  gzip_static on;
}

# Images
location ~* \.(jpg|jpeg|png|webp|avif|svg|gif)$ {
  add_header Cache-Control "public, max-age=2592000";  # 30 days
  add_header Vary "Accept";
}

# HTML: don't cache in browser, but allow CDN
location / {
  add_header Cache-Control "public, max-age=0, s-maxage=300, must-revalidate";
  # s-maxage=300: CDN caches for 5 minutes
  # max-age=0: browser always validates freshness
}

# API endpoints: caching depends on data
location /api/products {
  add_header Cache-Control "public, max-age=60, s-maxage=60";
  add_header Vary "Accept-Language, Accept-Encoding";
}

# Private data — don't cache on CDN
location /api/user {
  add_header Cache-Control "private, no-cache, no-store";
}

Next.js: Cache Management

// App Router: fetch with cache control
async function getProducts() {
  const res = await fetch('https://api.mysite.com/products', {
    next: {
      revalidate: 300, // ISR: update every 5 minutes
      tags: ['products'], // for on-demand revalidation
    },
  });
  return res.json();
}

// On-demand revalidation via webhook (CMS)
// app/api/revalidate/route.ts
export async function POST(request: Request) {
  const { secret, tag } = await request.json();

  if (secret !== process.env.REVALIDATION_SECRET) {
    return Response.json({ error: 'Unauthorized' }, { status: 401 });
  }

  revalidateTag(tag); // Invalidates all cache with this tag
  return Response.json({ revalidated: true });
}

Varnish Cache: Server Cache Before Origin

# /etc/varnish/default.vcl
vcl 4.0;

backend default {
  .host = "127.0.0.1";
  .port = "3000";
  .connect_timeout = 5s;
  .first_byte_timeout = 30s;
}

sub vcl_recv {
  # Don't cache authorized requests
  if (req.http.Authorization || req.http.Cookie ~ "session=") {
    return (pass);
  }

  # URL normalization
  set req.url = regsuball(req.url, "[?&](utm_source|utm_medium|utm_campaign|fbclid)=[^&]*", "");

  # Remove unnecessary cookies for cached pages
  if (req.url ~ "\.(css|js|png|jpg|webp|woff2)(\?.*)?$") {
    unset req.http.Cookie;
  }
}

sub vcl_backend_response {
  # Force TTL for static
  if (bereq.url ~ "\.(css|js|woff2)(\?.*)?$") {
    set beresp.ttl = 30d;
    set beresp.http.Cache-Control = "public, max-age=2592000";
  }

  # TTL for HTML
  if (beresp.http.Content-Type ~ "text/html") {
    set beresp.ttl = 5m;
  }
}

Monitor Cache Hit Rate

# Cloudflare Analytics API
curl "https://api.cloudflare.com/client/v4/zones/{zone_id}/analytics/dashboard" \
  -H "Authorization: Bearer {token}" \
  | jq '.result.totals.cached / .result.totals.requests * 100'

# Nginx: add X-Cache-Status header
add_header X-Cache-Status $upstream_cache_status;

# Check via curl
curl -I https://mysite.com/api/products | grep -i x-cache
# X-Cache-Status: HIT
# X-Cache-Status: MISS
# X-Cache-Status: BYPASS

Target Metrics:

  • Static assets: Cache Hit Rate > 99%
  • HTML pages: > 80%
  • API responses (public): > 70%

Setup Cloudflare caching with Cache Rules and optimal headers — 1–2 working days.