Edge Caching Without Stale CMS Edits

Real-time server throughput metrics during peak traffic
Real-time server throughput metrics during peak traffic (Photo via Unsplash)

Every publishing team hits the same ugly afternoon eventually. An editor spots a wrong dollar figure in a headline, fixes the typo, clicks Publish, and opens the article in a private window. Nothing changes. Five minutes later Slack lights up. Someone appends ?refresh=1 to the URL, which fixes their laptop and helps nobody else. Twenty minutes after that, the corrected headline finally appears, well after the social traffic has already peaked.

This isn't a deep mystery of distributed caching. It happens when someone puts a content delivery network in front of a dynamic CMS, sets a flat twenty-minute TTL on HTML to shield the origin, and treats invalidation as an afterthought. Dropping the TTL to 30 seconds doesn't solve it either; you just hammer the origin every half-minute and still look sluggish to editors. Watching your cache hit ratio sink from 98% to 60% puts immediate read pressure on the database tier, something we saw firsthand when comparing PostgreSQL and MariaDB for modern CMS workloads.

Wiring the Publish button to a full-zone "Purge Everything" call is even worse. Evicting 80,000 cached pages over a fixed comma sends a thundering herd straight into PHP-FPM or Node. The real fix separates freshness from expiration: keep long edge TTLs measured in hours or days, and pair them with sub-second targeted invalidation whenever content changes.

Why URL-Based Purging Breaks Down in Real CMS Layouts

Most engineers start by purging the canonical URL on save. That holds up for about a week, right up until an editor asks why the article shows the new headline while the homepage and tag archive still serve the typo.

In any active publication, one CMS record fans out across a web of routes. Editing post #4821 typically touches:

  • The canonical article path (/2026/11/edge-caching-guide)
  • The homepage hero and latest-posts block at /
  • Category and tag archives, plus paginated views like /tag/caching/page/2
  • The author page at /author/owen-gallagher
  • Feeds like /rss.xml and /feed.json, plus related-posts widgets on other articles

Maintaining that URL list inside CMS code turns brittle fast. Add one sidebar module or change pagination from 12 to 15 items per page, and your purge map drifts out of sync. Teams building out enterprise publishing performance architecture hit this dependency wall as soon as editorial volume grows. Stop teaching the CMS to guess which URLs rendered a record; let every HTTP response declare what it depends on instead.

Surrogate Keys: Tagging Responses by Content Graph

Surrogate keys (Surrogate-Key on Fastly, Cache-Tag on Cloudflare, and xkey in self-hosted Varnish) attach a space-separated list of logical IDs to each cacheable response. When your CMS renders HTML, it already knows which post IDs, author IDs, and taxonomy slugs it queried. Emitting those IDs in a response header costs almost nothing:

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
Cache-Control: public, max-age=30, s-maxage=86400, stale-while-revalidate=300, stale-if-error=86400
Surrogate-Key: post-4821 author-17 cat-caching nav-global
ETag: "8f3c2a19b04d"
Vary: Accept-Encoding

Your homepage might emit list-home post-4821 post-4819 nav-global. When an editor updates post 4821, your purge worker doesn't compute a single URL. It invalidates the key post-4821, and the edge walks its inverted index to evict every tagged URL (article, homepage, feed, and category view) in one shot.

Two Surrogate-Key Limits Worth Respecting

First, watch header size caps. NGINX defaults to 4 KB or 8 KB proxy buffers, and most CDNs reject header lines past 16 KB. Dumping 200 individual post IDs into an archive page's Surrogate-Key header will eventually trigger a 502 Bad Gateway. On dense listing pages, tag by coarse collection keys like cat-caching or list-archive instead.

Second, always strip Surrogate-Key at the edge before forwarding responses to browsers. Readers don't need internal database IDs or taxonomy hints, and stripping it trims wasted bytes. On self-hosted Varnish 7 with vmod_xkey, the speed difference over regex bans is stark. Regex bans accumulate on the ban lurker during heavy edit bursts, whereas xkey.softpurge("post-4821") on a 120,000-object, 8 GB malloc cache clears 20 dependent URLs in under 2 milliseconds while holding hit rates above 97.4%.

Splitting Browser TTLs From Edge TTLs With Stale-While-Revalidate

Even with spotless CDN purges, editors still complain about stale pages when someone sets Cache-Control: public, max-age=1800 across the board. You can purge Varnish or Cloudflare on demand, but you can't reach into an editor's browser disk cache. Getting HTTP Cache-Control headers right means splitting browser freshness from edge storage explicitly:

  • Browser cache (max-age=30 or max-age=0, must-revalidate): force clients to revalidate quickly against the edge, where 304 Not Modified responses return in milliseconds over warm TLS connections.
  • Edge cache (s-maxage=86400): give the CDN or Varnish a 24-hour lifetime because surrogate-key purges drive freshness.
  • Background refresh (stale-while-revalidate=300): after expiration or a soft purge, the edge serves the stale copy immediately to the next visitor while kicking off one collapsed background fetch to the origin.
  • Outage shield (stale-if-error=86400): if the CMS throws a 502 or 503 during a bad deploy, the edge serves the last good copy for up to 24 hours instead of an error screen.

Watch out for the soft-purge reload trap: if an editor clicks Publish, waits two seconds, and reloads the live URL, stale-while-revalidate serves the old page on that first request while refreshing in the background. From their chair, the purge looks broken.

Two tweaks prevent that confusion. Use a hard purge for the canonical post key (post-4821) and a soft purge for shared high-traffic views like list-home and cat-caching. The single article refreshes synchronously in roughly 120 ms, while busy listing pages never spike origin load. In parallel, bypass cache for requests carrying a signed editor session cookie and strip every other cookie before lookup.

vcl 4.1;
import xkey;

acl purge_emitters {
    "127.0.0.1";
    "10.24.0.14";
}

sub vcl_recv {
    if (req.method == "PURGE") {
        if (!client.ip ~ purge_emitters) {
            return (synth(405, "Method not allowed"));
        }
        if (req.http.X-Purge-Mode == "hard") {
            set req.http.X-Purged = xkey.purge(req.http.X-Surrogate-Key);
        } else {
            set req.http.X-Purged = xkey.softpurge(req.http.X-Surrogate-Key);
        }
        return (synth(200, "Purged " + req.http.X-Purged + " objects"));
    }

    if (req.http.Cookie ~ "cms_editor_session=") {
        return (pass);
    }

    unset req.http.Cookie;
}

sub vcl_deliver {
    unset resp.http.xkey;
    unset resp.http.Surrogate-Key;
}

Dropping req.http.Cookie for anonymous visitors looks aggressive, and it should be. Stray _ga analytics cookies and consent flags quietly destroy hit ratios when they leak into cache keys. Stick to Vary: Accept-Encoding and avoid varying on Cookie or User-Agent.

Targeted Webhook Purges Without Origin Meltdowns

Never fire synchronous CDN purge calls inside your CMS save controller. If the edge API stalls for four seconds or returns 429 Too Many Requests, the editor's browser hangs and your database transaction holds row locks waiting on external network I/O.

Run invalidation through an asynchronous outbox instead:

  1. Inside the save transaction, write the affected keys (post-4821, cat-caching, list-home) into a small cache_purge_queue table.
  2. Have a worker listen via PostgreSQL LISTEN/NOTIFY and coalesce pending keys over a 1,500-millisecond debounce window.
  3. Deduplicate the batch and send one compact request to the CDN API or Varnish socket, with exponential backoff and a dead-letter alert after five retries.

That 1.5-second debounce pays off immediately when an editor bulk-edits 40 posts or a cron job publishes a morning batch. Instead of 40 redundant purges against list-home, the worker sends one merged call. Edits appear live in under three seconds while API usage stays tiny. Verify the live headers directly after a publish:

$ curl -sI https://example.org/2026/11/edge-caching-guide
HTTP/2 200
content-type: text/html; charset=utf-8
cache-control: public, max-age=30, s-maxage=86400, stale-while-revalidate=300, stale-if-error=86400
etag: "8f3c2a19b04d"
age: 2
x-cache: HIT

Treat the purge path as privileged infrastructure. Lock Varnish PURGE requests to private subnets or WireGuard peers, sign webhook payloads with HMAC-SHA256, and scope CDN tokens strictly to cache invalidation. An exposed purge endpoint hands anyone on the internet a cheap origin-DoS switch, a control-plane exposure we lock down in our guide to hardening self-hosted Linux CMS nodes.

Failure Modes Caching Will Not Mask

Long edge TTLs hide two sharp failure modes. First, expired CDN API tokens fail quietly: pages stay fast for 24 hours until editors notice nothing updates on Monday morning. Alert whenever purge queue lag crosses 30 seconds.

Second, webhook purges faithfully replicate data corruption. If a bad migration blanks out 300 posts and fires model hooks, your worker evicts every healthy page within seconds, and stale-if-error won't save you from HTTP 200 empty HTML. Put a circuit breaker in the purge worker to pause batches exceeding 50 distinct post keys in ten seconds, and keep tested automated offsite backups and recovery drills ready for real rollbacks.

Five Checks Before You Raise Edge TTLs

Before raising s-maxage to 24 hours in production, verify these five behaviors on staging:

  • Split TTLs cleanly: keep browser max-age at 60 seconds or below while s-maxage holds the 24-hour edge lifetime.
  • Confirm header stripping: check that Surrogate-Key arrives from origin and never leaks to public clients.
  • Test real editorial saves: edit a headline, wait three seconds, and check both an editor session and an unauthenticated curl request.
  • Simulate a 503 outage: stop the CMS app briefly and verify stale-if-error serves cached HTML cleanly.
  • Trigger the queue alert: revoke a staging purge token to prove dead-letter alerts fire within a minute.

Get those five pieces wired right, and editors stop trading query-string hacks in Slack, origin CPU stays boring during traffic spikes, and Publish finally means published.

Comments

Popular posts from this blog

PostgreSQL vs MariaDB for Modern CMS

Hardening Self Hosted Linux CMS Nodes