Your country

Tools that support it use your country for local currency, number formats, units and paper size. Your choice is saved only in this browser.

Type a name or a two-letter code. Use the up and down arrow keys to move through the countries, Enter to choose one and Escape to close.

System Design (High-Level Design)  Module 4 – Networking for system designers

DNS, GeoDNS and anycast for system design

How DNS resolution and TTL caching work, how GeoDNS and health-checked records steer traffic, and how anycast compares, with a failover model that runs.

  • Intermediate
  • 25 minutes
  • Examples run with Python 3.14.8, Pyodide 314.0.7, Node.js 24.21.0 and quickjs 0.32.0
  • By MySmartCoPilot
Free lesson, Pro answers: 25 minutes
Free: the whole lesson. With a pass: the model answers to its 2 interview questions.

What you will learn

  • Trace how a recursive resolver follows referrals and caches answers, aliases and NXDOMAIN for their TTLs
  • Choose a TTL from how fast a change must reach users and the query load it adds
  • Use GeoDNS, weighted and health-checked records to steer traffic
  • Calculate how much traffic still reaches a failed region after a DNS change
  • Compare DNS-based steering with anycast routing

Before you start

What you’ll learn · Before you start

What you will learn

  • Trace how a recursive resolver follows referrals and caches answers, aliases and NXDOMAIN for their TTLs
  • Choose a TTL from how fast a change must reach users and the query load it adds
  • Use GeoDNS, weighted and health-checked records to steer traffic
  • Calculate how much traffic still reaches a failed region after a DNS change
  • Compare DNS-based steering with anycast routing

Before you start

On this page

With a 300-second TTL (DNS): Time to live: the number of seconds a resolver or a client may keep a DNS answer in its cache before it must ask again. A change reaches a user only once the cached copy's TTL has run out., 90 % of the requests in this lesson’s failover model still went to a failed region a minute after it failed. DNS turns a name into an address through a chain of servers: the device asks a recursive resolver: The DNS server that answers a device's question in full. It follows referrals from the root down to the servers authoritative for the name, and caches every answer for its TTL so the next user skips the walk., which follows referrals from the root to the servers that are authoritative name server: A DNS server that holds a zone's records and answers for them itself, without asking any other server. Steering policies such as GeoDNS and health-checked failover run here. for the name, and every answer is cached for its TTL along the way. Because the authoritative server chooses each answer, it can answer differently by where the question came from (GeoDNS: Answering a DNS query by where it appears to come from, so that users get the address of a nearby region. The authoritative server sees the resolver's address, not the user's, unless the resolver passes a client subnet.), by weights, or by which regions pass their health checks. That makes DNS a traffic-steering tool, with one weakness: a change reaches users only as caches expire, so DNS failover takes minutes, not seconds. anycast: Announcing the same IP address from several sites, so that Internet routing delivers each packet to the nearest announcement by its own measure. A failed site withdraws its route, and traffic moves to the others. steers differently: many sites announce the same IP address, Internet routing delivers each packet to the nearest one, and a failed site simply withdraws its announcement.

Run a small resolver, measure what a TTL costs during a failover, and compare the two ways to steer.

A resolver walks down from the root once, then answers from its cache

The diagram shows one lookup on an empty cache, message by message:

A device asks a recursive resolver, which asks the root, then the example. servers, then the authoritative servers, and caches the answer.Phone or laptop(stub resolver)Recursive resolver(shared cache)Root serversServers ofexample.Servers ofshop.example.1. www.shop.example?2. www.shop.example?3. referral: ask example.4. www.shop.example?5. referral: ask shop.example.6. www.shop.example?7. answer, TTL 36008. answer, TTL counting down

Resolving a name on a cold cache, step by step

Text description of the diagram

A device's stub resolver asks a recursive resolver for www.shop.example (1). The recursive resolver has nothing cached, so it walks the hierarchy: - it asks a root server (2), which answers with a referral to the servers of the example. zone (3); - it asks those servers (4), which refer it to the servers of shop.example. (5); - it asks the authoritative servers of shop.example. (6), which return the answer with its TTL (7).

The recursive resolver caches the referrals and the answer, and returns the answer to the device (8). Until the TTL runs out, the next users of the same resolver get the answer from its cache without any of steps 2 to 7.

A device does not walk the DNS itself. Its The small DNS client in a device's operating system. It sends the whole question to a recursive resolver and waits for the final answer, without following any referrals itself. sends the whole question to a recursive resolver, run by the network, an ISP or a public service. The recursive resolver starts at the root, which refers it to the servers of the top-level domain, which refer it to the servers that hold the zone, and those give the answer (RFC 1034). Every referral and every answer carries a TTL, and the resolver keeps each for that long, so the next user of the same resolver skips most or all of the walk.

This resolver runs on invented zones under .example, a name reserved for documentation (RFC 6761). The address is an alias, a CNAME, that points into a second zone, as names served through a CDN often do. Each tab holds the same resolver in one of 13 languages, and all of them printed what is shown under the tabs:

One program · 13 languages A recursive resolver with a cache, six lookups

Python 3.14 · main.py

# NS delegates a zone; A and CNAME answer.
ZONES = {
    "root": {"example.": ("NS", "", 172800)},
    "example.": {"shop.example.": ("NS", "", 86400), "cdn.example.": ("NS", "", 86400)},
    "shop.example.": {"www.shop.example.": ("CNAME", "shop.cdn.example.", 3600)},
    "cdn.example.": {"shop.cdn.example.": ("A", "192.0.2.10", 60)},
}
NXDOMAIN = ("NXDOMAIN", "NXDOMAIN", 300)
cache: dict[str, tuple[str, str, int]] = {}


def resolve(name: str, now: int, asked: list[str]) -> str:
    kind, value, expiry = cache.get(name, ("", "", 0))
    if expiry <= now:
        labels = name.split(".")
        suffixes = [".".join(labels[i:]) for i in range(len(labels) - 1)]
        # Start at the closest zone whose referral is cached, else at the root.
        zone = next((s for s in suffixes if cache.get(s, ("", "", 0))[2] > now), "root")
        while True:
            asked.append(zone)
            found = next((s for s in suffixes if s in ZONES[zone]), name)
            kind, value, ttl = ZONES[zone].get(found, NXDOMAIN)
            cache[found] = (kind, value, now + ttl)
            if kind != "NS":
                break
            zone = found
    return resolve(value, now, asked) if kind == "CNAME" else value


for now in (0, 30, 90, 100, 200, 500):
    name = "www.shop.example." if now < 100 else "wwww.shop.example."
    asked: list[str] = []
    answer = resolve(name, now, asked)
    print(f"{now} s, {name} -> {answer}, asked: {', '.join(asked) or 'none'}")

In Python: next() with a default takes the first suffix that passes its test, and dict.get with NXDOMAIN as the default turns a name the zone does not hold into the negative answer.

Recorded with CPython 3.14.8 on macOS 26 arm64. It runs in your browser with Pyodide 314.0.7 (CPython 3.14.2). To run it yourself: python3 main.py

JavaScript Node 24 · main.mjs

// NS delegates a zone; A and CNAME answer.
const ZONES = {
  root: { "example.": ["NS", "", 172800] },
  "example.": { "shop.example.": ["NS", "", 86400], "cdn.example.": ["NS", "", 86400] },
  "shop.example.": { "www.shop.example.": ["CNAME", "shop.cdn.example.", 3600] },
  "cdn.example.": { "shop.cdn.example.": ["A", "192.0.2.10", 60] },
};
const NXDOMAIN = ["NXDOMAIN", "NXDOMAIN", 300];
const cache = new Map();

function resolve(name, now, asked) {
  let [kind, value, expiry] = cache.get(name) ?? ["", "", 0];
  if (expiry <= now) {
    const labels = name.split(".");
    const suffixes = labels.slice(0, -1).map((_, i) => labels.slice(i).join("."));
    // Start at the closest zone whose referral is cached, else at the root.
    let zone = suffixes.find((s) => (cache.get(s)?.[2] ?? 0) > now) ?? "root";
    for (;;) {
      asked.push(zone);
      const found = suffixes.find((s) => s in ZONES[zone]) ?? name;
      let ttl;
      [kind, value, ttl] = ZONES[zone][found] ?? NXDOMAIN;
      cache.set(found, [kind, value, now + ttl]);
      if (kind !== "NS") break;
      zone = found;
    }
  }
  return kind === "CNAME" ? resolve(value, now, asked) : value;
}

for (const now of [0, 30, 90, 100, 200, 500]) {
  const name = now < 100 ? "www.shop.example." : "wwww.shop.example.";
  const asked = [];
  const answer = resolve(name, now, asked);
  console.log(`${now} s, ${name} -> ${answer}, asked: ${asked.join(", ") || "none"}`);
}

In JavaScript: ?? supplies every default: the root when no referral is cached, the name itself when the zone holds no closer record, and NXDOMAIN when it holds nothing for the name.

Recorded with Node.js 24.21.0 LTS (V8 13.6) on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0). To run it yourself: node main.mjs

Java 25 LTS · Main.java

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Main {
  record Rec(String type, String value, int ttl) {}

  // NS delegates a zone; A and CNAME answer.
  static final Map<String, Map<String, Rec>> ZONES =
      Map.of(
          "root", Map.of("example.", new Rec("NS", "", 172800)),
          "example.",
              Map.of(
                  "shop.example.", new Rec("NS", "", 86400),
                  "cdn.example.", new Rec("NS", "", 86400)),
          "shop.example.", Map.of("www.shop.example.", new Rec("CNAME", "shop.cdn.example.", 3600)),
          "cdn.example.", Map.of("shop.cdn.example.", new Rec("A", "192.0.2.10", 60)));
  static final Rec NXDOMAIN = new Rec("NXDOMAIN", "NXDOMAIN", 300);
  static final Map<String, Rec> CACHE = new HashMap<>();

  static String resolve(String name, int now, List<String> asked) {
    Rec r = CACHE.getOrDefault(name, new Rec("", "", 0));
    if (r.ttl() <= now) {
      List<String> suffixes = new ArrayList<>();
      for (int i = 0; i < name.length(); i = name.indexOf('.', i) + 1) {
        suffixes.add(name.substring(i));
      }
      // Start at the closest zone whose referral is cached, else at the root.
      String zone =
          suffixes.stream()
              .filter(s -> CACHE.containsKey(s) && CACHE.get(s).ttl() > now)
              .findFirst()
              .orElse("root");
      while (true) {
        asked.add(zone);
        Map<String, Rec> here = ZONES.get(zone);
        String found = suffixes.stream().filter(here::containsKey).findFirst().orElse(name);
        r = here.getOrDefault(found, NXDOMAIN);
        CACHE.put(found, new Rec(r.type(), r.value(), now + r.ttl()));
        if (!r.type().equals("NS")) {
          break;
        }
        zone = found;
      }
    }
    return r.type().equals("CNAME") ? resolve(r.value(), now, asked) : r.value();
  }

  public static void main(String[] args) {
    for (int now : new int[] {0, 30, 90, 100, 200, 500}) {
      String name = now < 100 ? "www.shop.example." : "wwww.shop.example.";
      List<String> asked = new ArrayList<>();
      String answer = resolve(name, now, asked);
      String where = asked.isEmpty() ? "none" : String.join(", ", asked);
      System.out.println(now + " s, " + name + " -> " + answer + ", asked: " + where);
    }
  }
}

In Java: Map.of builds the zones, which never change; getOrDefault falls back to NXDOMAIN for a missing name, and a stream's findFirst takes the closest suffix.

Recorded with OpenJDK 25.0.4.1 LTS (Eclipse Temurin) on macOS 26 arm64. It runs in your browser with a TeaVM 0.16.0 build in QuickJS (quickjs-emscripten 0.32.0). To run it yourself: java Main.java

C++23 · main.cpp

#include <algorithm>
#include <map>
#include <print>
#include <string>
#include <vector>

using std::string;

struct Record {
  string type, value;
  int ttl; // in the cache: when it expires
};

// NS delegates a zone; A and CNAME answer.
const std::map<string, std::map<string, Record>> zones = {
    {"root", {{"example.", {"NS", "", 172800}}}},
    {"example.",
     {{"shop.example.", {"NS", "", 86400}},
      {"cdn.example.", {"NS", "", 86400}}}},
    {"shop.example.",
     {{"www.shop.example.", {"CNAME", "shop.cdn.example.", 3600}}}},
    {"cdn.example.", {{"shop.cdn.example.", {"A", "192.0.2.10", 60}}}},
};
const Record nxdomain = {"NXDOMAIN", "NXDOMAIN", 300};
std::map<string, Record> cache;

string resolve(const string &name, int now, std::vector<string> &asked) {
  Record r = cache.contains(name) ? cache.at(name) : Record{};
  if (r.ttl <= now) {
    std::vector<string> suffixes;
    for (std::size_t i = 0; i < name.size(); i = name.find('.', i) + 1)
      suffixes.push_back(name.substr(i));
    // Start at the closest zone whose referral is cached, else at the root.
    const auto known = std::ranges::find_if(suffixes, [&](const string &s) {
      return cache.contains(s) && cache.at(s).ttl > now;
    });
    string zone = known == suffixes.end() ? "root" : *known;
    for (;;) {
      asked.push_back(zone);
      const auto &here = zones.at(zone);
      const auto it = std::ranges::find_if(
          suffixes, [&](const string &s) { return here.contains(s); });
      const string found = it == suffixes.end() ? name : *it;
      r = here.contains(found) ? here.at(found) : nxdomain;
      cache[found] = {r.type, r.value, now + r.ttl};
      if (r.type != "NS")
        break;
      zone = found;
    }
  }
  return r.type == "CNAME" ? resolve(r.value, now, asked) : r.value;
}

int main() {
  for (const int now : {0, 30, 90, 100, 200, 500}) {
    const string name = now < 100 ? "www.shop.example." : "wwww.shop.example.";
    std::vector<string> asked;
    const string answer = resolve(name, now, asked);
    string where = asked.empty() ? "none" : asked[0];
    for (std::size_t i = 1; i < asked.size(); i++)
      where += ", " + asked[i];
    std::println("{} s, {} -> {}, asked: {}", now, name, answer, where);
  }
}

In C++: std::ranges::find_if returns an iterator, so each search compares it with suffixes.end() before it reads the suffix it found.

Recorded with Apple clang 21.0.0 (C++23) and GCC 16.2.0 on macOS 26 arm64. It runs in your browser with Clang in WebAssembly (YoWASP) 22.0.0-git20542-10. To run it yourself: clang++ -std=c++23 -O2 -Wall -Wextra -Werror -pedantic -fsanitize=address,undefined main.cpp -o main && ./main

C# 14 · .NET 10 · app.cs

// NS delegates a zone; A and CNAME answer.
var zones = new Dictionary<string, Dictionary<string, Rec>>
{
    ["root"] = new() { ["example."] = new("NS", "", 172800) },
    ["example."] = new()
    {
        ["shop.example."] = new("NS", "", 86400),
        ["cdn.example."] = new("NS", "", 86400),
    },
    ["shop.example."] = new() { ["www.shop.example."] = new("CNAME", "shop.cdn.example.", 3600) },
    ["cdn.example."] = new() { ["shop.cdn.example."] = new("A", "192.0.2.10", 60) },
};
var nxdomain = new Rec("NXDOMAIN", "NXDOMAIN", 300);
var cache = new Dictionary<string, Rec>();

foreach (int now in new[] { 0, 30, 90, 100, 200, 500 })
{
    string name = now < 100 ? "www.shop.example." : "wwww.shop.example.";
    var asked = new List<string>();
    string answer = Resolve(name, now, asked);
    string where = asked.Count > 0 ? string.Join(", ", asked) : "none";
    Console.WriteLine($"{now} s, {name} -> {answer}, asked: {where}");
}

string Resolve(string name, int now, List<string> asked)
{
    Rec r = cache.GetValueOrDefault(name) ?? new("", "", 0);
    if (r.Ttl <= now)
    {
        var suffixes = Enumerable.Range(0, name.Length)
            .Where(i => i == 0 || name[i - 1] == '.')
            .Select(i => name[i..])
            .ToList();
        // Start at the closest zone whose referral is cached, else at the root.
        string zone = suffixes.FirstOrDefault(s => cache.GetValueOrDefault(s)?.Ttl > now) ?? "root";
        while (true)
        {
            asked.Add(zone);
            string found = suffixes.FirstOrDefault(zones[zone].ContainsKey) ?? name;
            r = zones[zone].GetValueOrDefault(found) ?? nxdomain;
            cache[found] = r with { Ttl = now + r.Ttl };
            if (r.Type != "NS")
            {
                break;
            }
            zone = found;
        }
    }
    return r.Type == "CNAME" ? Resolve(r.Value, now, asked) : r.Value;
}

record Rec(string Type, string Value, int Ttl);

In C#: Resolve is a local function after the top-level statements. It uses the zones and the cache declared there, so it cannot be static; r with { Ttl = … } copies a record with its expiry.

Recorded with C# 14 on .NET 10.0.12 (SDK 10.0.401) on macOS 26 arm64. It runs in your browser with the .NET runtime for WebAssembly 10.0.12. To run it yourself: dotnet run app.cs

C23 · main.c

C is left out of this example: C's standard library has no map or growable list, so the zones and the cache would be arrays searched by hand, another design.

PHP 8.5 · main.php

<?php

declare(strict_types=1);

// NS delegates a zone; A and CNAME answer.
const ZONES = [
    'root' => ['example.' => ['NS', '', 172800]],
    'example.' => ['shop.example.' => ['NS', '', 86400], 'cdn.example.' => ['NS', '', 86400]],
    'shop.example.' => ['www.shop.example.' => ['CNAME', 'shop.cdn.example.', 3600]],
    'cdn.example.' => ['shop.cdn.example.' => ['A', '192.0.2.10', 60]],
];
const NXDOMAIN = ['NXDOMAIN', 'NXDOMAIN', 300];

/** @param list<string> $asked */
function resolve(string $name, int $now, array &$asked): string
{
    static $cache = [];
    [$kind, $value, $expiry] = $cache[$name] ?? ['', '', 0];
    if ($expiry <= $now) {
        $labels = explode('.', $name);
        $suffixes = [];
        for ($i = 0; $i < count($labels) - 1; $i++) {
            $suffixes[] = implode('.', array_slice($labels, $i));
        }
        // Start at the closest zone whose referral is cached, else at the root.
        $known = array_filter($suffixes, fn(string $s): bool => ($cache[$s][2] ?? 0) > $now);
        $zone = array_values($known)[0] ?? 'root';
        while (true) {
            $asked[] = $zone;
            $here = array_filter($suffixes, fn(string $s): bool => isset(ZONES[$zone][$s]));
            $found = array_values($here)[0] ?? $name;
            [$kind, $value, $ttl] = ZONES[$zone][$found] ?? NXDOMAIN;
            $cache[$found] = [$kind, $value, $now + $ttl];
            if ($kind !== 'NS') {
                break;
            }
            $zone = $found;
        }
    }
    return $kind === 'CNAME' ? resolve($value, $now, $asked) : $value;
}

foreach ([0, 30, 90, 100, 200, 500] as $now) {
    $name = $now < 100 ? 'www.shop.example.' : 'wwww.shop.example.';
    $asked = [];
    $answer = resolve($name, $now, $asked);
    $where = $asked === [] ? 'none' : implode(', ', $asked);
    echo "{$now} s, {$name} -> {$answer}, asked: {$where}\n";
}

In PHP: The cache is a static variable of resolve, kept from one call to the next; array_filter with an arrow function keeps the matching suffixes, and array_values(…)[0] takes the first.

Recorded with PHP 8.5.11 (CLI) on macOS 26 arm64. It runs in your browser with php-wasm 0.2.0 (PHP 8.5.2). To run it yourself: php main.php

Rust 1.99 · main.rs

use std::collections::HashMap;

type Name = &'static str;
type Record = (Name, Name, u32); // type, value, TTL (in the cache: when it expires)
type Cache = HashMap<Name, Record>;
const NXDOMAIN: Record = ("NXDOMAIN", "NXDOMAIN", 300);

/// NS delegates a zone; A and CNAME answer.
fn zone_record(zone: Name, name: Name) -> Option<Record> {
    match (zone, name) {
        ("root", "example.") => Some(("NS", "", 172800)),
        ("example.", "shop.example." | "cdn.example.") => Some(("NS", "", 86400)),
        ("shop.example.", "www.shop.example.") => Some(("CNAME", "shop.cdn.example.", 3600)),
        ("cdn.example.", "shop.cdn.example.") => Some(("A", "192.0.2.10", 60)),
        _ => None,
    }
}

fn resolve(cache: &mut Cache, name: Name, now: u32, asked: &mut Vec<Name>) -> Name {
    let mut r = cache.get(name).copied().unwrap_or(("", "", 0));
    if r.2 <= now {
        let suffixes: Vec<Name> =
            std::iter::successors(Some(name), |s| s.split_once('.').map(|(_, rest)| rest))
                .filter(|s| !s.is_empty())
                .collect();
        // Start at the closest zone whose referral is cached, else at the root.
        let fresh = |s: &&Name| cache.get(*s).is_some_and(|c| c.2 > now);
        let mut zone = suffixes.iter().find(fresh).copied().unwrap_or("root");
        loop {
            asked.push(zone);
            let held = |s: &Name| zone_record(zone, s).is_some();
            let found = suffixes.iter().copied().find(held).unwrap_or(name);
            r = zone_record(zone, found).unwrap_or(NXDOMAIN);
            cache.insert(found, (r.0, r.1, now + r.2));
            if r.0 != "NS" {
                break;
            }
            zone = found;
        }
    }
    match r {
        ("CNAME", alias, _) => resolve(cache, alias, now, asked),
        (_, value, _) => value,
    }
}

fn main() {
    let mut cache = Cache::new();
    for now in [0, 30, 90, 100, 200, 500] {
        let name = if now < 100 {
            "www.shop.example."
        } else {
            "wwww.shop.example."
        };
        let mut asked = Vec::new();
        let answer = resolve(&mut cache, name, now, &mut asked);
        let mut place = asked.join(", ");
        if place.is_empty() {
            place = "none".to_string();
        }
        println!("{now} s, {name} -> {answer}, asked: {place}");
    }
}

In Rust: The zones are a match on (zone, name), a lookup table the compiler checks; the cache is passed in as &mut, the one writer the borrow checker allows at a time.

Recorded with rustc 1.99.0 (edition 2024) on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: rustc --edition 2024 -O main.rs && ./main

TypeScript 6.0 · main.ts

// NS delegates a zone; A and CNAME answer.
type Rec = [type: string, value: string, ttl: number];
const ZONES: Record<string, Record<string, Rec>> = {
  root: { "example.": ["NS", "", 172800] },
  "example.": { "shop.example.": ["NS", "", 86400], "cdn.example.": ["NS", "", 86400] },
  "shop.example.": { "www.shop.example.": ["CNAME", "shop.cdn.example.", 3600] },
  "cdn.example.": { "shop.cdn.example.": ["A", "192.0.2.10", 60] },
};
const NXDOMAIN: Rec = ["NXDOMAIN", "NXDOMAIN", 300];
const cache = new Map<string, Rec>();

function resolve(name: string, now: number, asked: string[]): string {
  let [kind, value, expiry]: Rec = cache.get(name) ?? ["", "", 0];
  if (expiry <= now) {
    const labels = name.split(".");
    const suffixes = labels.slice(0, -1).map((_, i) => labels.slice(i).join("."));
    // Start at the closest zone whose referral is cached, else at the root.
    let zone = suffixes.find((s) => (cache.get(s)?.[2] ?? 0) > now) ?? "root";
    for (;;) {
      asked.push(zone);
      const found = suffixes.find((s) => s in ZONES[zone]) ?? name;
      let ttl: number;
      [kind, value, ttl] = ZONES[zone][found] ?? NXDOMAIN;
      cache.set(found, [kind, value, now + ttl]);
      if (kind !== "NS") break;
      zone = found;
    }
  }
  return kind === "CNAME" ? resolve(value, now, asked) : value;
}

for (const now of [0, 30, 90, 100, 200, 500]) {
  const name = now < 100 ? "www.shop.example." : "wwww.shop.example.";
  const asked: string[] = [];
  const answer = resolve(name, now, asked);
  console.log(`${now} s, ${name} -> ${answer}, asked: ${asked.join(", ") || "none"}`);
}

In TypeScript: A labelled tuple type names the three fields of a record; everything else is the JavaScript program.

Recorded with TypeScript 6.0.3 (strict), run by Node.js 24.21.0 on macOS 26 arm64. It runs in your browser with QuickJS (quickjs-emscripten 0.32.0) after Sucrase 3.35.1. To run it yourself: npx -p typescript@6.0.3 tsc --noEmit --strict main.ts && node main.ts

Go 1.27 · main.go

package main

import (
	"cmp"
	"fmt"
	"strings"
)

type record struct {
	kind, value string
	ttl         int // in the cache: when it expires
}

// NS delegates a zone; A and CNAME answer.
var zones = map[string]map[string]record{
	"root":          {"example.": {"NS", "", 172800}},
	"example.":      {"shop.example.": {"NS", "", 86400}, "cdn.example.": {"NS", "", 86400}},
	"shop.example.": {"www.shop.example.": {"CNAME", "shop.cdn.example.", 3600}},
	"cdn.example.":  {"shop.cdn.example.": {"A", "192.0.2.10", 60}},
}

var nxdomain = record{"NXDOMAIN", "NXDOMAIN", 300}
var cache = map[string]record{}

func resolve(name string, now int, asked *[]string) string {
	r := cache[name]
	if r.ttl <= now {
		var suffixes []string
		for s := name; s != ""; _, s, _ = strings.Cut(s, ".") {
			suffixes = append(suffixes, s)
		}
		// Start at the closest zone whose referral is cached, else at the root.
		zone := "root"
		for _, s := range suffixes {
			if cache[s].ttl > now {
				zone = s
				break
			}
		}
		for {
			*asked = append(*asked, zone)
			found := name
			for _, s := range suffixes {
				if _, ok := zones[zone][s]; ok {
					found = s
					break
				}
			}
			var ok bool
			if r, ok = zones[zone][found]; !ok {
				r = nxdomain
			}
			cache[found] = record{r.kind, r.value, now + r.ttl}
			if r.kind != "NS" {
				break
			}
			zone = found
		}
	}
	if r.kind == "CNAME" {
		return resolve(r.value, now, asked)
	}
	return r.value
}

func main() {
	for _, now := range []int{0, 30, 90, 100, 200, 500} {
		name := "www.shop.example."
		if now >= 100 {
			name = "wwww.shop.example."
		}
		var asked []string
		answer := resolve(name, now, &asked)
		where := cmp.Or(strings.Join(asked, ", "), "none")
		fmt.Printf("%d s, %s -> %s, asked: %s\n", now, name, answer, where)
	}
}

In Go: A missing map key reads as the zero value, so a name that was never cached has ttl 0 and counts as expired; cmp.Or prints none when no zone was asked.

Recorded with Go 1.27.1 on macOS 26 arm64. It runs in your browser with the Go compiler in WebAssembly 1.27.1. To run it yourself: go run main.go

Swift 6.4 · main.swift

typealias Record = (type: String, value: String, ttl: Int)

// NS delegates a zone; A and CNAME answer.
let zones: [String: [String: Record]] = [
  "root": ["example.": ("NS", "", 172800)],
  "example.": ["shop.example.": ("NS", "", 86400), "cdn.example.": ("NS", "", 86400)],
  "shop.example.": ["www.shop.example.": ("CNAME", "shop.cdn.example.", 3600)],
  "cdn.example.": ["shop.cdn.example.": ("A", "192.0.2.10", 60)],
]
let nxdomain: Record = ("NXDOMAIN", "NXDOMAIN", 300)

struct Resolver {
  var cache: [String: Record] = [:]

  mutating func resolve(_ name: String, at now: Int, asked: inout [String]) -> String {
    var record = cache[name] ?? ("", "", 0)
    if record.ttl <= now {
      let labels = name.split(separator: ".")
      let suffixes = labels.indices.map { labels[$0...].joined(separator: ".") + "." }
      // Start at the closest zone whose referral is cached, else at the root.
      var zone = suffixes.first { (cache[$0]?.ttl ?? 0) > now } ?? "root"
      while true {
        asked.append(zone)
        let found = suffixes.first { zones[zone]?[$0] != nil } ?? name
        record = zones[zone]?[found] ?? nxdomain
        cache[found] = (record.type, record.value, now + record.ttl)
        if record.type != "NS" { break }
        zone = found
      }
    }
    return record.type == "CNAME" ? resolve(record.value, at: now, asked: &asked) : record.value
  }
}

var resolver = Resolver()
for now in [0, 30, 90, 100, 200, 500] {
  let name = now < 100 ? "www.shop.example." : "wwww.shop.example."
  var asked: [String] = []
  let answer = resolver.resolve(name, at: now, asked: &asked)
  let place = asked.isEmpty ? "none" : asked.joined(separator: ", ")
  print("\(now) s, \(name) -> \(answer), asked: \(place)")
}

In Swift: The resolver is a struct with a mutating method, so its cache is a value it owns, and zones[zone]?[found] chains two optional dictionary lookups.

Recorded with Apple Swift 6.4 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: swiftc -O main.swift -o main && ./main

Ruby 4.0 · main.rb

# frozen_string_literal: true

# NS delegates a zone; A and CNAME answer.
ZONES = {
  'root' => { 'example.' => ['NS', '', 172_800] },
  'example.' => { 'shop.example.' => ['NS', '', 86_400], 'cdn.example.' => ['NS', '', 86_400] },
  'shop.example.' => { 'www.shop.example.' => ['CNAME', 'shop.cdn.example.', 3600] },
  'cdn.example.' => { 'shop.cdn.example.' => ['A', '192.0.2.10', 60] }
}.freeze
NXDOMAIN = ['NXDOMAIN', 'NXDOMAIN', 300].freeze

# A recursive resolver whose cache keeps answers and referrals until they expire.
class Resolver
  def initialize
    @cache = {}
  end

  def resolve(name, now, asked)
    kind, value, expiry = @cache.fetch(name, ['', '', 0])
    kind, value = walk(name, now, asked) if expiry <= now
    kind == 'CNAME' ? resolve(value, now, asked) : value
  end

  private

  def walk(name, now, asked)
    suffixes = (0...name.count('.')).map { |i| name.split('.', i + 1).last }
    zone = start(suffixes, now)
    loop do
      asked << zone
      found = suffixes.find { |s| ZONES[zone].key?(s) } || name
      kind, value = store(found, ZONES[zone].fetch(found, NXDOMAIN), now)
      return [kind, value] unless kind == 'NS'

      zone = found
    end
  end

  # The closest zone whose referral is cached, else the root.
  def start(suffixes, now)
    suffixes.find { |s| @cache.dig(s, 2).to_i > now } || 'root'
  end

  def store(name, record, now)
    kind, value, ttl = record
    @cache[name] = [kind, value, now + ttl]
  end
end

resolver = Resolver.new
[0, 30, 90, 100, 200, 500].each do |now|
  name = now < 100 ? 'www.shop.example.' : 'wwww.shop.example.'
  asked = []
  answer = resolver.resolve(name, now, asked)
  puts "#{now} s, #{name} -> #{answer}, asked: #{asked.empty? ? 'none' : asked.join(', ')}"
end

In Ruby: split('.', i + 1).last gives each suffix, and the walk is split into short methods, as RuboCop asks; dig(s, 2).to_i reads a cached expiry, or 0 when there is none.

Recorded with CRuby 4.0.7 on macOS 26 arm64. It runs in your browser with ruby.wasm 2.10.1 (Ruby 4.0.0). To run it yourself: ruby main.rb

Kotlin 2.4 · Main.kt

data class Rec(
    val type: String,
    val value: String,
    val ttl: Int,
)

// NS delegates a zone; A and CNAME answer.
val zones =
    mapOf(
        "root" to mapOf("example." to Rec("NS", "", 172800)),
        "example." to
            mapOf("shop.example." to Rec("NS", "", 86400), "cdn.example." to Rec("NS", "", 86400)),
        "shop.example." to mapOf("www.shop.example." to Rec("CNAME", "shop.cdn.example.", 3600)),
        "cdn.example." to mapOf("shop.cdn.example." to Rec("A", "192.0.2.10", 60)),
    )
val nxdomain = Rec("NXDOMAIN", "NXDOMAIN", 300)
val cache = mutableMapOf<String, Rec>()

fun resolve(
    name: String,
    now: Int,
    asked: MutableList<String>,
): String {
    var r = cache[name] ?: Rec("", "", 0)
    if (r.ttl <= now) {
        val labels = name.split(".").dropLast(1)
        val suffixes = labels.indices.map { labels.drop(it).joinToString(".") + "." }
        // Start at the closest zone whose referral is cached, else at the root.
        var zone = suffixes.firstOrNull { (cache[it]?.ttl ?: 0) > now } ?: "root"
        while (true) {
            asked.add(zone)
            val here = zones.getValue(zone)
            val found = suffixes.firstOrNull { it in here } ?: name
            r = here[found] ?: nxdomain
            cache[found] = r.copy(ttl = now + r.ttl)
            if (r.type != "NS") break
            zone = found
        }
    }
    return if (r.type == "CNAME") resolve(r.value, now, asked) else r.value
}

fun main() {
    for (now in listOf(0, 30, 90, 100, 200, 500)) {
        val name = if (now < 100) "www.shop.example." else "wwww.shop.example."
        val asked = mutableListOf<String>()
        val answer = resolve(name, now, asked)
        println("$now s, $name -> $answer, asked: ${asked.joinToString(", ").ifEmpty { "none" }}")
    }
}

In Kotlin: copy(ttl = now + r.ttl) stores a record with its expiry instead of its TTL, and ifEmpty prints none when no zone was asked.

Recorded with Kotlin 2.4.20 on Java 25.0.4.1 on macOS 26 arm64. It runs in your browser with a WebAssembly build on the WASI runner (browser_wasi_shim 0.4.2). To run it yourself: kotlinc Main.kt -include-runtime -d main.jar && java -jar main.jar

Dart 3.13 · main.dart

typedef Rec = (String type, String value, int ttl);

// NS delegates a zone; A and CNAME answer.
const zones = <String, Map<String, Rec>>{
  'root': {'example.': ('NS', '', 172800)},
  'example.': {
    'shop.example.': ('NS', '', 86400),
    'cdn.example.': ('NS', '', 86400),
  },
  'shop.example.': {'www.shop.example.': ('CNAME', 'shop.cdn.example.', 3600)},
  'cdn.example.': {'shop.cdn.example.': ('A', '192.0.2.10', 60)},
};
const Rec nxdomain = ('NXDOMAIN', 'NXDOMAIN', 300);
final cache = <String, Rec>{};

String resolve(String name, int now, List<String> asked) {
  var (kind, value, expiry) = cache[name] ?? ('', '', 0);
  if (expiry <= now) {
    final labels = name.split('.')..removeLast();
    final suffixes = [
      for (var i = 0; i < labels.length; i++) '${labels.skip(i).join('.')}.',
    ];
    // Start at the closest zone whose referral is cached, else at the root.
    var zone = suffixes.firstWhere(
      (s) => (cache[s]?.$3 ?? 0) > now,
      orElse: () => 'root',
    );
    while (true) {
      asked.add(zone);
      final here = zones[zone] ?? const {};
      final found = suffixes.firstWhere(here.containsKey, orElse: () => name);
      final int ttl;
      (kind, value, ttl) = here[found] ?? nxdomain;
      cache[found] = (kind, value, now + ttl);
      if (kind != 'NS') break;
      zone = found;
    }
  }
  return kind == 'CNAME' ? resolve(value, now, asked) : value;
}

void main() {
  for (final now in [0, 30, 90, 100, 200, 500]) {
    final name = now < 100 ? 'www.shop.example.' : 'wwww.shop.example.';
    final asked = <String>[];
    final answer = resolve(name, now, asked);
    final place = asked.isEmpty ? 'none' : asked.join(', ');
    print('$now s, $name -> $answer, asked: $place');
  }
}

In Dart: A record pattern assigns kind, value and ttl in one statement, and firstWhere with orElse gives the default when no suffix matches.

Recorded with Dart 3.13.5 on macOS 26 arm64. It runs in your browser with a WebAssembly build by dart2wasm 3.13.5. To run it yourself: dart run main.dart

What every language printed

0 s, www.shop.example. -> 192.0.2.10, asked: root, example., shop.example., example., cdn.example.
30 s, www.shop.example. -> 192.0.2.10, asked: none
90 s, www.shop.example. -> 192.0.2.10, asked: cdn.example.
100 s, wwww.shop.example. -> NXDOMAIN, asked: shop.example.
200 s, wwww.shop.example. -> NXDOMAIN, asked: none
500 s, wwww.shop.example. -> NXDOMAIN, asked: shop.example.

Read it line by line:

  • The first lookup asks five servers. Two of them, the root and the example. servers, only refer it onward. The alias costs a second walk, but a shorter one, because the referral to example. is already cached.
  • Thirty seconds later nothing is asked. Both records come from the cache, with their TTLs counting down.
  • At 90 seconds one server is asked. The address had a TTL of 60 seconds and has expired, while the alias, with a TTL of 3,600, has not. Each link of a chain expires on its own clock.
  • A typo is cached too. A name that does not exist gets an NXDOMAIN answer, and the zone’s Start of authority: the record at the top of every zone. Among its fields is the limit on how long a resolver may cache the answer that a name in the zone does not exist. says how long that “no” may be cached (RFC 2308), here 300 seconds. The second typo is answered from the cache; the third, after the 300 seconds, asks again.

Step through the same six lookups and watch the resolver’s cache: each referral, the alias, the address and the “no” count down on their own clocks.

Interactive · step by step Six lookups through one resolver's cache Step through the six lookups of the program above. The sub-labels show what the resolver has cached and how long each part has left.
Six lookups through one resolver's cache, step 11 of 11. Showing Phone (NXDOMAIN), Recursive resolver (NXDOMAIN 300 s), Root servers, example. servers (servers known, 2 days), shop.example. servers (servers known, 1 day), cdn.example. servers (servers known, 1 day). In focus: shop.example. servers.PhoneNXDOMAINRecursive resolverNXDOMAIN 300 sRoot serversexample. serversservers known, 2 daysshop.example. serversservers known, 1 daycdn.example. serversservers known, 1 daywwww.shop.example?

The drawing shows the whole scene; its 11 steps are listed below.

Every step as text
  1. 0 s: nothing cached. At 0 s a phone asks its recursive resolver for www.shop.example. The cache is empty, so the resolver starts at the root, whose servers every resolver knows from the start.
  2. The root refers it on. The root does not hold the name, but it knows who holds example. and answers with a referral. The resolver caches it for 172,800 seconds, two days.
  3. A second referral. The servers of example. refer the resolver to the servers of shop.example., a referral it keeps for 86,400 seconds, one day.
  4. An alias, not an address. shop.example. answers with a CNAME. www.shop.example. is an alias of shop.cdn.example., valid for 3,600 seconds, and the resolver now has a second name to resolve.
  5. A shorter second walk. The referral to example. is already cached, so the walk for shop.cdn.example. skips the root. The servers of example. refer the resolver to cdn.example.
  6. Five servers, one address. cdn.example. returns the address 192.0.2.10, valid for 60 seconds. Five servers were asked for one name, as the program printed, and the phone has its answer.
  7. 30 s: nothing is asked. Thirty seconds later both records are still in the cache, with 3,570 and 30 seconds left. The resolver answers at once and asks no server.
  8. 90 s: one link expired. At 90 s the address has expired but the alias has not, so the resolver asks only cdn.example., whose referral it still holds. The fresh address starts another 60 seconds.
  9. 100 s: a typo. A typo, wwww.shop.example., goes straight to shop.example., whose servers the resolver knows. No such name exists, and the zone's SOA lets the resolver cache that NXDOMAIN for 300 seconds.
  10. 200 s: the no is cached. At 200 s the same typo is answered from the cache, with 200 seconds of its negative TTL left. No server is asked.
  11. 500 s: asked again. At 500 s the negative answer has expired, so the resolver asks shop.example. again and caches a fresh NXDOMAIN for another 300 seconds.

One fetch of the alias served all three lookups of www.shop.example., the address had to be fetched twice, and the typo’s NXDOMAIN lived exactly its 300 seconds. negative caching: Keeping the answer that a name does not exist (NXDOMAIN) in a cache, for as long as the zone's SOA record allows. A name looked up before it was created can stay missing for that long. has a practical edge: if someone looks up a record before you create it, resolvers may keep answering “no such name” for the negative TTL after you have added it.

DNS Lookup Look up a real name's records and see each record's TTL as a public resolver reports it.

Key idea

A resolver starts at the closest zone whose servers it already knows, and everything it learns on the way, a referral, an alias, an address or a “no”, stays in its cache for its own TTL.

Checkpoint

Check: Recursive resolution and caching

  1. Question 1 of 2 In the program's first lookup the resolver walked the root, example. and shop.example. and got an alias. Which servers did it then ask for shop.cdn.example., the name the alias points to?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: example., then cdn.example.

    A resolver starts at the closest zone whose servers it knows. After the first walk it knew example., so the second walk asked example. for a referral to cdn.example. and then cdn.example. for the address: five servers in all, as the program printed.

  2. Question 2 of 2 At 100 s the resolver cached NXDOMAIN for a typo, and the zone's SOA allows 300 seconds for that answer. From what time on does a lookup of the same typo ask the zone again?

    Type a number.

    A hint

    A negative answer is kept for its TTL from the moment it was cached.

    Show the answer: Question 2 of 2

    Answer: 400 s

    100 + 300 = 400 s. The lookup at 200 s was answered from the cache with 200 seconds left; the program's lookup at 500 s found the answer expired and asked shop.example. again.

TTLs trade the speed of change against load

The TTL is a limit on how long a record may be kept in a cache, and the DNS specification suggests that for a typical host it can be days. It also gives the standard trick for planned changes: lower the TTL before a change you can anticipate, then raise it again afterwards (RFC 1034). Lower it at least one old TTL ahead of time, so that the long-lived copies are gone when the change happens.

The failover model later in this lesson counts 20,000 resolvers that keep the name in their caches all day. Here is what three TTLs cost them and what they buy:

TTL Queries a second at the DNS servers Longest a cached copy outlives a change
30 s 667 30 s
300 s 67 5 min
3,600 s 6 1 hour

Each row is the same rule twice: every resolver asks again once per TTL, and a copy fetched just before a change lives one TTL more. A short TTL has costs:

  • Load on the DNS servers rises in proportion. Every resolver that keeps the name warm asks again once per TTL, so going from 3,600 seconds to 30 multiplies those queries by 120.
  • Users wait more often. Each lookup that misses the cache costs round trips, which the previous lessons counted.
  • Not every client obeys. Some applications and devices keep an address longer than its TTL. Resolvers may also keep serving an expired answer, with a short TTL attached, when they cannot reach the authoritative servers to refresh it; the standard for this suggests keeping such stale data for 1 to 3 days at most (RFC 8767). That makes DNS more resilient when its servers are under attack, and it means an old answer can outlive its TTL.

Checkpoint

Check: What a TTL trades

  1. Question 1 of 2 20,000 resolvers keep a name in their caches all day. With a TTL of 120 seconds, about how many queries a second reach the name's DNS servers?

    Type a number.

    A hint

    Each resolver that keeps the name warm asks again once per TTL.

    Show the answer: Question 1 of 2

    Answer: 167 queries a second (anything from 166 to 168 counts)

    20,000 ÷ 120 ≈ 167 queries a second. At 30 seconds it is 667 and at an hour about 6, the numbers in the table.

  2. Question 2 of 2 A record has a TTL of 3,600 seconds, and you will move the service to new addresses. When must you lower the TTL to 60 seconds, at the latest, so that no cache keeps the old address for more than a minute after the move?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: At least 3,600 seconds, one old TTL, before the move

    RFC 1034 suggests lowering the TTL before a change you can anticipate and raising it again afterwards. Lower it at least one old TTL ahead, so the long-lived copies have expired by the time of the change.

DNS steers by answering each query differently

An authoritative server can apply a policy to every query instead of returning one fixed answer. Managed DNS services offer these policies by name; one provider’s documentation lists simple, failover, geolocation, geoproximity, latency-based, IP-based, multivalue and weighted routing (Route 53 Developer Guide). For a design, four of them matter most:

  • GeoDNS answers by the location the query appears to come from, so users reach a nearby region.
  • Latency-based answers with the region that measured fastest for that part of the network.
  • Weighted splits answers by percentages, which is how traffic moves gradually to a new region or a canary.
  • Failover answers with a standby only while health checks find the primary unhealthy.

GeoDNS has a blind spot: the authoritative server sees the address of the recursive resolver, not of the user. A user whose resolver is far away, or whose resolver’s address is placed elsewhere, gets an answer for the wrong place. EDNS Client Subnet lets a resolver pass on part of the user’s address, recommended at 24 bits for IPv4 and 56 for IPv6, to get a tailored answer. It has costs: answers must be cached per subnet, and the user’s network becomes visible to every server involved, which is why its own specification recommends shipping it switched off and enabling it only where it clearly helps (RFC 7871).

Step through one lookup by a user whose resolver is on another continent, first without a client subnet and then with one:

Interactive · message by message GeoDNS without and with a client subnet Step through one lookup by a user in Chennai whose resolver is in Frankfurt. The places and addresses are made up for the example.
GeoDNS without and with a client subnet, step 6 of 6. Messages so far: User in Chennai to Resolver: www.shop.example?; Resolver to GeoDNS server: www.shop.example?; GeoDNS server to Resolver: Europe region; Resolver to GeoDNS server: same, + 198.51.100.0/24; GeoDNS server to Resolver: Mumbai, for this /24.User in Chennai198.51.100.77Resolverin FrankfurtGeoDNS serverauthoritativewww.shop.example?www.shop.example?Europe regionsame, + 198.51.100.0/24Mumbai, for this /24one cache entry per subnet

The drawing shows the whole scene; its 6 steps are listed below.

Every step as text
  1. The question goes to Frankfurt. The user's office VPN sends every DNS query to the company's resolver in Frankfurt. The user is in Chennai, where the service also has a region, in Mumbai.
  2. GeoDNS sees the resolver. Without a client subnet, the authoritative server sees only where the query comes from, the resolver's address in Frankfurt. It cannot tell where the user is.
  3. An answer for Europe. GeoDNS answers with the Europe region, right for the resolver and wrong for the user, whose requests now cross two continents.
  4. Now with a client subnet. With EDNS Client Subnet the resolver adds the first 24 bits of the user's address, 198.51.100.0/24, as the standard recommends for IPv4. The last 8 bits are never sent.
  5. An answer for Mumbai. The server answers with the Mumbai region and says which subnet the answer is for. The resolver may give that answer only to users of that subnet.
  6. What the subnet costs. Users of other subnets get answers of their own, so one name can fill many cache entries, and every server on the way learns part of the user's address. The standard says to ship it switched off and enable it only where it clearly helps.

With 24 bits of the user’s address the answer fitted the user, at the price of a cache entry per subnet and a little of the user’s privacy. Health-checked failover adds its own delay. A checker has to see several failed probes in a row before it changes the answer, and only then do the caches start to expire.

Checkpoint

Check: Steering with DNS answers

  1. Question 1 of 2 In the figure, GeoDNS sent a user in Chennai to Europe because the user's resolver is in Frankfurt. Which change gives that user the Mumbai region?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The resolver sends EDNS Client Subnet with the first 24 bits of the user's address

    The authoritative server sees the address of the recursive resolver, not of the user. EDNS Client Subnet passes part of the user's address, recommended at 24 bits for IPv4, so that the answer can fit the user.

  2. Question 2 of 2 What does EDNS Client Subnet cost? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 2 of 2

    Answer:

    • Answers are cached per subnet, so one name can fill many cache entries
    • Every server involved in the lookup learns part of the user's address

    RFC 7871 names both costs, a much larger cache and a privacy cost, and recommends shipping the option switched off and enabling it only where it clearly helps.

DNS failover takes minutes, because caches must expire

Two regions serve users; one fails at the evening peak. How many requests still go to it, and for how long? This model needs only the TTL, the time the health check needs to notice, and a small share of clients that ignore the TTL. Each of those numbers is an assumption, and the model says so:

Requests still sent to a failed region, by TTL Python · failover/ttl_failover_sim.py
"""How long requests keep going to a failed region after DNS fails over, for three TTLs. A model: every number at
the top is an assumption, and each one says so."""

DETECT_S = 30          # assumption: the health check probes every 10 s and needs 3 failures in a row
STICKY_SHARE = 0.02    # assumption: 2 % of clients keep an address for at least 30 minutes, whatever the TTL
STICKY_S = 1800
REQUESTS_PER_S = 2000  # assumption: the requests a second that the failed region was serving
RESOLVERS = 20000      # assumption: resolvers that keep the name in their caches all day
TTLS = (30, 300, 3600)


def still_sent(t, ttl):
    """Share of requests still sent to the failed region t seconds after it failed."""
    if t < DETECT_S:
        return 1.0  # the record still names the failed region
    since = t - DETECT_S
    # A resolver's cached answer was fetched at a random moment during the last TTL, so after the change the share
    # of caches still holding the old answer falls in a straight line to zero over one TTL.
    obeying = max(0.0, 1 - since / ttl)
    sticky = max(0.0, 1 - since / max(ttl, STICKY_S))
    return (1 - STICKY_SHARE) * obeying + STICKY_SHARE * sticky


def label(seconds):
    return f"{seconds // 60} min" if seconds % 60 == 0 else f"{seconds} s"


print(f"Share of requests still sent to the failed region ({DETECT_S} s until the health check notices):")
print(f"{'after':>8}" + "".join(f"{'TTL ' + str(ttl) + ' s':>13}" for ttl in TTLS))
for t in (15, 30, 45, 60, 120, 300, 600, 1800, 3600):
    print(f"{label(t):>8}" + "".join(f"{still_sent(t, ttl):>13.1%}" for ttl in TTLS))

failed = [sum(still_sent(t, ttl) for t in range(0, 4 * 3600)) * REQUESTS_PER_S for ttl in TTLS]
print()
print(f"{'requests sent to the failed region in all':<44}" + "".join(f"{n:>13,.0f}" for n in failed))
print(f"{'queries a second at the DNS servers':<44}" + "".join(f"{RESOLVERS / ttl:>13,.0f}" for ttl in TTLS))

Output

Share of requests still sent to the failed region (30 s until the health check notices):
   after     TTL 30 s    TTL 300 s   TTL 3600 s
    15 s       100.0%       100.0%       100.0%
    30 s       100.0%       100.0%       100.0%
    45 s        51.0%        95.1%        99.6%
   1 min         2.0%        90.2%        99.2%
   2 min         1.9%        70.5%        97.5%
   5 min         1.7%        11.5%        92.5%
  10 min         1.4%         1.4%        84.2%
  30 min         0.0%         0.0%        50.8%
  60 min         0.0%         0.0%         0.8%

requests sent to the failed region in all         126,400      391,000    3,661,000
queries a second at the DNS servers                   667           67            6

Recorded with Python 3.14.8 on macOS 26 arm64. To run it yourself: mise exec python@3.14.8 -- python3 ttl_failover_sim.py

Change the TTLs or the detection time at the top and run it again to price your own failover. With the numbers as they are:

  • Nothing moves until the health check notices. For the first 30 seconds every request goes to the failed region, whatever the TTL. Detection time is part of every failover budget.
  • A 30-second TTL leaves only the stragglers after a minute: the 2 % of clients that ignore the TTL, which now dominate the tail.
  • A 300-second TTL still sends 90 % of requests to the dead region after a minute and 11.5 % after five.
  • A one-hour TTL sends half the requests there for half an hour: 3.66 million failed requests at 2,000 a second, against 391,000 at 300 seconds and 126,400 at 30.
  • The price of the short TTL is the last line: 667 queries a second at the DNS servers instead of 67 or 6.

So DNS failover is a tool for minutes. When a design needs a region to drop out within seconds, the steering has to happen below DNS: in anycast routing, or in a load balancer or edge that retries a healthy region itself.

DNS Propagation Checker Watch a DNS change spread: compare a record and its remaining TTL across public resolvers in many places.

Key idea

DNS failover costs the time the health check needs, up to one TTL of cached answers and a tail of clients that ignore TTLs, so it moves users in minutes, never in seconds.

Checkpoint

Check: How long DNS failover takes

  1. Question 1 of 2 In the failover model, every request still goes to the failed region during the first 30 seconds, whatever the TTL. Why?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: The health check has not noticed the failure yet, so the DNS answer has not changed

    Detection comes before any expiry: until the checker has seen several failed probes, the authoritative servers keep answering with the failed region. Detection time belongs in every failover budget.

  2. Question 2 of 2 With a 300-second TTL and a health check that needs 30 seconds to notice a failure, how many seconds after the failure have all the clients that respect the TTL left the failed region?

    Type a number.

    A hint

    Add the detection time to the longest a cached copy can live.

    Show the answer: Question 2 of 2

    Answer: 330 s

    Nothing moves for 30 seconds; then cached copies expire over one TTL, the last of them 300 seconds later: 30 + 300 = 330 s. The model's 2 % of clients that ignore TTLs take longer still.

Anycast lets routing choose the site, packet by packet

The diagram shows two sites that announce one address, and where each group of users ends up:

Two sites announce the same address 203.0.113.10; routing sends each user to the nearer site, and to site A once site B withdraws.Users in the westUsers in the eastInternet routingpicks the nearest announcementSite Aannounces 203.0.113.10Site Bannounces 203.0.113.10(fails: withdraws it)to 203.0.113.10to 203.0.113.10west; east once B withdrawseast, while B is up

Anycast: one address, announced from two sites

Text description of the diagram

Site A and site B both announce the same IP address, 203.0.113.10, to the Internet's routing system. Users in the west and users in the east send their packets to that one address, and routing delivers each packet to the announcement that is nearest by its own measure: - traffic from the west reaches site A; - traffic from the east reaches site B while it is up.

When site B fails, it withdraws its announcement. Once routers have learned of the withdrawal, traffic from the east also goes to site A. No DNS answer changes, so no cache has to expire.

With anycast, a service gets a stable set of IP addresses, and several independent sites announce reachability to those addresses into the routing system. Routing then makes the choice for each client: packets go to the announcement that is closest by the routing system’s own measures, which is not always the closest in kilometres or the fastest (RFC 4786, RFC 7094). DNS servers are its classic use, including many of the root servers, and the same architecture notes record its growing use by content delivery networks, despite the caveats about connections described below.

Failover needs no DNS change at all. The operational guidance is to tie a site’s route announcement to the health of the service there, so that a failed site withdraws its route and traffic moves to the remaining sites as routing converges. It also warns against announcing and withdrawing in rapid alternation, which routers may punish by ignoring the route for a while (RFC 4786).

The catch is state. Routing picks the site again for every packet, so a connection survives only while routing stays stable for longer than the connection lasts. A DNS query is a single packet each way and does not care. A long TCP download can break if the route changes halfway, because the new site has never heard of the connection; the architecture notes on anycast state plainly that unmodified stateful transports can fail when used with anycast under normal routing changes (RFC 7094). One answer in the guidance is to let anycast handle only the start of an exchange and to hand the long part to a unicast address (RFC 4786).

Step through a failure at site B of the diagram, first for new traffic and then for a download that was already running there:

Interactive · step by step An anycast site fails during a long download Step through a failure at site B, first for new traffic, then for a download that was already running.
An anycast site fails during a long download, step 7 of 7. Showing Users in the west, Users in the east, Site A (announces 203.0.113.10), Site B (down, route withdrawn). In focus: Site A, Users in the east.Users in the westUsers in the eastSite Aannounces 203.0.113.10Site Bdown, route withdrawnlong transfers on a unicast address

The drawing shows the whole scene; its 7 steps are listed below.

Every step as text
  1. One address, two sites. Sites A and B announce the same address, 203.0.113.10. Routing delivers each packet to the announcement that is nearest by its own measure, which is not always the fastest.
  2. Each user to the nearer site. Users in the east reach site B and users in the west site A. A DNS query is one packet each way, so any site can answer it.
  3. A long download starts. A user in the east starts a large download over TCP. Site B holds the connection's state, the sequence numbers and what has been sent so far.
  4. Site B withdraws its route. The service at site B fails. Its route announcement is tied to the service's health, so the announcement is withdrawn. No DNS answer changes, and no cache has to expire.
  5. Routing moves the east to A. Once routers have learned of the withdrawal, packets for 203.0.113.10 from the east go to site A. New queries and new connections work again at once.
  6. The download breaks. The download's next packet reaches site A, which has never heard of the connection. TCP answers a segment for a connection it does not have with a reset, so the download must start again.
  7. Keep long exchanges on one site. Anycast suits short exchanges. For long ones the guidance is to let anycast handle only the start and to hand the rest to an address that one site announces alone.

New queries and new connections moved to site A as soon as routing had learned of the withdrawal, while the running download met a site with no state for it and got a reset (RFC 9293).

IP Address Lookup See which network announces an address and its prefix: the routing facts behind anycast.

Checkpoint

Check: Anycast routing and its catch

  1. Question 1 of 2 Site B of an anycast service fails. What moves its users to site A?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Site B's route announcement is withdrawn, and routing converges on site A

    With anycast every site announces the same address and routing chooses among the announcements. A site whose announcement follows its service's health withdraws it on failure, and traffic moves as routing converges.

  2. Question 2 of 2 A long TCP download from site B is under way when routing starts to deliver its packets to site A. What happens to the download?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Site A has no state for the connection and answers with a reset, so the download starts again

    Routing picks the site again for every packet, so a connection survives only while routing stays stable for longer than the connection lasts. RFC 7094 notes that unmodified stateful transports can fail under normal routing changes.

DNS steering or anycast?

The table puts the two side by side on the six things a design has to decide about them:

Two ways to send users to a nearby, healthy site
Criterion DNS steering (GeoDNS, weights, failover)Anycast
Who chooses the site Your authoritative DNS servers, per queryInternet routing, per packet
What it knows about the user The resolver's address, or a client subnetNothing: only the routing topology
Time to move users after a failure Detection plus up to one TTL, and a tail that ignores TTLsDetection plus routing convergence
Fine control Yes: weights, percentages, per-country answersLittle: routing decides
What you need A DNS service with policies and health checksYour own address space and routing relationships, or a provider that has them
Weak spot Caches keep old answersLong connections can break when routes change
When to choose Choosing an application region, gradual migrations and canariesDNS servers, CDN edges and front doors that must fail over fast

Large systems often use both: an anycast front door, a CDN or a global load balancer, keeps the first hop close and fails over fast, while DNS policies decide which application region sits behind it.

Give each layer the job it does fast

Put whatever must escape a failure in seconds on anycast or a front door, and whatever needs weights, countries or a gradual move on DNS. A TTL then decides only how quickly your region choices change, not how long users wait on a failed site.

Checkpoint

Check: DNS steering or anycast

  1. One question A service must move users off a failed site within seconds, and it must also send 5 % of its users to a new region for a canary. Which design fits?

    Choose one answer.

    Show the answer: One question

    Answer: An anycast front door that fails over by withdrawing routes, with weighted DNS answers behind it

    Large systems often use both: an anycast front door keeps the first hop close and fails over fast, while DNS policies such as weights choose the region behind it.

Practise: choose the longest TTL

Turn the failover model into a function that picks the longest TTL that still meets a failover goal, and run its sample tests in your browser:

Exercise · Medium · Python

Choose the longest TTL that still meets a failover goal

A failover goal reads like this: "deadline_s seconds after a region fails, at most target of the clients may still be sent to it." A long TTL keeps load on the DNS servers low, so you want the longest TTL that still meets the goal.

Use this lesson's model for clients that respect the TTL. Nothing changes until the health check notices the failure, detect_s seconds after it happens. From then on, the share of clients still holding the old answer falls in a straight line from 1 to 0 over one TTL: t seconds after the failure it is 1 - (t - detect_s) / ttl.

Write longest_ttl(deadline_s, detect_s, target) in ttl.py. Return the longest whole number of seconds that meets the goal. Raise ValueError when no TTL can meet it, because the deadline is not later than the detection time, and when target is not at least 0 and below 1.

longest_ttl(300, 30, 0.05)   # 284: after 5 minutes at most 5 % of clients on the failed region

The sample tests import longest_ttl from ttl.py and run in your browser.

Starter code · ttl.py

def longest_ttl(deadline_s, detect_s, target):
    """The longest TTL in whole seconds that leaves at most `target` of clients on a failed region at the deadline."""
    # Replace this line with your code.
    return 0
The sample tests · test_ttl.py
from ttl import longest_ttl


def raises_value_error(call):
    try:
        call()
    except ValueError:
        return True
    return False


def test_five_minutes_five_percent():
    """after 5 minutes, at most 5 % of clients on the failed region"""
    assert longest_ttl(300, 30, 0.05) == 284


def test_everyone_moved():
    """with a target of 0, every cache must have expired by the deadline"""
    assert longest_ttl(120, 30, 0.0) == 90


def test_half_after_an_hour():
    """a lenient goal allows a long TTL"""
    assert longest_ttl(3600, 60, 0.5) == 7080


def test_impossible_goals():
    """raises ValueError when no TTL can meet the goal, or the target is out of range"""
    assert raises_value_error(lambda: longest_ttl(20, 30, 0.05))
    assert raises_value_error(lambda: longest_ttl(30, 30, 0.05))
    assert raises_value_error(lambda: longest_ttl(300, 30, 1.0))
    assert raises_value_error(lambda: longest_ttl(300, 30, -0.1))
A hint

Write the goal as an inequality and solve it for the TTL: 1 - (deadline_s - detect_s) / ttl <= target. Moving ttl to one side gives ttl <= (deadline_s - detect_s) / (1 - target). The longest whole number of seconds that fits is the floor of the right-hand side (math.floor).

The sample tests run on this device, in your browser (Pyodide): nothing is sent to mysmartcopilot.com. The first run downloads Python (about 13.5 MB), which is kept for the next runs. A check in your browser is feedback for you, not proof that the code is right for every input.

Then answer the self-check, which begins with the idea you have practised least:

Practice that adapts to you

Practise this lesson

19 questions about 6 ideas of this lesson. Each answer is explained at once, and what you get right is kept in this browser.

  1. Question 1 of 19 What does a recursive resolver do with a referral it receives?

    Choose one answer.

    Show the answer: Question 1 of 19

    Answer: It caches the referral for its TTL and asks the servers it names

    A referral names the servers of a child zone. The resolver asks them next and keeps the referral for its TTL, so the next lookup under that zone can start there instead of at the root.

  2. Question 2 of 19 On a completely empty cache, how many servers does the resolver ask to resolve shop.cdn.example. on its own?

    Type a number.

    A hint

    Walk down from the root, one referral at a time.

    Show the answer: Question 2 of 19

    Answer: 3 servers

    The root refers it to example., the servers of example. refer it to cdn.example., and the servers of cdn.example. answer: 3 servers. In the program the same name cost only 2, because the referral to example. was cached.

  3. Question 3 of 19 A team adds a record for new.shop.example., yet some users keep getting NXDOMAIN for several minutes. The zone's SOA allows 300 seconds of negative caching. What happened?

    Choose one answer.

    Show the answer: Question 3 of 19

    Answer: Someone looked the name up before it existed, and resolvers cached the NXDOMAIN for up to 300 seconds

    Negative caching has this practical edge: a lookup before the record exists leaves an NXDOMAIN in the caches, and resolvers keep answering no such name until that negative TTL has run out.

  4. Question 4 of 19 You will move a service to new addresses next week. What do the DNS specifications suggest you do with its TTL?

    Choose one answer.

    Show the answer: Question 4 of 19

    Answer: Lower it ahead of the move, then raise it back once the move is done

    RFC 1034 says that when a change can be anticipated, the TTL can be reduced before the change to keep the inconsistency short, and increased back afterwards. Lower it at least one old TTL before the move, so the long cached copies have expired by then.

  5. Question 5 of 19 A resolver cached an A record with a TTL of 300 seconds, 120 seconds ago. The zone's owner changes the address now. At most how many seconds can this resolver keep returning the old address?

    Type a number.

    A hint

    The TTL counts from the moment the record was cached.

    Show the answer: Question 5 of 19

    Answer: 180 seconds

    The TTL is a limit on how long the record may stay in the cache, counted from when it was cached: 300 − 120 = 180 seconds are left. A resolver that respects the TTL asks again after that and gets the new address.

  6. Question 6 of 19 A team lowers every record's TTL from 3,600 to 30 seconds to be ready for failover. What does that cost?

    Choose one answer.

    Show the answer: Question 6 of 19

    Answer: About 120 times as many queries reach their DNS servers, and more users wait for a lookup that a cache would have answered

    Each resolver that keeps a name warm asks again once per TTL, so 3,600 / 30 = 120 times as often. More lookups also miss the caches, and each miss costs the user round trips to the DNS servers.

  7. Question 7 of 19 Your DNS provider's servers become unreachable, and resolvers that support serving stale data keep answering with expired records. What does that mean for an address change you make in that time?

    Choose one answer.

    Show the answer: Question 7 of 19

    Answer: Users can keep reaching the old address past its TTL, because the resolvers cannot fetch the new one

    RFC 8767 lets resolvers keep serving an expired answer, with a short TTL, while they cannot reach the authoritative servers. That makes DNS more resilient, and it means an old answer can outlive its TTL.

  8. Question 8 of 19 Which DNS routing policy sends 5 % of users to a new region for a canary?

    Choose one answer.

    Show the answer: Question 8 of 19

    Answer: Weighted answers

    Weighted routing splits answers by percentages, which is how traffic moves gradually to a new region or a canary. Geolocation, latency-based and failover policies decide by place, speed and health instead.

  9. Question 9 of 19 GeoDNS sends a user in Chennai to a region in Europe, although there is a region in Mumbai. What is the most likely reason?

    Choose one answer.

    Show the answer: Question 9 of 19

    Answer: The user's resolver is far away or geolocates elsewhere, and GeoDNS answers by the resolver's address unless the resolver passes a client subnet

    The authoritative server sees the address of the recursive resolver, not of the user. Unless the resolver sends EDNS Client Subnet with part of the user's address, the answer fits wherever the resolver appears to be.

  10. Question 10 of 19 During a canary, weighted DNS sends 10 % of its answers to region B, with no health check on region B. Region B starts failing. What happens until someone acts?

    Choose one answer.

    Show the answer: Question 10 of 19

    Answer: About 10 % of users keep reaching region B, and after the weights change, cached answers keep some there for up to one TTL

    A weighted answer is an answer like any other: it changes only when someone or something changes it, and then reaches users as caches expire. Health-checked failover is what takes a failing answer out on its own.

  11. Question 11 of 19 Which delays add up before every client has left a failed region under DNS failover? Choose every one.

    Choose every answer that is right.

    Show the answer: Question 11 of 19

    Answer:

    • The time the health check needs to notice the failure
    • Clients that keep an address longer than its TTL
    • The TTL of the answers resolvers have cached

    Detection, then expiry over up to one TTL, then a tail of clients that ignore TTLs: that is why DNS failover is a tool for minutes, not seconds.

  12. Question 12 of 19 With a 300-second TTL and a health check that needs 30 seconds to notice a failure, what percentage of the clients that respect the TTL still use the failed region 2 minutes after it failed?

    Type a number.

    A hint

    How much of the 300-second TTL has passed since the answer changed?

    Show the answer: Question 12 of 19

    Answer: 70 % (anything from 69 to 71 counts)

    The record changes after 30 seconds, so 90 seconds of the 300-second TTL have passed by the 2-minute mark: 1 − 90 / 300 = 0.7, or 70 %. The model in this lesson prints 70.5 %, because its 2 % of clients that ignore the TTL leave even more slowly.

  13. Question 13 of 19 In the failover model's output, what share of the requests still went to the failed region 10 minutes after it failed, with a 30-second TTL?

    Type a number.

    A hint

    With a 30-second TTL, the clients that respect it left long ago. Who is left?

    Show the answer: Question 13 of 19

    Answer: 1.4 % (anything from 1.35 to 1.45 counts)

    The model printed 1.4 %: only the 2 % of clients that keep an address for at least 30 minutes, whatever the TTL, and a little less than 2 % because some of them have refreshed by then. A shorter TTL cannot reach them.

  14. Question 14 of 19 With a one-hour TTL, the model sent 3.66 million requests to a dead region. Which change cuts that number most without touching DNS?

    Choose one answer.

    Show the answer: Question 14 of 19

    Answer: Clients or a front door that retry a failed request in the other region

    When a design needs a region to drop out within seconds, the steering has to happen below DNS: in anycast routing, or in a load balancer, edge or client that retries a healthy region itself.

  15. Question 15 of 19 What decides which anycast site a packet reaches?

    Choose one answer.

    Show the answer: Question 15 of 19

    Answer: The routing system, which delivers it to the announcement nearest by its own measures

    With anycast, several sites announce the same address and routing delivers each packet to the announcement that is closest by the routing system's own measures, which is not always the closest in kilometres or the fastest.

  16. Question 16 of 19 Why do DNS servers suit anycast better than long downloads do?

    Choose one answer.

    Show the answer: Question 16 of 19

    Answer: A DNS query and its answer are one packet each way, so a route change between two queries breaks nothing

    Routing may pick another site for any packet. A one-packet exchange does not care, while a long TCP connection breaks when its packets start to arrive at a site that has no state for it.

  17. Question 17 of 19 Which of these are real risks when long-lived TCP connections go to an anycast address?

    Choose every answer that is right.

    Show the answer: Question 17 of 19

    Answer:

    • The nearest site is chosen by routing, which may not be the site with the lowest latency
    • Load balancing on a router that sends each packet of a flow down a different path can split one connection across sites
    • A routing change in the middle of a connection can deliver its packets to a different site, which has no state for it

    Anycast hands node selection to the routing system, so a connection lives only as long as routing stays stable, and routing's idea of near is not a latency measurement. TCP over anycast works in practice wherever routing is stable for much longer than the connections last.

  18. Question 18 of 19 Which tool fits moving an application from one region to another a little at a time?

    Choose one answer.

    Show the answer: Question 18 of 19

    Answer: Weighted DNS answers

    DNS steering gives fine control, weights, percentages and per-country answers, which is what choosing an application region and moving traffic gradually need. Anycast gives speed of failover instead.

  19. Question 19 of 19 What does anycast need that DNS steering does not?

    Choose one answer.

    Show the answer: Question 19 of 19

    Answer: Your own address space and routing relationships, or a provider that has them

    DNS steering needs a DNS service with policies and health checks. Anycast needs the same address announced from many sites, which takes address space and routing relationships of your own, or a provider such as a CDN or a global load balancer that has them.

Design practice: failovers and front doors

These two decisions come up whenever a design relies on DNS or anycast to move users. Decide each one first, then test it against the figures above: the failover model for the first brief, and the anycast failure for the second.

Checkpoint

Your first decision

  1. Question 1 of 2 Design brief: two regions sit behind DNS failover with a 300-second TTL. The business now wants users moved off a failed region within 30 seconds. What is the first change?

    Choose one answer.

    Show the answer: Question 1 of 2

    Answer: Move the failover below DNS, to a front door or load balancer that checks both regions and sends each request to a healthy one

    DNS failover costs the detection time, up to one TTL and a tail of clients that ignore TTLs: minutes, not seconds. A deadline of seconds needs a layer that steers each request itself.

  2. Question 2 of 2 Design brief: an anycast address serves long-lived WebSocket connections, and users are cut off whenever a site is taken out of service. What do you change first?

    Choose one answer.

    Show the answer: Question 2 of 2

    Answer: Let the anycast address handle only the start, then move each long connection to an address that one site announces alone

    RFC 4786 suggests splitting a long exchange into a start that anycast handles and a rest on a non-anycast address; RFC 7094 explains why stateful transports can break when routes change.

Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.

  1. Mid to senior

    Your service runs active-active in two regions behind DNS failover with a 300-second TTL. One region fails at the evening peak. Estimate how long users keep failing, then say what you would change.

    Model answer, Pro. Model answers open with any pass; prices are in the notice on this page. First step and follow-ups

  2. Senior to staff

    A global API serves users on four continents from three regions. Would you send users to regions with GeoDNS or with anycast? Defend the choice, including what each does when a region fails.

    Model answer, Pro. First step and follow-ups

Interview questions

Warm-up (fresher to mid level): what does a DNS TTL control, and what happens when you lower it? The TTL says how many seconds resolvers and clients may keep a record in their caches before they must ask the authoritative servers again. Lowering it makes changes, such as a failover or a move to new servers, reach users sooner, because cached copies expire sooner. The cost is load and latency: every resolver asks again once per TTL, so going from 3,600 to 30 seconds multiplies those queries by 120, and more user lookups miss the cache and wait for round trips. A lower TTL also does not help clients that ignore it, and it takes effect only after the old, longer TTL has run out, so for a planned change it should be lowered at least one old TTL in advance.

Key takeaways

  • A recursive resolver walks from the root to the authoritative servers once, then serves the cached answer until its TTL runs out; every link of a CNAME chain and every “no such name” has its own TTL.
  • A TTL trades the speed of change against load: in the model, 30 seconds cost 667 queries a second against 6 for an hour.
  • DNS failover takes detection time plus up to a TTL, plus a tail of clients that ignore TTLs: minutes, not seconds.
  • GeoDNS answers by the resolver’s location; EDNS Client Subnet improves it at a cost in caching and privacy.
  • Anycast lets routing pick the nearest site and fails over by withdrawing a route, but long-lived connections need routing to stay stable.
  • Use DNS policies to choose regions and move traffic gradually; use anycast where the first hop must stay close and fail over fast.

Terms in this lesson

anycast
Announcing the same IP address from several sites, so that Internet routing delivers each packet to the nearest announcement by its own measure. A failed site withdraws its route, and traffic moves to the others.
authoritative name server
A DNS server that holds a zone's records and answers for them itself, without asking any other server. Steering policies such as GeoDNS and health-checked failover run here.
GeoDNS
Answering a DNS query by where it appears to come from, so that users get the address of a nearby region. The authoritative server sees the resolver's address, not the user's, unless the resolver passes a client subnet.
negative caching
Keeping the answer that a name does not exist (NXDOMAIN) in a cache, for as long as the zone's SOA record allows. A name looked up before it was created can stay missing for that long.
recursive resolver
The DNS server that answers a device's question in full. It follows referrals from the root down to the servers authoritative for the name, and caches every answer for its TTL so the next user skips the walk.
TTL (DNS)
Time to live: the number of seconds a resolver or a client may keep a DNS answer in its cache before it must ask again. A change reaches a user only once the cached copy's TTL has run out.

References

Related tools

Report a problem with this lesson

Quick answers and tool search

Type to search tools or to get a quick answer, for example 18% of 2500. Use the up and down arrow keys to move through the results, Enter to choose, and Escape to close.