AlgoViz

CDN operations

medium 30 min

Running a CDN day by day: what to measure, when to wake somebody, how to keep attackers away, how to make it faster and cheaper, and how to find out why a user got a slow, stale or broken answer.

Video lesson · Chapter 1 of 5

One chart says the edge is nearly healthy

0:00 / 4:05

Four numbers for a CDN

1:15Reel coming soon

Theory

Read or listen first. About 2 min.

What it is

After a CDN is switched on, somebody must look after it. CDN operations has four parts: monitoring what it does, securing what passes through, optimizing speed and cost, and troubleshooting when an answer is wrong.

The special difficulty is that the machines belong to another company and stand in hundreds of places. You see them through headers, logs, metrics and your own tests from outside.

Why it exists

A CDN fails quietly. A wrong header in one release can cut the hit ratio from 95% to 70%. Users notice little, but the origin gets six times the load, and at the next peak it falls over.

It is also your front door. Nearly every request passes it, so it is the right place to stop attacks, and the place where one wrong rule can stop everybody.

A short history

  1. November 2012

    RFC 6797 defines HTTP Strict Transport Security: a site can tell browsers to use only HTTPS.

  2. July 2019

    A web application firewall rule with a costly regular expression exhausts CPU at Cloudflare, and its service is down for 27 minutes.

  3. May 2021

    RFC 9000 standardizes QUIC, the transport under HTTP/3.

  4. June 2021

    A customer's valid configuration triggers a bug at Fastly and 85% of its network returns errors. Within 49 minutes 95% of the network works normally.

  5. June 2022

    RFC 9211 defines Cache-Status, a standard header for what caches did with a request. RFC 9114 defines HTTP/3.

Words to know

Cache hit ratio
Hits divided by cacheable requests, or by all requests. Say which.
Byte hit ratio
The share of bytes served from cache.
Origin offload
The share of traffic that the origin does not serve.
p95
95% of requests are at or below this time.
WAF
Web application firewall: rules that inspect requests and block harmful ones.
Cache warming
Requesting content before users do, so that the first user gets a hit.
Synthetic check
A test request sent on purpose, from outside, at regular times.

How it works

Step through the idea, or press Play.

Step 1 of 3

Measure. Hits, bytes, delay, errors per place

Understand it

Start here

A string of mountain huts

Imagine three huts along a mountain path. Hikers want hot soup. Cooking happens in the valley, and the huts keep pots ready.

Looking after the huts
123Every flag is green

A restaurant chain has the same work: check every kitchen, keep trouble outside, speed up service, repair quickly.

The whole field

  • Performance

    Delay, hit ratio, throughput.

  • Security

    Firewall, floods, limits.

  • Cache management

    Lifetimes, purge, warming.

  • Alerts and incidents

    Notice early, respond calmly.

  • Cost

    Speed against the bill.

  • Logs and compliance

    Who changed what, and what was served.

Monitor

The numbers to watch

MetricExample targetTells you
Request hit ratioAbove 90% for static filesHow often the edge answers
Byte hit ratioSet your ownWhat the origin link carries
Origin shareBelow 20% of all requestsWhat still reaches your servers
p95 latency per regionBelow 100 ms for cached filesWhat most users feel
5xx error rateBelow 0.1%Broken answers
Bandwidth and requests a secondA trendCapacity and cost
Examples, not standards. A site of private pages cannot reach 90% hits and need not try.

Small changes in the ratio are large at the origin

1−0.891−0.945=11%5.5%=2×1−0.701−0.95=6×\frac{1-0.89}{1-0.945} = \frac{11\%}{5.5\%} = 2\times \qquad \frac{1-0.70}{1-0.95} = 6\times
From 94.5% to 89% sounds harmless and doubles the origin's work. Alert on origin requests, not only on the ratio.

Requests and bytes tell different stories

950⋅20 KB=19 MB from cache50⋅2 MB=100 MB from origin19119≈16%950 \cdot 20\text{ KB} = 19\text{ MB from cache} \qquad 50 \cdot 2\text{ MB} = 100\text{ MB from origin} \qquad \frac{19}{119} \approx 16\%
95% of requests are hits, but only 16% of bytes. Large files missed.

The example dashboard saves 2.4 TB a day. That is 2.4 x 10^12 x 8 bits / 86,400 s, or about 222 Mbit/s on average and about 667 Mbit/s at a 3x peak that the origin does not have to send.

Alert

When to wake somebody

LevelExample triggerAction
CriticalErrors above 5%, or the origin is downPage the person on call
WarningHit ratio below 85%, latency jumpMessage the team, look today
InfoUnusual traffic, a new locationLog for review
Say how long it must last, for example 5 minutes, and how many requests it needs. One failed request of two is not 50% trouble.

Page or not?

Where the signals come from

Users and a synthetic checker outside send requests to the edges of the CDN. The edges ask our origin on a miss. Edge logs and origin metrics both flow into our monitoring with Prometheus and Grafana, and Grafana alerts the person on call.
Three views: the CDN's logs, our own metrics, and tests from outside. Each one can be wrong alone.

Tools people use: the CDN's own analytics (Cloudflare, Fastly, CloudFront metrics in CloudWatch), and Datadog, Grafana, New Relic, Prometheus or Splunk for collecting. CloudFront's cache hit rate counts cacheable requests only and must be switched on per distribution.

Secure

Layers of protection

  • Flood protection

    Large networks absorb traffic floods. Small, clever floods on costly pages need limits too.

  • WAF

    Rules against injection, scripts and known attacks. It reduces risk and does not repair the app.

  • Rate limiting

    Too many requests from one key get a 429.

  • Bot management

    Keep bad bots out and let good ones in, with proof of identity.

  • TLS

    Certificates at the edge. Encrypt the way to the origin as well.

  • Geo rules

    By country, for law or licences. Easy to get around, so not a security wall.

A request through the layers

Order differs between providers. Cheap checks come first.

Secure

Security headers

HeaderValueDoes
Strict-Transport-Securitymax-age=31536000; includeSubDomainsOnly HTTPS for a year
X-Content-Type-OptionsnosniffNo guessing of types
Content-Security-Policydefault-src 'self'; frame-ancestors 'none'Limits sources and framing
X-Frame-OptionsDENYFraming, for older browsers
Referrer-Policystrict-origin-when-cross-originLess address data to others
Do not add X-XSS-Protection with mode=block. MDN marks it deprecated and non-standard, and it can create holes in safe pages. Start HSTS with a short time: includeSubDomains locks every subdomain.

Optimize

Faster and smaller

TechniqueWhat it doesRemember
Compressiongzip or Brotli for textNot for JPEG or video. CloudFront compresses 1,000 to 10,000,000 bytes
HTTP/2 and HTTP/3Many requests on one connection, HTTP/3 on QUICGains depend on the network
Image formatsWebP, AVIF, right sizes, lazy loadingGoogle: lossy WebP is 25 to 34% smaller than comparable JPEG
Cache rulesLifetimes per type of contentUsually the largest gain
MinificationSmaller HTML, CSS and JSDo it in the build
Connection hintsdns-prefetch and preconnectOnly for a few important hosts
Measure before and after with real user data. Percentages from other sites are not yours.

Raise the hit ratio

  1. 1

    Split by path

    One path often causes most misses.

  2. 2

    Look at the key

    Tracking words, cookies, many values of a header.

  3. 3

    Look at the headers

    Set-Cookie or private on public files stops caching.

  4. 4

    Lengthen lifetimes

    With hashed names or a purge by tag.

  5. 5

    Add a shield

    One place for all misses: see CDN design.

Prepare

Warming a cache

Request the important pages before users do: after a deployment, before a campaign. A request warms only the location it reaches, so test requests from one city warm that one city, plus the shield. Warm the shield and let edges fill quickly from it.

Do

  • A list of the top pages
  • Slowly, below the spare load of the origin
  • The same key as users: encoding, language
  • Before the peak, after the purge

Avoid

  • Crawling everything
  • All at once
  • Warming a version users do not ask for
  • Warming so early that it expires

Warming 10,000 pages at 100 a second takes 100 seconds through one shield. At 50 locations without a shield it is 500,000 requests to the origin, or 83 minutes at the same speed. More in cache warming.

Troubleshoot

Four common troubles

TroubleLook forDo
Low hit ratioShort TTL, Vary with many values, query words, Set-CookieLonger TTL, normalize, clean the key
High latencyMisses, slow origin, wrong locationWarm, speed up the origin, check routing
Stale contentLong TTL, purge not sent or late, browser copyCheck Age and ETag, repeat the purge, new name
5xx errorsOrigin down, TLS between CDN and origin, limits, timeoutsTest the origin directly, certificates, limits

Why did the user get this answer?

Headers that help

HeaderSaysWho
AgeSeconds since the copy was made or checkedStandard
Cache-StatusHit, or why it was forwardedStandard, RFC 9211
X-CacheHIT or MISSFastly, CloudFront and others
X-Cache-HitsHits at each nodeFastly
X-Served-ByWhich cache servers answeredFastly
CF-Cache-StatusHIT, MISS, STALE, BYPASS, DYNAMIC and moreCloudflare
CF-RayIdentifier of the requestCloudflare
Names that start with X- have no common meaning. Read your provider's page.
Shell
curl -sS -o /dev/null -D - https://www.example.com/logo.png# look for: cache-control, age, etag, x-cache, cache-status, vary, set-cookie
Only the headers of one answer. Run it twice: the second one should be a hit.

Pay and prove

Cost and logs

You pay forLower it by
Bytes sent to usersCompression, right image sizes
Number of requestsBrowser caching, fewer files
Origin trafficByte hit ratio, a shield
Extras: logs, functions, purgesSampling, hashed names instead of purges
Price lists differ. Work out your own bill by path: a few large files often make most of it.

Keep edge logs for debugging, security and billing, and keep them only as long as you need. Addresses of users are personal data in many places. Also record who changed which rule, and when.

An incident, step by step

First stop the harm, then look for the deeper cause.

Change

Rules are deployments

A CDN configuration reaches the whole world in seconds. Both outages in the history above began with a change. So treat rules as code: review, test, and roll out in steps.

A safe rule change

  1. 1

    Log only

    Count what the rule would block.

  2. 2

    A small part

    One path, one region or 1% of traffic.

  3. 3

    Watch

    Errors, blocked share, complaints.

  4. 4

    Everywhere

    With a tested way back.

  5. 5

    Write it down

    Who, why, until when.

Do

  • Monitor each location and path
  • Runbooks for the common troubles
  • Security headers for the whole site
  • Review hit ratios regularly
  • A plan for a CDN outage

Avoid

  • Ignoring alerts until they mean nothing
  • Switching the WAF off to make an error go away
  • Limits so tight that shared offices are blocked
  • Skipping load tests
  • Changes without a way back

Summary

The whole topic in one minute.

Watch hit ratio in requests and in bytes, origin load, p95 per region and the error rate, each split by path and place. Page a person for harm to users, not for every wobble.

Protect in layers: floods, firewall rules, limits, bots, TLS, headers, and an origin that accepts only the CDN. Roll rules out in steps. For every strange answer, read the headers first: hit or miss, how old, which place.

  • Monitor, optimize, secure, troubleshoot.
  • Misses, not hits, are what the origin feels.
  • Count requests and bytes.
  • Close the origin to everybody but the CDN.
  • Read the headers before you guess.

Sources