DEV Community

Florient DOGBE
Florient DOGBE

Posted on

CDN and Cache Invalidation: Purging CloudFront Without Taking Down Your Origin

A deploy goes out at 14:03. Someone runs aws cloudfront create-invalidation --paths "/*". At 14:03:30, your origin — three pods behind an OpenShift Route — goes from 40 req/s to 4,000 req/s. Pods OOM, the readiness probe flips, the Service drops endpoints, and CloudFront starts serving 502s to everyone. The invalidation "worked": the cache is empty. That is exactly the problem.

This is a thundering herd, and wildcard invalidation is the single most reliable way to trigger one. This article walks through why it happens, and how to design a cache policy that survives ten deploys a day without ever needing /*.

Context: why a wildcard invalidation is a self-inflicted DDoS

CloudFront is not one cache. It is ~700 points of presence, each with its own local cache, backed by a smaller set of regional edge caches. When you invalidate /*, you simultaneously evict every object from every POP. The next request for each object at each POP is a MISS.

Three multipliers turn that into an outage:

  1. Fan-out across POPs. The same /static/app.js may be fetched by 40+ different POPs within seconds. Without Origin Shield, that is 40 origin requests for one object.
  2. No request collapsing on a cold cache. CloudFront does collapse concurrent requests for the same object at a given POP, but only once the first request is in flight. A burst of 200 simultaneous requests arriving at the same microsecond can still produce more than one origin fetch, and collapsing does not happen across POPs.
  3. Your origin is sized for cache-hit traffic. If your cache hit ratio is 95%, your origin normally sees 5% of edge traffic. Emptying the cache means a 20x instantaneous load multiplier. No HPA reacts in 30 seconds.

Add to that the operational friction: invalidations are asynchronous (seconds to minutes), you get 1,000 free paths per month and pay $0.005 per path after that, and /* counts as a single path but is the most destructive option available.

The goal is to never invalidate for routine deploys. Invalidation should be an incident-response tool, not part of your CI pipeline.

Strategy 1: content-addressed URLs (versioning) — the real fix

If a URL's content never changes, you never need to invalidate it. This is the foundation; everything else is mitigation.

For static assets, let your bundler emit content hashes: app.a3f9c21b.js, main.7d2e.css. The HTML that references them is the only mutable document. Serve assets with a one-year immutable TTL and the HTML with a near-zero TTL.

/index.html                 Cache-Control: no-cache, must-revalidate
/assets/app.a3f9c21b.js     Cache-Control: public, max-age=31536000, immutable
/assets/logo.7d2e.svg       Cache-Control: public, max-age=31536000, immutable
Enter fullscreen mode Exit fullscreen mode

immutable tells the browser not to even send a conditional request on reload. no-cache on the HTML does not mean "don't cache": it means "cache it, but revalidate before each use". Combined with an ETag, the revalidation costs a 304 with no body.

Here is an nginx config shipped as a ConfigMap on OpenShift, serving a SPA build:

apiVersion: v1
kind: ConfigMap
metadata:
  name: web-nginx-conf
  namespace: frontend
data:
  default.conf: |
    server {
      listen 8080;
      root /usr/share/nginx/html;

      # Hashed assets: immutable, one year
      location ~* \.[0-9a-f]{8,}\.(js|css|svg|woff2|png|jpg)$ {
        add_header Cache-Control "public, max-age=31536000, immutable" always;
        try_files $uri =404;
      }

      # Entry document: always revalidate, allow stale on origin trouble
      location = /index.html {
        add_header Cache-Control "no-cache, stale-while-revalidate=30, stale-if-error=86400" always;
        etag on;
      }

      location / {
        try_files $uri /index.html;
      }
    }
Enter fullscreen mode Exit fullscreen mode

And the Deployment, with a non-root UID and a read-only root filesystem — standard for the restricted-v2 SCC:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: web
  namespace: frontend
spec:
  replicas: 3
  selector:
    matchLabels: { app: web }
  template:
    metadata:
      labels: { app: web }
    spec:
      securityContext:
        runAsNonRoot: true
        seccompProfile: { type: RuntimeDefault }
      containers:
        - name: nginx
          image: registry.example.com/frontend/web:2026.02.11-a3f9c21
          ports:
            - containerPort: 8080
          securityContext:
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities: { drop: ["ALL"] }
          volumeMounts:
            - { name: conf,  mountPath: /etc/nginx/conf.d }
            - { name: cache, mountPath: /var/cache/nginx }
            - { name: run,   mountPath: /var/run }
          readinessProbe:
            httpGet: { path: /healthz, port: 8080 }
            periodSeconds: 5
          resources:
            requests: { cpu: 100m, memory: 128Mi }
            limits:   { memory: 256Mi }
      volumes:
        - name: conf
          configMap: { name: web-nginx-conf }
        - name: cache
          emptyDir: {}
        - name: run
          emptyDir: {}
Enter fullscreen mode Exit fullscreen mode

Versioning what you cannot hash

Some paths are inherently stable: /api/v1/catalog, /sitemap.xml. For those, use a cache key prefix you control. Put a build identifier in the origin path and swap it atomically at deploy time:

# Origin path carries the release; changing it changes every cache key at once
aws cloudfront get-distribution-config --id E1A2B3C4D5E6F7 \
  --query 'DistributionConfig' > dist.json

jq '.Origins.Items[0].OriginPath = "/rel-2026-02-11"' dist.json > dist-new.json

ETAG=$(aws cloudfront get-distribution-config --id E1A2B3C4D5E6F7 --query 'ETag' --output text)
aws cloudfront update-distribution \
  --id E1A2B3C4D5E6F7 \
  --if-match "$ETAG" \
  --distribution-config file://dist-new.json
Enter fullscreen mode Exit fullscreen mode

This is effectively a cache-wide swap with zero invalidation cost — but note it has the same thundering-herd profile as /* unless combined with Origin Shield and stale serving. Use it for blue/green asset buckets, not for every commit.

Strategy 2: stale-while-revalidate and stale-if-error

stale-while-revalidate (RFC 5861) is the single highest-leverage header for CDN resilience. It tells the cache: serve the expired object immediately, and refresh it in the background. The user never waits on the origin, and the origin sees exactly one refresh request per POP per TTL window instead of a burst of blocked requests.

Cache-Control: public, max-age=60, stale-while-revalidate=300, stale-if-error=86400
Enter fullscreen mode Exit fullscreen mode

Read that as:

  • 0–60s: fresh, served from cache, no origin contact.
  • 60–360s: stale but served instantly; one background fetch refreshes it.
  • Origin returns 5xx or times out: keep serving the stale copy for up to 24h.

CloudFront honors both directives on cacheable responses. stale-if-error is what turns an origin outage from a customer-visible incident into a graph on your dashboard.

Set this at the origin. Here is a Go/Quarkus-agnostic way to do it in an OpenShift Route when the app does not control its headers — Routes support response header injection:

apiVersion: route.openshift.io/v1
kind: Route
metadata:
  name: web
  namespace: frontend
spec:
  host: origin.example.com
  to:
    kind: Service
    name: web
  port:
    targetPort: 8080
  tls:
    termination: edge
    insecureEdgeTerminationPolicy: Redirect
  httpHeaders:
    actions:
      response:
        - name: Cache-Control
          action:
            type: Set
            set:
              value: "public, max-age=60, stale-while-revalidate=300, stale-if-error=86400"
Enter fullscreen mode Exit fullscreen mode

Header actions on Routes require OpenShift 4.13+. On older clusters, inject headers in the application or in a sidecar proxy.

ETag and conditional revalidation

When CloudFront revalidates, it sends If-None-Match with the stored ETag. If the content has not changed, your origin returns 304 Not Modified with no body. That is a cheap request: no serialization, no bytes on the wire.

This only works if your ETags are stable across replicas. nginx derives ETags from mtime + size, so three pods built from the same image produce the same ETag — good. An application that generates ETags from a per-process random seed or a timestamp will produce a different ETag per pod, and every revalidation becomes a full 200 response. Verify it:

for i in 1 2 3; do
  curl -sI https://origin.example.com/index.html | grep -i '^etag'
done
# etag: "67ab12cd-4f2"
# etag: "67ab12cd-4f2"
# etag: "67ab12cd-4f2"   <-- must be identical
Enter fullscreen mode Exit fullscreen mode

Then confirm the 304 path end to end:

ETAG=$(curl -sI https://origin.example.com/index.html | awk -F': ' '/^[Ee]tag/{print $2}' | tr -d '\r')
curl -s -o /dev/null -w '%{http_code}\n' \
  -H "If-None-Match: $ETAG" https://origin.example.com/index.html
# 304
Enter fullscreen mode Exit fullscreen mode

Strategy 3: Origin Shield

Origin Shield adds a single designated regional cache between all POPs and your origin. Every miss funnels through it, so the fan-out collapses: 40 POPs requesting the same object produce one origin fetch, because Origin Shield also performs request collapsing.

Pick the region closest to your origin. If your OpenShift cluster is in eu-west-1, shield in eu-west-1.

aws cloudfront get-distribution-config --id E1A2B3C4D5E6F7 > current.json
ETAG=$(jq -r '.ETag' current.json)

jq '.DistributionConfig.Origins.Items[0].OriginShield = {
      "Enabled": true,
      "OriginShieldRegion": "eu-west-1"
    } | .DistributionConfig' current.json > shielded.json

aws cloudfront update-distribution \
  --id E1A2B3C4D5E6F7 --if-match "$ETAG" \
  --distribution-config file://shielded.json
Enter fullscreen mode Exit fullscreen mode

Origin Shield costs per request routed through it, but it typically pays for itself in origin compute and egress on any workload with real geographic spread. Combined with stale-while-revalidate, your origin sees a near-constant, predictable request rate regardless of edge traffic.

Strategy 4: surgical invalidation when you really must

Sometimes you ship a bad /index.html or a wrong robots.txt. Invalidate narrowly and rate-limit yourself.

# Good: explicit, short list, no wildcards
aws cloudfront create-invalidation \
  --distribution-id E1A2B3C4D5E6F7 \
  --paths /index.html /manifest.json /robots.txt \
  --query 'Invalidation.Id' --output text
Enter fullscreen mode Exit fullscreen mode

Wait for completion before declaring the rollback done:

INV=$(aws cloudfront create-invalidation \
  --distribution-id E1A2B3C4D5E6F7 --paths /index.html \
  --query 'Invalidation.Id' --output text)

aws cloudfront wait invalidation-completed \
  --distribution-id E1A2B3C4D5E6F7 --id "$INV"
echo "invalidation $INV completed"
Enter fullscreen mode Exit fullscreen mode

If you need a broad purge, stagger it so the origin warms progressively:

#!/usr/bin/env bash
set -euo pipefail
DIST="E1A2B3C4D5E6F7"
PREFIXES=(/api/catalog /api/pricing /api/inventory /api/reviews)

for p in "${PREFIXES[@]}"; do
  echo "purging ${p}/*"
  aws cloudfront create-invalidation --distribution-id "$DIST" --paths "${p}/*" >/dev/null
  sleep 120   # let the origin absorb one wave before the next
done
Enter fullscreen mode Exit fullscreen mode

Before and during any purge, watch the origin from the cluster side:

oc -n frontend get hpa web -w
oc -n frontend top pods --containers
oc -n frontend logs deploy/web --since=2m | grep -c ' 5[0-9][0-9] '
Enter fullscreen mode Exit fullscreen mode

And make sure the origin can actually scale and refuse excess load rather than melting:

apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: web
  namespace: frontend
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: web
  minReplicas: 3
  maxReplicas: 30
  metrics:
    - type: Resource
      resource:
        name: cpu
        target: { type: Utilization, averageUtilization: 60 }
  behavior:
    scaleUp:
      stabilizationWindowSeconds: 0
      policies:
        - { type: Percent, value: 100, periodSeconds: 15 }
    scaleDown:
      stabilizationWindowSeconds: 300
      policies:
        - { type: Percent, value: 20, periodSeconds: 60 }
Enter fullscreen mode Exit fullscreen mode

A PodDisruptionBudget keeps the origin available during node drains that coincide with a cache-cold window:

apiVersion: policy/v1
kind: PodDisruptionBudget
metadata:
  name: web
  namespace: frontend
spec:
  minAvailable: 2
  selector:
    matchLabels: { app: web }
Enter fullscreen mode Exit fullscreen mode

Cache keys: the quiet hit-ratio killer

A perfect TTL policy is useless if every request produces a unique cache key. By default, CloudFront's legacy behavior could forward all query strings and many headers. Use a managed or custom cache policy that includes only what actually changes the response.

# Inspect what the current behavior keys on
aws cloudfront get-cache-policy --id $(
  aws cloudfront get-distribution --id E1A2B3C4D5E6F7 \
    --query 'Distribution.DistributionConfig.DefaultCacheBehavior.CachePolicyId' \
    --output text)
Enter fullscreen mode Exit fullscreen mode

Rules of thumb:

  • Marketing params (utm_*, fbclid, gclid) must never be in the cache key. Strip them with a CloudFront Function.
  • Accept-Encoding should be handled by CloudFront's native compression settings, not by a raw header in the key.
  • Cookie in the cache key means "no caching" in practice. If a page is personalized, split it: cached shell + uncached fragment fetched client-side.
  • Use an origin request policy to forward headers your app needs (e.g. Accept-Language) without adding them to the cache key, when they do not change the response.

A CloudFront Function to normalize query strings:

function handler(event) {
  var qs = event.request.querystring;
  ['utm_source','utm_medium','utm_campaign','utm_term','utm_content','fbclid','gclid']
    .forEach(function (k) { delete qs[k]; });
  return event.request;
}
Enter fullscreen mode Exit fullscreen mode

Security best practices

Caching changes your security boundary: a misconfigured CDN can serve one user's data to another.

Lock the origin to CloudFront only. An exposed origin lets attackers bypass WAF and cache entirely. Use Origin Access Control for S3, and for a custom origin (your Route), require a shared secret header plus the com.amazonaws.global.cloudfront.origin-facing prefix list on the load balancer security group.

apiVersion: v1
kind: Secret
metadata:
  name: cdn-origin-verify
  namespace: frontend
type: Opaque
stringData:
  header-name: X-Origin-Verify
  header-value: REPLACE_ME_WITH_A_ROTATED_RANDOM_VALUE
Enter fullscreen mode Exit fullscreen mode

Reject requests without the header at the ingress or in the app, and rotate the value on a schedule (store it in AWS Secrets Manager or Vault, sync with External Secrets Operator — never commit it).

Never cache authenticated responses by accident. Any response that varies per user must carry Cache-Control: private, no-store. One missing header on a /api/me endpoint plus a cache key that ignores Authorization equals cross-user data leakage. Add a contract test in CI that asserts no-store on every authenticated route.

Defend against cache poisoning. Unkeyed headers that influence the response body (X-Forwarded-Host, X-Original-URL) are the classic vector: an attacker sends a poisoned header, the response is cached, every subsequent visitor gets it. Either key on those headers or strip them at the edge. Normalize Host at the origin and reject unknown values.

Restrict who can invalidate. cloudfront:CreateInvalidation on * in a CI role is a denial-of-service primitive. Scope it to the distribution and keep it out of developer roles:

{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Action": ["cloudfront:CreateInvalidation", "cloudfront:GetInvalidation"],
    "Resource": "arn:aws:cloudfront::123456789012:distribution/E1A2B3C4D5E6F7"
  }]
}
Enter fullscreen mode Exit fullscreen mode

Enable logging and alert on hit-ratio drops. CloudFront standard logs or real-time logs to Kinesis let you detect a sudden CacheHitRate collapse — which is either an attack, a bad deploy, or a cache-key regression. Alarm on CloudFront/OriginLatency p99 and on origin 5xx rate, not just on edge 5xx.

Conclusion: key takeaways

  • Invalidation is an incident tool, not a deploy step. If your pipeline runs --paths "/*", that is the bug. Fix it with content-hashed URLs.
  • Two TTL tiers. Immutable, hashed assets at max-age=31536000, immutable; mutable entry documents at no-cache with a stable ETag so revalidation costs a 304.
  • stale-while-revalidate + stale-if-error are free resilience. Users never block on your origin, and an origin outage becomes invisible for the duration of the stale window.
  • Origin Shield collapses POP fan-out from dozens of origin fetches per object to one. Place it in your origin's region.
  • Audit your cache key. Stripped marketing params and cookie-free public paths usually buy more hit ratio than any TTL tuning.
  • Size the origin for a cold cache anyway. Aggressive HPA scale-up, conservative scale-down, a PDB, and a staggered purge script are what turn an unavoidable purge into a non-event.
  • Treat the CDN as part of your security perimeter. Lock the origin to CloudFront, mark private responses no-store, strip unkeyed request headers, and scope the invalidation IAM permission to a single distribution.

Design the cache so that correctness comes from the URL, not from purging. Then the day you do need to purge, it will be a deliberate, narrow, well-rehearsed action — not a 14:03 outage.

Top comments (0)