Skip to content
Tech Intuition
Tech Intuition

Appearance

Theme

Signal · Dark with amber

Background

Slow stars and the odd comet

Connect

Core concepts · Lesson 10 of 44

DNS, CDNs and the edge

How a request finds your servers and how content gets close to users: DNS resolution, TTLs and failover timelines, anycast, CDN cache keys and headers, origin shields and invalidation, with simulations of failover time and hit ratio.

ConceptCore26 min readUpdated

  • 4 code samples
  • 6 interviewer follow-ups
  • 5 self-checks

Read first: Caching, Load balancing

By the end you will be able to
  • Walk through a DNS resolution, say what each cache layer does, and explain why a TTL bounds but does not guarantee how fast traffic moves.
  • Estimate a failover timeline from the detection time and the TTL, including resolvers that keep answers too long.
  • Explain how a CDN decides what to cache (cache key, Cache-Control, Vary) and compute origin load from a hit ratio.
  • Show why many edge locations dilute the hit ratio, and how a shield and long TTLs on versioned URLs recover it.
  • Choose between purging and versioned URLs, and keep private content private at the edge.
Prefer to watch? · 14 min video

4 code samples (163 lines), collapsed so the explanation stays in focus.

Before a request reaches your code it has to find your servers, which is DNS, and then for most of the bytes it never reaches them at all, because a cache near the user, a CDN, answers it. Both are caches with expiry times, and between them they appear in nearly every large design: global traffic management, failover, static content, video. Both also fail in the same way, which is that the time a change takes to reach everyone is longer than people expect. This lesson explains how a name becomes an address, what a failover through DNS really costs in time, how a CDN decides what to keep, and why adding more edge locations can raise the load on your origin. Each claim is checked by a simulation.

HLD

How a name becomes an address

A client that needs www.example.com asks a recursive resolver (its ISP's, or a public one) through a small stub resolver in the operating system. If the resolver has no fresh answer it walks the hierarchy: it asks a root server which servers handle com, asks a TLD server which servers are authoritative for example.com, and asks one of those for the record. The answer comes back down with a TTL, and every cache on the path keeps it for that long.

LayerWhat it cachesWhere the surprises are
Browser and applicationThe answer for its own, often short, timeSome runtimes cache longer than the TTL, or forever, and connection pools keep resolved addresses
Operating system stubThe answer, by TTL
Recursive resolverAnswers for all its users, and the addresses of TLD and authoritative serversMay raise very short TTLs to a floor, or lower very long ones
Authoritative serversNothing: they are the sourceThey set the TTL, and they are what an outage of your DNS provider takes down

A cold lookup is about four round trips, and a warm one is zero to one, which is why a CDN's or a site's first visit is slower. The records that matter: A and AAAA (an address), CNAME (an alias to another name, which adds a lookup), NS (which servers are authoritative), TXT (verification, policy), and SRV or HTTPS records for services. Failures are cached too: a negative answer (no such name) is kept for a TTL of its own.

The TTL is a promise about how long an answer may be reused, not a command. Resolvers, operating systems, runtimes and connection pools each have their own caching, so a record changed at 12:00:00 is seen at different moments by different clients, and a few see it much later. Every design that moves traffic with DNS has to plan for that.

DNS for traffic management. An authoritative server can return different answers to different askers: several addresses in rotation (round robin), weighted answers for a gradual shift, answers chosen by the asker's location or measured latency, and answers withheld for endpoints whose health checks fail. The limits are real. The authoritative server sees the resolver's address, which may be far from the user (EDNS Client Subnet lets a resolver pass a prefix of the user's address along, where it is supported). It knows nothing about load, it cannot drain connections, and any change waits for the TTLs.

Anycast is the other way to steer users. Many locations announce the same IP address through BGP, and the network delivers each packet to the closest announcer in routing terms. DNS providers and CDNs use it, which gives them nearest-location routing without DNS tricks, spreads attack traffic over every location, and fails over by withdrawing the announcement from a broken one. The costs are that "closest in routing" is not always closest in distance, route changes take tens of seconds to settle, and a long-lived TCP connection can be broken when its path moves to another location.

LLD

A failover through DNS, in time

When an endpoint fails, three delays add up before a client stops using it. Detection: health checks run on an interval and need several failures in a row (three checks ten seconds apart is thirty seconds) before the record changes. Propagation: a client that cached the old answer keeps using it until its cache expires, up to one full TTL. And stragglers: some resolvers and clients keep answers longer than the TTL says, and they decide the tail. A resolver that refreshes before detection simply gets the failed address again and keeps it for another full TTL, so the worst compliant client moves at detection plus one TTL.

Example · formula
last compliant client:  detection + TTL
half of the clients:    about detection + TTL ÷ 2
stragglers:             stretch × TTL, for resolvers that keep answers

The simulation has 100,000 resolvers, each at a random point of its cache lifetime when the endpoint fails. It computes when each one starts using the new address, with and without a share of resolvers that keep answers five times longer than the TTL (the 5% is an assumption, since the real share varies with your clients).

C# · 100,000 resolvers cache the DNS answer for the TTL. At time 0 the endpoint fails. Health…30 lines
using System;
using System.Diagnostics;

// 100,000 resolvers cache the DNS answer for the TTL. At time 0 the endpoint fails. Health checks notice after `detect`
// seconds and the record is changed. A resolver that refreshes before then gets the failed address again and keeps it for another
// TTL. A share of resolvers keep answers `stretch` times longer than the TTL says.
double[] MovedAt(double ttl, double detect, double misbehaving, double stretch)
{
    var random = new Random(23);
    var moved = new double[100_000];
    for (int r = 0; r < moved.Length; r++)
    {
        double lifetime = random.NextDouble() < misbehaving ? ttl * stretch : ttl;
        double expires = random.NextDouble() * lifetime;                  // when this resolver next asks, counted from the failure
        while (expires < detect) expires += lifetime;                      // asked too early: it got the failed address again
        moved[r] = expires;
    }
    Array.Sort(moved);
    return moved;
}
double Percentile(double[] sorted, double p) => sorted[(int)(p * (sorted.Length - 1))];

var ttl60 = MovedAt(60, 30, 0, 5);
Debug.Assert(Math.Abs(Percentile(ttl60, 0.5) - 60) < 1 && Math.Abs(Percentile(ttl60, 0.9) - 84) < 1 && Math.Abs(Percentile(ttl60, 0.99) - 89) < 1 && ttl60[^1] <= 90);
var ttl300 = MovedAt(300, 30, 0, 5);
Debug.Assert(Math.Abs(Percentile(ttl300, 0.5) - 180) < 1 && Math.Abs(Percentile(ttl300, 0.9) - 300) < 1 && ttl300[^1] <= 330);
var stragglers60 = MovedAt(60, 30, 0.05, 5);
Debug.Assert(Math.Abs(Percentile(stragglers60, 0.9) - 86) < 1 && Math.Abs(Percentile(stragglers60, 0.99) - 274) < 1 && stragglers60[^1] <= 330);
var stragglers30 = MovedAt(30, 30, 0.05, 5);
Debug.Assert(Math.Abs(Percentile(stragglers30, 0.99) - 150) < 1 && stragglers30[^1] <= 180);
Setup50% moved90%99%Last
TTL 60 s, detection 30 s60 s84 s89 s90 s
TTL 300 s, detection 30 s180 s300 s327 s330 s
TTL 60 s, 5% of resolvers keep answers 5 times longer61 s86 s274 s330 s
TTL 30 s, the same 5%46 s58 s150 s180 s

What to take from the numbers. DNS failover is minutes, not seconds, and a low TTL helps the middle of the curve and almost not the tail: with 5% of clients stretching answers, the 99th percentile was 274 seconds at a 60-second TTL and still 150 at 30. The lower the TTL, the more queries your authoritative servers answer and the more every lookup costs the user, so TTLs of 30 to 60 seconds are for the few records that move traffic and long TTLs (an hour or more) for the stable ones. Lower the TTL before a planned move, a full old TTL ahead of it. And do not use DNS as the only failover. Within a region a health-checked load balancer shifts traffic in seconds, and anycast does the same across locations. Use DNS for the coarse, global decision (this region is gone), and say plainly that it takes minutes.

HLD

What a CDN does

A content delivery network is a fleet of reverse-proxy caches in many points of presence (PoPs) near users. A request is steered to a nearby PoP (by DNS answers or anycast), which terminates the connection and TLS there, and looks the object up in its cache. A hit is served from a few milliseconds away. A miss is fetched from the origin (or from a bigger cache layer in front of it, below), stored according to the response's headers and served.

What that buys: latency (the round trip to a PoP, not to the origin: see the network performance lesson for what handshakes cost per round trip), offload (the origin serves only misses), absorption (traffic spikes and attacks are spread over a large fleet), and optimised connections from the PoP to the origin, kept warm and reused. What it costs: egress charges, a second place where things can be stale or wrong, and invalidation, which is the hard part.

What gets cached is decided by the cache key and the response headers.

Header or ruleWhat it does
Cache keyNormally the method, host, path and query string. Normalise parameter order and drop tracking parameters, or the same object is cached many times
Cache-Control: max-age=NFresh for N seconds in any cache. s-maxage=N overrides it for shared caches such as a CDN
public and privateprivate means only the user's own browser may keep it, and a CDN must not
no-storeNever store it
no-cacheStore it, but check with the origin (a conditional request with the ETag) before every use
immutableThe object will never change, so skip even revalidation while fresh
stale-while-revalidate=N, stale-if-error=NServe a stale copy for N seconds while refreshing in the background, or when the origin is failing
Vary: Accept-EncodingA separate stored copy for each value of that request header (compressed or not)
Vary: Cookie or User-AgentAlmost every request becomes its own variant, and the hit ratio collapses

The rules are mechanical, and the next sample encodes the ones that decide whether a CDN may keep a response and for how long.

C# · How long may a shared cache (a CDN) serve this response without asking the origin? The…29 lines
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

// How long may a shared cache (a CDN) serve this response without asking the origin? The response's Cache-Control and its age.
int SharedCacheSeconds(string cacheControl, int ageSeconds)
{
    var directives = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
    foreach (var part in cacheControl.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries))
    {
        var pair = part.Split('=', 2);
        directives[pair[0].Trim()] = pair.Length > 1 ? pair[1].Trim() : "";
    }
    if (directives.ContainsKey("no-store") || directives.ContainsKey("private") || directives.ContainsKey("no-cache")) return 0;   // not stored, or must be revalidated every time
    string lifetime = directives.TryGetValue("s-maxage", out var shared) ? shared : directives.TryGetValue("max-age", out var normal) ? normal : null;
    if (lifetime == null) return 0;                                                  // no explicit freshness: this sketch does not guess
    return Math.Max(0, int.Parse(lifetime) - ageSeconds);                             // the time already spent in other caches counts
}

Debug.Assert(SharedCacheSeconds("max-age=60", 0) == 60);
Debug.Assert(SharedCacheSeconds("max-age=60, s-maxage=300", 0) == 300);                    // the CDN's own lifetime wins
Debug.Assert(SharedCacheSeconds("public, max-age=31536000, immutable", 0) == 31_536_000);  // a hashed asset: a year
Debug.Assert(SharedCacheSeconds("private, max-age=600", 0) == 0);                          // per-user data must not sit in a shared cache
Debug.Assert(SharedCacheSeconds("no-store", 0) == 0);
Debug.Assert(SharedCacheSeconds("no-cache, max-age=600", 0) == 0);                         // stored maybe, but revalidated before every use
Debug.Assert(SharedCacheSeconds("max-age=60", 50) == 10);                                  // it already spent 50 seconds in an upstream cache
Debug.Assert(SharedCacheSeconds("Max-Age=60 , S-MaxAge=90", 0) == 90);                     // directive names are case-insensitive
Debug.Assert(SharedCacheSeconds("", 0) == 0);

LLD

Hit ratio, cache size and the shape of traffic

The number that governs a CDN is the hit ratio, because the origin sees only the misses.

Example · formula
origin load = requests × (1 − hit ratio)
95% to 99% hit ratio: origin load falls 5 times

Web traffic is skewed: a few objects get most of the requests and a long tail gets almost none, roughly Zipf's law (the object ranked kth in popularity gets a share proportional to 1 / k). That makes the hit ratio climb steeply for the first small cache and flatten after, and it is why "how big should the cache be?" has an answer with a knee in it. The sample below uses a catalog of 20,000 objects with Zipf popularity and an LRU cache with expiry (the same eviction as in the caching lesson), and compares a single cache of different sizes, then many edge caches with and without a shield. The first million of two million requests warm the caches, and only the second million are counted.

C# · An LRU cache whose entries also expire after a time to live. Lookup returns true on a…61 lines
using System;
using System.Collections.Generic;

// An LRU cache whose entries also expire after a time to live. Lookup returns true on a hit; on a miss the caller fetches from
// the next tier, and the object is inserted here.
public sealed class TtlCache
{
    private readonly int capacity;
    private readonly Dictionary<int, LinkedListNode<(int Key, double Expires)>> map = new Dictionary<int, LinkedListNode<(int, double)>>();
    private readonly LinkedList<(int Key, double Expires)> order = new LinkedList<(int, double)>();    // front = most recently used

    public TtlCache(int capacity) { this.capacity = capacity; }

    public bool Lookup(int key, double now, double ttl)
    {
        if (map.TryGetValue(key, out var node))
        {
            if (node.Value.Expires > now)
            {
                order.Remove(node);
                order.AddFirst(node);
                return true;
            }
            order.Remove(node);                                    // expired: treat as a miss and refetch
            map.Remove(key);
        }
        if (map.Count >= capacity)
        {
            map.Remove(order.Last.Value.Key);
            order.RemoveLast();
        }
        map[key] = order.AddFirst((key, now + ttl));
        return false;
    }
}

// Clients reach one of `edges` caches. A miss goes to the shield, if there is one, and then to the origin.
public sealed class Cdn
{
    private readonly TtlCache[] edges;
    private readonly TtlCache shield;
    private readonly double ttl;
    public long OriginRequests { get; private set; }

    public Cdn(int edgeCount, int edgeCapacity, int shieldCapacity, double ttl)
    {
        edges = new TtlCache[edgeCount];
        for (int i = 0; i < edgeCount; i++) edges[i] = new TtlCache(edgeCapacity);
        shield = shieldCapacity > 0 ? new TtlCache(shieldCapacity) : null;
        this.ttl = ttl;
    }

    public void ResetCounters() => OriginRequests = 0;

    public void Request(int edge, int key, double now)
    {
        if (edges[edge].Lookup(key, now, ttl)) return;
        if (shield != null && shield.Lookup(key, now, ttl)) return;
        OriginRequests++;
    }
}
C# · 2,000,000 requests over 10 minutes for 20,000 objects whose popularity follows Zipf's…43 lines
using System;
using System.Diagnostics;

// 2,000,000 requests over 10 minutes for 20,000 objects whose popularity follows Zipf's law (exponent 1). The first million warm the
// caches and only the second million are counted.
const int Catalog = 20_000, Requests = 2_000_000, Seconds = 600;
var zipfRandom = new Random(17);
double[] cumulative = new double[Catalog];
double total = 0;
for (int rank = 0; rank < Catalog; rank++) cumulative[rank] = total += 1.0 / (rank + 1);
int[] objects = new int[Requests];
int[] clients = new int[Requests];
for (int i = 0; i < Requests; i++)
{
    int at = Array.BinarySearch(cumulative, zipfRandom.NextDouble() * total);
    objects[i] = at < 0 ? ~at : at;
    clients[i] = zipfRandom.Next(1_000_000);                                // which edge a client reaches, chosen below by modulo
}

// The share of the counted requests that reach the origin.
double OriginShare(int edges, int edgeCapacity, int shieldCapacity, double ttl)
{
    var cdn = new Cdn(edges, edgeCapacity, shieldCapacity, ttl);
    for (int i = 0; i < Requests; i++)
    {
        if (i == Requests / 2) cdn.ResetCounters();
        cdn.Request(clients[i] % edges, objects[i], i * (double)Seconds / Requests);
    }
    return cdn.OriginRequests / (double)(Requests / 2);
}

// One cache, no expiry: the hit ratio against the size of the cache.
Debug.Assert(Math.Abs(OriginShare(1, 200, 0, 1e9) - 0.569) < 0.002);        // 1% of the catalog: 43% of requests hit
Debug.Assert(Math.Abs(OriginShare(1, 1_000, 0, 1e9) - 0.386) < 0.002);      // 5%
Debug.Assert(Math.Abs(OriginShare(1, 4_000, 0, 1e9) - 0.216) < 0.002);      // 20%
Debug.Assert(Math.Abs(OriginShare(1, 10_000, 0, 1e9) - 0.095) < 0.002);     // 50%

// Twenty edges of 4,000 objects (20% of the catalog each). A 60-second TTL against a day, and a shield of 12,000 objects against none.
Debug.Assert(Math.Abs(OriginShare(1, 4_000, 0, 60) - 0.217) < 0.002);       // one busy cache barely notices a 60-second TTL
Debug.Assert(Math.Abs(OriginShare(20, 4_000, 0, 60) - 0.295) < 0.002);      // spread over 20 edges, each object expires between repeats
Debug.Assert(Math.Abs(OriginShare(20, 4_000, 12_000, 60) - 0.083) < 0.002); // the shield merges the 20 miss streams
Debug.Assert(Math.Abs(OriginShare(20, 4_000, 0, 86_400) - 0.216) < 0.002);  // a day-long TTL brings it back to a single cache's ratio
Debug.Assert(Math.Abs(OriginShare(20, 4_000, 12_000, 86_400) - 0.064) < 0.002);
Setup (20,000 objects, Zipf popularity)Share of requests reaching the origin
One cache holding 1% of the catalog, no expiry56.9%
One cache holding 5%38.6%
One cache holding 20%21.6%
One cache holding 50%9.5%
One cache of 20%, 60-second TTL21.7%
20 edges of 20% each, 60-second TTL29.5%
The same 20 edges with a shield of 60%8.3%
20 edges of 20% each, one-day TTL21.6%
The same with a shield of 60%6.4%

Four things follow from the table. Hit ratio has diminishing returns: a cache of 1% of the catalog already served 43% of the requests, and doubling from 20% to 50% of the catalog took the origin from 21.6% to 9.5%, so size the cache for the knee and not for the whole catalog. Spreading traffic over many edges dilutes it. At a 60-second TTL, twenty edges sent 29.5% of requests to the origin, against 21.7% for one cache of the same size, because each edge sees a twentieth of the traffic, so an object is often not requested again before it expires, and each edge has to fetch it for itself. A shield cures it. A shield (or tiered cache, or regional cache) is a larger cache between the edges and the origin: every edge that misses asks the shield first, so the same object is fetched from the origin once and not once per edge. It took the origin share from 29.5% to 8.3%. A long TTL cures it too where the content allows, which leads to the next section. The sample processes requests one at a time, so concurrent misses for the same object are free. A real cache must collapse them (request coalescing), so that a hundred simultaneous misses cause one origin fetch, which is the cure for the stampede in the cache consistency lesson.

HLD

Freshness: purge or version

Content changes, and the copies in the PoPs must change with it. There are three ways, and the best of them avoids the problem.

StrategyHowStrengthWeakness
Wait for the TTLA short max-ageNothing to buildStale until it expires, and a short TTL costs hit ratio
PurgeTell the CDN to drop a URL or a tagImmediate-ish, for content that must change nowReaches PoPs over seconds to a minute (vendor-specific), races with refills, and a purge of a hot object is a stampede on the origin
Version the URLThe file name carries a hash of the content (app.4f9c2a.js), cached with max-age=31536000, immutableNo invalidation: a new version is a new URL, the old one is harmless. Caches at every layer, including browsersNeeds a build step, and the HTML that references the files must itself be fresh

So the pattern: immutable, hashed assets with a year-long TTL, and a short TTL (or revalidation with an ETag) on the HTML or API response that points at them. A deploy changes the HTML, which names new asset URLs, and nothing is ever purged. Where purge is needed (a corrected article, a take-down), purge by tag (a surrogate key you attach to every page that contains an object), purge after the origin serves the new version (or a refill can cache the old one again: the invalidation race from the cache consistency lesson), and prefer a soft purge, which marks the object stale so it is served while it is refreshed, over deleting it. stale-while-revalidate hides the refresh latency, and stale-if-error serves the old copy when the origin is failing, which makes the CDN a buffer against origin outages. Brief negative caching of 404s and errors (seconds) protects the origin from a flood of requests for something that is not there.

HLD

Beyond static files

  • Dynamic content. Even uncacheable responses are faster through a CDN: the client's handshakes end at a nearby PoP, and the PoP reuses warm connections to the origin. Hot, slightly stale-tolerant endpoints can be micro-cached for one to five seconds: a hot API called 1,000 times a second by users spread over 50 PoPs reaches the origin at most 50 times in a second, and with a shield once.
  • Personalisation. Do not mark per-user pages cacheable and do not Vary on a cookie. Cache the shared page and fetch the personal parts with a separate API call, or personalise at the edge with code running in the PoP.
  • Video and large files. Video is cut into short segments (HLS and DASH) that are plain cacheable files, with a short-lived playlist that names them. Large files are fetched in ranges. Netflix's Open Connect and similar designs place caches inside ISPs, so the popular titles are filled once overnight and never cross the ISP's backbone at peak.
  • Private content. Do not cache it as public. Use signed URLs or cookies with an expiry that the CDN verifies at the edge, so the object is cached once and only holders of a valid signature get it.
  • Security. A CDN absorbs volumetric attacks across its fleet, and many offer a WAF and bot rules. Lock the origin so that it accepts only the CDN (allow-listed addresses, a shared secret header or mutual TLS), or attackers go around the protection.
  • Cache poisoning. If a response depends on a request header that is not in the cache key (a host override header, say), one attacker's request can store a bad response for everyone. Key on, or strip, every input that changes the response.
  • The CDN is a dependency. Its outage is yours. The largest sites use two CDNs behind a DNS or traffic-management layer, accepting the cost of a split cache and doubled configuration.

HLD

Failure modes and edge cases

FailureWhat goes wrongDefence
A user's page cached for everyoneOne user sees another's dataprivate or no-store on anything personal, no Vary: Cookie tricks, tests that fetch as two users
A bad object with a long TTLA broken file or page is served for hours or a yearVersioned URLs, a tested purge by tag, short TTL on HTML
A purge of a hot objectEvery PoP refetches at once and the origin falls overSoft purge, shield, request collapsing, stale-while-revalidate
Cache fragmentationQuery parameters, Vary or cookies split one object into thousandsNormalise the key, drop tracking parameters, no Vary on cookies
DNS TTL too long at failoverClients keep going to the dead endpoint for many minutesA short TTL on failover records, and health-checked load balancers and anycast for fast cases
The origin is reachable directlyAn attacker bypasses the CDNAccept only the CDN: allow-listed addresses, a secret header or mutual TLS
Cold PoPsA new or flushed PoP sends all its traffic to the origin at onceA shield, pre-warming, rate-limited refills
A CDN or DNS provider outageThe site disappears with itA second provider for the critical records, stale-if-error, health-checked failover
An expired certificate at the edgeBrowsers refuse the siteAutomated renewal and an alert on days to expiry

Senior depth

What senior interviews ask about DNS and CDNs

Interviewer follow-upL5What happens between typing a URL and seeing the page, as far as the network is concerned?How to answer

The stub resolver and the resolver's caches answer the name, or the recursive resolver walks root, TLD and authoritative servers (about four round trips cold). The client opens TCP and a TLS session, which for a CDN ends at a nearby PoP, then sends the HTTP request. A hit is served from the PoP, and a miss goes to a shield or the origin and is stored. Mention that each step is a cache with a TTL, and say where the time goes: round trips.

Interviewer follow-upL5What is the difference between no-cache and no-store, and between max-age and s-maxage?How to answer

no-store means never keep it. no-cache means keep it but check with the origin (a conditional request with the ETag) before every use, which still saves the body when it is unchanged. max-age is how long any cache may reuse the response, and s-maxage overrides it for shared caches such as a CDN, so a CDN can hold something for five minutes that a browser rechecks after one.

Interviewer follow-upL6How do you invalidate a CDN?How to answer

Avoid it: version the URL with a content hash and serve it with a year-long immutable TTL, and keep the HTML that references it on a short TTL, so a deploy never needs a purge. Where a purge is unavoidable, purge by tag after the origin has the new version, prefer soft purge so a stale copy serves while it refreshes, rely on request collapsing and a shield so the refill does not flatten the origin, and know that a purge takes seconds to a minute to reach every PoP.

Interviewer follow-upL6You added more edge locations and the origin load went up. Why?How to answer

Each PoP now sees a smaller share of the traffic, so objects are requested less often at each one and expire or are evicted before the next request, and every PoP has to fetch each object for itself. In the test, twenty edges at a 60-second TTL sent 29.5% of requests to the origin against 21.7% for a single cache of the same size. Add a shield or regional tier so the misses merge (8.3%), lengthen the TTL where content is versioned (21.6%), and watch the hit ratio per PoP.

Interviewer follow-upL6How fast can you fail over a service with DNS, and what would you do about it?How to answer

Detection time plus up to one TTL plus the stragglers: about 90 seconds at a 60-second TTL with 30-second detection, and with 5% of resolvers keeping answers five times longer the 99th percentile was 274 seconds and the last client moved after 330. So say minutes. Keep failover records at a short TTL (lowered before planned moves), use health-checked load balancers for in-region failover and anycast where available, and keep DNS for the coarse, global decision.

Interviewer follow-upL7How would you serve personalised pages at CDN speeds?How to answer

Split the page into a cacheable shell and personal parts. Cache the shell at the edge (versioned assets, a short TTL or stale-while-revalidate on the HTML), and fetch the personal data from an API with private caching, or assemble at the edge with code that runs in the PoP using a signed cookie. Never Vary on a cookie or cache a response that contains one user's data as public, and test it by fetching as two users.

HLD

Putting it into an answer

Say where each request is answered and what its cache rules are. Users reach a nearby PoP through anycast or latency-based DNS. Static assets are hashed and immutable with a year-long TTL, the HTML and API responses have short TTLs or revalidation, misses go through a shield with request collapsing, private content uses signed URLs, and the origin accepts only the CDN. Failover is health-checked load balancing inside a region and DNS or anycast between regions, with a stated detection time and TTL and an honest statement that DNS takes minutes.

Summary

A name becomes an address through a stub resolver, a recursive resolver and the root, TLD and authoritative servers, with an answer cached at every level for its TTL. The TTL is a promise, not a command, so a DNS failover takes the detection time plus up to one TTL plus the stragglers: in the test 90 seconds at a 60-second TTL with 30 seconds of detection, but 274 seconds at the 99th percentile when 5% of resolvers keep answers five times longer. Anycast steers users to the nearest location and fails over by withdrawing a route. A CDN caches by a key and the response's Cache-Control, and origin load is requests times one minus the hit ratio. Hit ratio has diminishing returns under skewed traffic (a cache of 1% of the catalog hit 43%, 20% hit 78%), many edges dilute it (29.5% of requests reached the origin against 21.7% for one cache), and a shield (8.3%) or a long TTL on versioned URLs (21.6%, 6.4% with a shield) restores it. Prefer versioned immutable URLs to purging, purge by tag and softly when you must, keep private content out of shared caches or behind signed URLs, lock the origin to the CDN, and treat DNS and the CDN as dependencies that can fail.

Check yourself

Try answering out loud before you reveal each answer.

QuestionAn endpoint fails. Health checks need three failures ten seconds apart, and the DNS record has a 60-second TTL. About when have all well-behaved clients moved, and why does a low TTL not fix the tail?Reveal answer

Detection takes 30 seconds, and a client that refreshed just before the record changed gets the failed address again and keeps it for a full TTL, so the last compliant client moves at about 90 seconds (the test: 50% at 60 s, 99% at 89 s). Resolvers and clients that keep answers longer than the TTL decide the tail: with 5% of them stretching five times, the 99th percentile was 274 seconds.

QuestionA response carries Cache-Control: private, max-age=600. Does a CDN cache it, and for how long may a browser reuse it?Reveal answer

A CDN must not store it: private allows only the user's own browser cache. The browser may reuse it for 600 seconds without asking the origin. For something the CDN should hold, use public with s-maxage.

QuestionAt a 95% hit ratio the origin handles 50,000 requests a second. What does it handle at 99%?Reveal answer

10,000, five times less: origin load is requests times one minus the hit ratio, and the miss ratio fell from 5% to 1% (on a million requests a second). Each extra point of hit ratio near the top is worth a lot, which is why shields and long TTLs are worth the trouble.

QuestionWhy did twenty edge caches send more requests to the origin than one cache of the same size, and what fixes it?Reveal answer

Each edge sees a twentieth of the traffic, so an object is often not requested again before its 60-second TTL expires and each edge fetches it separately (29.5% of requests reached the origin against 21.7% for a single cache). A shield in front of the origin merges the misses of all edges (8.3%), and a long TTL on versioned URLs lets each edge keep objects (21.6%).

QuestionWhy prefer a hashed file name with a year-long TTL to purging?Reveal answer

A new version is a new URL, so the old copies are harmless and nothing needs to be invalidated: no purge delay across PoPs, no race with refills, no stampede on the origin, and browsers and every intermediate cache can keep the file for a year. The only thing that must stay fresh is the HTML that names the files.

Sources and further reading

Lesson 10 of 44

Nice. Lock it in, then keep going.

Up next · Lesson 11Multi-region designRunning a system in several regions: disaster recovery strategies with their RPO and RTO, replication choices and what each costs in latency and lost writes, quorum latency across regions, routing, failover headroom, and data residency.

Send a message

It goes straight to my inbox. I usually reply within a few days.