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.
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:
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:
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.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads JavaScript (about 0.6 MB), which is kept for the next runs. Runs on this device: a JavaScript build of this program (about 14 KB), made when the page was built. The first run also downloads the JavaScript runner (about 0.6 MB), which is kept for the next runs. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 156 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device, in your browser. The first run downloads the C and C++ compiler (about 29.1 MB), which is kept for the next runs. It is best on a computer. Runs on this device: a .NET build of this program (about 5 KB), made when the page was built. The first run also downloads .NET (about 3.6 MB), which is kept for the next runs. Edit runs your changes in the browser: the first edited run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads .NET (about 8.9 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads PHP (about 4.3 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 30 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads the JavaScript runner (about 0.9 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 723 KB), made when the page was built. Edit runs your changes in the browser: the first edited run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device, in your browser. The first run downloads the Go compiler (about 18.7 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 1.7 MB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device, in your browser. The first run downloads Ruby (about 10.2 MB), which is kept for the next runs. Runs on this device: a WebAssembly build of this program (about 198 KB), made when the page was built. To change the code, copy it and run it with the command below. Runs on this device: a WebAssembly build of this program (about 18 KB), made when the page was built. To change the code, copy it and run it with the command below.Your run, in this browser
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 toexample.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.
The drawing shows the whole scene; its 11 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
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
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
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:
The drawing shows the whole scene; its 6 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
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:
"""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
Runs on this device, in your browser. The first run downloads Python (about 13.5 MB), which is kept for the next runs.
Your run, in this browser
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
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:
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:
The drawing shows the whole scene; its 7 steps are listed below.
Every step as text
- 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.
- 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.
- 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.
- 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.
- 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.
- 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.
- 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
DNS steering or anycast?
The table puts the two side by side on the six things a design has to decide about them:
| Criterion | DNS steering (GeoDNS, weights, failover) | Anycast |
|---|---|---|
| Who chooses the site | Your authoritative DNS servers, per query | Internet routing, per packet |
| What it knows about the user | The resolver's address, or a client subnet | Nothing: only the routing topology |
| Time to move users after a failure | Detection plus up to one TTL, and a tail that ignores TTLs | Detection plus routing convergence |
| Fine control | Yes: weights, percentages, per-country answers | Little: routing decides |
| What you need | A DNS service with policies and health checks | Your own address space and routing relationships, or a provider that has them |
| Weak spot | Caches keep old answers | Long connections can break when routes change |
| When to choose | Choosing an application region, gradual migrations and canaries | DNS 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
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).
Results of the sample tests
| Test | Result | Details |
|---|
What your code printed
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.
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
Model answers open with any pass: ₹79 for 1 week ($2.99), one payment that never renews.
-
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.
-
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.
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
- RFC 1034: Domain Names, Concepts and Facilities (IETF)
- RFC 1035: Domain Names, Implementation and Specification (IETF)
- RFC 2308: Negative Caching of DNS Queries (DNS NCACHE) (IETF)
- RFC 8767: Serving Stale Data to Improve DNS Resiliency (IETF)
- RFC 7871: Client Subnet in DNS Queries (IETF)
- RFC 4786: Operation of Anycast Services (IETF)
- RFC 7094: Architectural Considerations of IP Anycast (IAB)
- RFC 9293: Transmission Control Protocol (TCP), reset generation (IETF)
- Choosing a routing policy (Amazon Route 53 Developer Guide) (Amazon Web Services)
- RFC 6761: Special-Use Domain Names (IETF)
- RFC 5737: IPv4 Address Blocks Reserved for Documentation (IETF)
Related tools
Report a problem with this lesson
Kept only in this browser. Your Learn progress