How systems work

CDNs.

A content delivery network (CDN) is a set of servers spread around the world, called edges, that keep copies of your files close to your users. A user in Mumbai gets your JavaScript from a server in Mumbai instead of from your one origin server in Virginia.

That sounds like a simple speed trick, and it is mostly a caching problem with all of caching’s traps: copies that are out of date, copies that belong to someone else, and caches that quietly store nothing at all until a traffic spike finds out. This page shows each one happening.

In the labs after the walkthrough, each row is a region: its users, their nearest edge and a line to the origin. Rows are placed by distance, so a longer line is a longer round trip. Each chip is one request. It is white on its way out and coloured on its way back by who answered: the edge, the shield or the origin. The small boxes in an edge are the copies it holds, each with a bar showing the time it has left. Network time is slowed six times so you can see it.

00 The life of one request

Before the live labs, follow a single request for a JavaScript file from a user in Sydney to a server in Virginia and back. Step through at your own pace, or press Play all.

Pacific · 200 msAnauser in SydneySydney edgenear Ana, keeps copiesShieldcache for all edgesOriginyour serverCachetime leftemptyCachetime leftemptyFiles/app.js v1asks for filesanswers from its copiessaves origin tripshas the real file

Step 1 of 10

Meet the pieces

A CDN puts servers between your users and your own server. Edges sit in many cities, close to users, and keep copies of your files. A shield is one more cache, next to your server. The origin is your server: it has the real files.

01 Distance is latency

Light in fibre covers about 200 km per millisecond, and real cables do not run in straight lines. A round trip from Sydney to Virginia takes about 200 ms before the server does any work. No amount of server tuning removes that; only moving the answer closer does.

A CDN does that. The user talks to an edge a few milliseconds away. If the edge has a copy, the answer never crosses the ocean.

UsersOriginNew Yorkno CDNLondonno CDNSão Paulono CDNMumbaino CDNSydneyno CDNyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
  • On its way
  • Edge hit
  • From the origin
  • Click a chip to follow it
Average response
–
Origin requests
0
Five regions and one origin in Virginia. The number under each group of users is their last response time.
    Try this. Watch Sydney and Mumbai take over 200 ms while New York, next door to the origin, takes about 60 (the origin itself spends 40 ms on each request). Turn on the CDN: every edge already holds a copy, so every region drops to 10 to 20 ms and the origin stops getting requests.

    For users far from your servers, the network, not your code, sets the floor on response time. A CDN lowers that floor by answering nearby.

    02 Hits, misses and separate caches

    An edge that has a fresh copy answers at once: a hit. One that doesn’t forwards the request to the origin, waits, stores the answer and passes it on: a miss. The miss is as slow as having no CDN.

    Every edge keeps its own cache. A copy in London does nothing for a user in Sydney, so the first request in every region misses. If a second request arrives while the first is still fetching, the edge makes it wait for that fetch instead of sending another (more in section 08).

    Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
    • On its way
    • Edge hit
    • From the origin
    • Click a chip to follow it
    Edge hit ratio
    –
    Edge hits
    0
    Origin requests
    0
    Copies at edges
    0
    Every edge starts empty. Watch the first request in each region go all the way to the origin.
      Try this. Count the orange chips: one per region, five origin requests in all, then green from then on. Press “Empty every edge cache” and it happens again.

      The hit ratio, the share of requests the edge answers itself, is the number to watch. It is lowest right after a deploy or purge, and for files few people ask for.

      03 TTL: how long a copy lives

      The origin tells caches how long a response stays fresh with a header: Cache-Control: public, max-age=60 means any cache may keep it for 60 seconds. That time is the TTL. Until it runs out the edge answers from its copy without asking the origin anything, even if the origin has changed the file since.

      • A long TTL means few origin requests and a high hit ratio, but users can see old content for that long after you change it.
      • A short TTL keeps content fresh, at the cost of more misses and more origin load.
      Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
      • On its way
      • Edge hit
      • From the origin
      • Click a chip to follow it
      Origin requests
      0
      Old version served
      0
      Edge hit ratio
      –
      The chips coming back show which version of /news they carry. Each copy's green bar is its remaining TTL.
        Try this. Wait until every edge holds v1, then press “Deploy a new version”. Every edge keeps serving v1 until its own bar runs out, and the old-version count climbs. Set the TTL to 60 s and deploy again: the stale window is far longer. Set it to 1 s: almost nothing stale, but origin requests climb.

        Pick the TTL from how long stale content is acceptable, file by file: long for images and fonts, short for news and prices.

        04 Public, private and no-store

        A CDN cannot see what a response means. It only reads headers. If a page is personal, the headers must say so:

        • public lets shared caches, such as a CDN, store it and give it to anyone.
        • private allows only the user’s own browser to keep it. A CDN must pass it through.
        • no-store means no cache anywhere keeps it.

        Mark a personal page public and the edge will store the first visitor’s page and hand it to everyone after them. This has happened to real companies, usually through one wrong rule.

        Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
        • On its way
        • Edge hit
        • From the origin
        • Click a chip to follow it
        Wrong person’s page
        0
        Edge hits
        0
        Origin requests
        0
        Each user's account page. Chips show the user's initial going out, and whose page it is coming back.
        Cache-Control on /account
          Try this. With public, watch a chip leave as B and come back red as A: Ben got Ana’s page. Switch to private. Every request now goes to the origin, which is slower, but every user gets their own page.

          Default to private for anything that depends on who is asking. Cache public pages, and fetch the personal parts separately.

          05 The cache key

          An edge finds a copy by its cache key, usually the host, the path and the query string. Two requests share a copy only if their keys match. That makes the key a trade-off in both directions:

          • Too much in the key splits one page into many copies. Ad links add ?utm_source=… with endless values, and each one becomes its own miss.
          • Too little in the key merges responses that differ, as in section 04.
          • Adding the session cookie keeps pages apart per user, but then each user warms their own copy and the cache helps little.
          Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
          • On its way
          • Edge hit
          • From the origin
          • Click a chip to follow it
          Edge hit ratio
          –
          Copies at edges
          0
          Origin requests
          0
          The same product page, linked from ads with 40 different tracking values.
          Cache key
            Try this. With the query string in the key, the edges fill up with copies of one page and most requests miss. Switch to path only: one copy per edge and nearly every request hits. Try the session cookie: better than tracking values, still far worse than path only.

            Put in the key exactly what changes the response, nothing more. Strip tracking parameters, and keep personal data out of cached pages instead of keying on it.

            06 Origin shield: one request, not one per edge

            With hundreds of edges, a file nobody has asked for lately costs one origin request per edge. An origin shield (also called tiered caching) adds one more cache next to the origin. Edges that miss ask the shield; only the shield asks the origin.

            A miss at the edge that hits the shield still crosses the ocean, so it is no faster for that user. The win is for the origin, which now sees one request per file per TTL.

            Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
            • On its way
            • Edge hit
            • From the shield
            • From the origin
            • Click a chip to follow it
            Origin requests
            0
            Shield hits
            0
            Edge hit ratio
            –
            A 5-second TTL, so copies expire often. Every expiry is a chance to hit the origin.
              Try this. Without the shield, each expiry brings five orange chips, one per region. Turn the shield on and reset: after its first fetch, the other regions come back purple from the shield, and the origin count grows a fifth as fast.

              A shield matters most when you have many edges, an origin that is expensive to call, or files that are each asked for rarely.

              07 Purging and versioned file names

              Static files such as scripts and styles want very long TTLs, often a year. But then a deploy changes nothing for users until the copies expire. There are two ways out:

              • Purge: tell the CDN to drop its copies. It takes a moment to reach every edge, and afterwards every region misses at once.
              • Versioned names: give each build its own file name, such as app.3f9c.js, and link to it from HTML with a short TTL. A new build is a new name, which no cache has seen, so no old copy can be served for it. Old copies sit there unused until they expire.
              Users and their nearest edgeOriginNew York · 10 msedge cachev176 ms round tripLondonedge cachev1120 ms round tripSão Pauloedge cachev1190 ms round tripMumbaiedge cachev1200 ms round tripSydneyedge cachev1your server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
              • On its way
              • Edge hit
              • From the origin
              • Click a chip to follow it
              Old version served
              0
              Origin requests
              0
              Edge hit ratio
              –
              app.js with a 10-minute TTL. Every edge starts with a copy of version 1.
                Try this. Deploy a new version. Nothing changes for users: every edge keeps serving v1 and the old-version count climbs. Press purge: a moment later every region misses once and gets v2. Now turn on versioned names, reset and deploy: the very next requests ask for the new name and old versions served stays at zero, with no purge.

                Version the file names of static assets and cache them for a year. Keep purges for mistakes, and for content whose URL cannot change.

                08 A viral spike, and wrong cache rules

                The origin below can handle about 100 requests a second: four workers and a short queue. Past that it answers 503. A viral link brings twelve times the normal traffic. With a working cache, the origin still sees about one request per region every five seconds, whatever the traffic.

                The cache only works if the rules let it. Three common mistakes make every request a miss, and you usually find out during the spike:

                • no-store or private on pages that are the same for everyone, often a framework default.
                • A Set-Cookie on every response. Many CDNs will not store a response that sets a cookie.
                • Tracking parameters in the cache key, so every ad click is a new key.

                There is one more trap: when a popular copy expires mid-spike, dozens of requests miss at the same moment. Collapsing makes them wait for one fetch. Without it, each one goes to the origin.

                Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
                • On its way
                • Edge hit
                • From the origin
                • 503 error
                • Click a chip to follow it
                Origin load
                0/s
                Peak origin load
                0/s
                Errors (503)
                0
                Edge hit ratio
                –
                The origin box shows requests in the last second, its four workers and its queue.
                Cache rule
                  Try this. Go viral with the right rule: the chips multiply, but almost all are green and the origin barely notices. Pick “Sets a cookie”, which starts a fresh run, and go viral again: every chip goes to the origin, the queue fills and red 503s come back. Then try the right rule with collapsing off and watch the origin load jump each time a copy expires.

                  Check the hit ratio of your busiest pages before launch day. A CDN that caches nothing still looks fine until the traffic arrives.

                  09 stale-while-revalidate

                  With a plain TTL, the first user after each expiry pays for a full trip to the origin. Cache-Control: max-age=60, stale-while-revalidate=600 changes that: for ten minutes after the TTL, the edge answers at once with its stale copy and fetches a fresh one in the background. The next user gets the fresh copy.

                  Users then never wait on the origin for a popular file, at the cost of one more request seeing content one TTL older than it could have. A related directive, stale-if-error, serves the stale copy when the origin is failing.

                  Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
                  • On its way
                  • Edge hit
                  • From the origin
                  • Stale, refreshing
                  • Background refresh
                  • Click a chip to follow it
                  Waited on origin
                  0
                  Served stale
                  0
                  Average response
                  –
                  A 2-second TTL. Dashed chips are background refreshes, not users.
                    Try this. Without it, every expiry makes one user per region wait for the origin, and waited on origin keeps climbing. Turn on stale-while-revalidate: yellow chips come straight back from the edge, a dashed chip goes to fetch the update, and waited on origin stops growing.

                    For content that is fine a little stale, stale-while-revalidate removes the slow request from the user’s path entirely.

                    10 Dynamic pages and code at the edge

                    Personal pages cannot be cached whole. Most CDNs now run your code on the edge servers (Cloudflare Workers, Fastly Compute, CloudFront Functions and Lambda@Edge, Akamai EdgeWorkers), so a page can be built a few milliseconds from the user. It is tempting to move everything there.

                    But code needs its data. If the edge function reads a database that lives in Virginia, each query crosses the ocean. A page that needs three queries in a row is three round trips, slower than building it at the origin next to the database. Edge code pays off when its data is at the edge too: cached, replicated, or carried in the request, such as a signed cookie.

                    Users and their nearest edgeOriginNew York · 10 msedge cacheempty76 ms round tripLondonedge cacheempty120 ms round tripSão Pauloedge cacheempty190 ms round tripMumbaiedge cacheempty200 ms round tripSydneyedge cacheemptyyour server0/sof 100 maxqueue 0100 ms round tripNetwork time slowed 6× · clock 0.0 s
                    • On its way
                    • Edge hit
                    • From the origin
                    • Built at the edge
                    • Click a chip to follow it
                    Average response
                    –
                    Origin requests
                    0
                    A personal page that needs three database reads. Watch where the chips go.
                    Where the page is built
                      Try this. Pick “Edge, database in Virginia”: Sydney’s chips cross the ocean three times and response times triple. Pick “Edge, data at the edge”: every region answers in about 20 ms.

                      Move code to the edge only with the data it reads. Common uses are redirects, auth checks on signed tokens, A/B routing and stitching cached fragments together.

                      11 Choosing a CDN

                      The ideas above are the same everywhere. The products differ in network size, how fast purges reach every edge, how you configure them and what code they can run. A rough map:

                      CDNCode at the edgePurgeShield / tiersKnown for
                      CloudflareWorkers (JavaScript, Wasm)By URL; by tag, prefix or host on some plansTiered CacheLarge network, free plan, security bundled in
                      FastlyCompute (Wasm); VCL for cache rulesVery fast, by URL or surrogate keyShielding, pick a shield locationProgrammable caching, quick purges
                      Amazon CloudFrontCloudFront Functions, Lambda@EdgeInvalidations by path, with wildcardsRegional edge caches, Origin ShieldClose fit with S3 and the rest of AWS
                      AkamaiEdgeWorkersFast Purge, by URL or cache tagTiered distributionOne of the oldest and largest networks, enterprise focus

                      Check the current docs before you choose: features, limits and prices change often and differ by plan.

                      12 Check yourself

                      1. You put a CDN in front of your site with a one-hour TTL. A user in Sydney is the first visitor from Australia today. How fast is their request?

                      2. The account page shows the signed-in user’s name. Someone marks it Cache-Control: public, max-age=300. What happens?

                      3. Your app ships app.js with a one-year TTL. You fix a bug and deploy. What is the cleanest way to get the fix to users?

                      4. Your hit ratio on product pages is 20% even though the TTL is an hour. Every ad link adds ?utm_source=… with a different value. Why?

                      5. A post goes viral and traffic jumps 20 times. The origin falls over even though there is a CDN. The responses set a session cookie on every request. What is the likely cause?

                      Next partSharding and consistent hashing