Chapters

DNS: how resolution works

Chapter 1 started with the browser asking "where is api.kade.lk?" and getting 34.87.120.15. This chapter opens that step fully: who is asked, in what order, why the second lookup is faster than the first, and where it can go wrong.

Application protocols · chapter 22 of 34 · 10 min read

Why DNS exists

Humans remember names (api.kade.lk). Machines route by numbers (34.87.120.15). DNS (Domain Name System) is the distributed directory that turns one into the other, for the whole internet.

It also separates the name from the address. When kade-api later moves behind a load balancer with a new IP, Kadé only changes one DNS record. The mobile app keeps calling api.kade.lk and never needs an update.

Reading a name, right to left

api.kade.lk.(root)
a name inside kade.lkthe domain Kadé registeredTLDtop
Each part is a label. The full name ends with an invisible dot for the root: api.kade.lk. is the "fully qualified" form, and you will see that trailing dot in DNS tools and zone files. .lk is Sri Lanka's country-code TLD.

A tree of zones

DNS is organised as a tree, read right to left. No server holds everything. Each level only knows who to ask one level down: this handing-off is called delegation, and each part someone manages is a zone.

Root ( . )knows every TLD.lkknows kade.lk's servers.com.orgkade.lkthe real records (authoritative)example.comapi.kade.lk → 34.87.120.15www.kade.lk → …MX → mail servers (chapter 23)Solid lines are delegations: each parent keeps only a pointer to the child zone's servers.

Wide by design - scroll it sideways.

LevelKnowsRun by
RootWhere each TLD's servers are13 named root server groups (a to m), run by 12 organisations
TLD (.lk, .com …)Which servers are authoritative for each domain under itThe registry, e.g. LK Domain Registry for .lk
AuthoritativeThe real records for kade.lk, and gives the final answerWhoever Kadé picks: here, GCP Cloud DNS

Who does the work

Your laptop never walks the tree itself. It runs a tiny stub resolver that passes the question on. The hard work is done by a recursive resolver, usually run by your ISP or a public one like 8.8.8.8 or 1.1.1.1. Between them sit several caches:

#StopWhat it doesIn the Kadé scenario
1Browser cacheRemembers recent answers for a short whileChrome's internal cache
2hosts fileFixed name → IP entries, checked before DNS/etc/hosts: handy to point api.kade.lk at a test server
3OS stub resolver + cacheAsks the configured DNS server; caches answersmacOS mDNSResponder, Linux systemd-resolved
4Home routerA small forwarder: passes questions on, caches answers192.168.1.1, the DNS server from DHCP (chapter 3)
5Recursive resolverWalks the tree, caches everything it learnsLankaNet's resolver, or 8.8.8.8
6Authoritative serversGive the final answer; never cache for othersCloud DNS for kade.lk

The full walk

With every cache empty, resolving api.kade.lk looks like this:

Laptop (stub)Resolver (ISP)Root server.lk TLD serverCloud DNS (kade.lk)1 · A api.kade.lk? (please recurse)2 · A api.kade.lk?3 · referral: ask the .lk servers4 · A api.kade.lk?5 · referral: ask ns-cloud-a1…a46 · A api.kade.lk?7 · 34.87.120.15 · TTL 300 · AA8 · 34.87.120.15
1The laptop's stub asks the resolver: "A record for api.kade.lk, please do the whole job" (recursion desired).
2-3The resolver asks a root server. The root does not know the answer, but it knows who handles .lk: it sends a referral listing .lk's name servers.
4-5The resolver asks a .lk server. Another referral: "kade.lk is served by ns-cloud-a1.googledomains.com and three more."
6-7The resolver asks Cloud DNS. This time a real answer, marked authoritative: 34.87.120.15, TTL 300.
8The resolver saves everything it learned (both referrals and the answer) and returns the IP to the laptop.
How does the resolver know the root servers in the first place? It ships with a small built-in list of their IPs, the root hints. And when a referral names a server inside the zone it delegates (e.g. ns1.kade.lk for kade.lk), the parent also sends that server's IP, called a glue record, to avoid a chicken-and-egg loop.

Recursive and iterative queries

Recursive query

"Find the final answer for me." Sent by the laptop to the resolver. The resolver does everything and returns only the final IP (or an error).

Iterative query

"Tell me what you know." Sent by the resolver to root, TLD and authoritative servers. Each replies with the answer or a referral to the next server to ask.

Root and TLD servers only answer iteratively. If they did recursive work for the whole internet, they would collapse under the load.

Caching and TTL

Walking the tree every time would be slow, so every record carries a TTL (time to live) in seconds. Resolvers keep the record for that long and answer repeats instantly from cache. This is why the first visit to a site is slower than the rest.

RecordTypical TTLWhy
.lk name servers (from the root)2 daysAlmost never change
kade.lk name servers (from .lk)1 dayChange only when moving DNS providers
api.kade.lk A record5 minutesKadé chose this: short enough to move quickly
  • Negative caching. "This name does not exist" (NXDOMAIN) is cached too, for a time set in the zone's SOA record (chapter 23). A typo'd name that someone later creates may keep failing for a while.
  • TTL is a trade-off. Long TTLs: fewer lookups, faster, but changes spread slowly. Short TTLs: quick changes, more queries.
  • Plan changes ahead. Before moving api.kade.lk to the load balancer, lower its TTL (say to 60 s) at least one old TTL in advance. Then switch the IP, check, and raise the TTL again.

Watch the caches work

Play the recursive resolver. Look up names, move the clock forward, and watch what gets cached and what has to be asked again. The time for each step is typical for a laptop in Colombo:

Name
clock: +0 s

Pick a name and look it up. Try the same name twice, then move the clock past 5 minutes.

Resolver cacheValueTTL
empty

Root servers and anycast

There are only 13 root server names (a.root-servers.net to m.root-servers.net), a limit from the days when a DNS answer had to fit in 512 bytes. But each name is served from many places using anycast (chapter 12): the same IP announced from hundreds of locations. Together the 13 names run on well over a thousand machines worldwide, so a resolver in Colombo reaches a nearby copy. Large DNS providers, including Cloud DNS and Cloudflare, use anycast for the same reason.

On the wire: port 53, UDP and TCP

DNS uses port 53. Most lookups go over UDP: one small question, one small answer, no handshake (chapter 14). Chapter 15 showed the exact bytes of the query for api.kade.lk. The DNS header inside it has a few fields worth knowing:

IDA random 16-bit number; the answer must carry the same one (0x1a2b in chapter 15)
RD / RARecursion Desired (set by the stub) / Recursion Available (set by the resolver)
AAAuthoritative Answer: set only by the zone's own servers
TCTruncated: "the full answer did not fit, ask again over TCP"
RCODEResult: NOERROR, NXDOMAIN (no such name), SERVFAIL (the resolver could not get an answer), REFUSED

DNS switches to TCP (also port 53) when an answer is too large for one UDP datagram (above about 1,232 bytes today, chapter 14), and for zone transfers (AXFR), where a secondary server copies a whole zone from the primary.

Security and privacy

#ProblemWhat it meansDefence
1Cache poisoningAn attacker races the real answer with a fake one ("api.kade.lk is 203.0.113.66"). If the resolver accepts it, everyone using that resolver is sent to the attacker for the whole TTL.Random query IDs and random source ports (chapter 15) make guessing hard; DNSSEC makes fakes detectable
2Forged answersPlain DNS has no proof an answer is genuineDNSSEC: each zone signs its records, and each parent vouches for the child's key, in a chain up to the root. It proves authenticity, not privacy.
3SnoopingPlain DNS is readable by anyone on the path: your ISP or café WiFi sees every name you look upDoT (DNS over TLS, port 853) and DoH (DNS over HTTPS, port 443) encrypt queries to the resolver
DoH hides DNS inside normal HTTPS traffic, which is good for privacy but means office networks can no longer see or filter lookups. Browsers can turn it on by themselves. Also remember chapter 14: an open resolver that answers anyone can be used for amplification attacks.

DNS in GCP

Cloud DNS public zoneHosts kade.lk for the internet. GCP gives four name servers like ns-cloud-a1.googledomains.com … a4; Kadé enters those at the .lk registry, which creates the delegation from section 3.
Internal DNSEvery VM can resolve other VMs by name through the metadata server (169.254.169.254, chapter 2), e.g. kade-db.asia-southeast1-b.c.PROJECT.internal. kade-api can connect to kade-db by name, so its config does not break if kade-db's IP changes.
Private zonesA Cloud DNS zone only visible inside chosen VPCs, e.g. db.kade.internal → 10.10.2.5. Friendlier names than the built-in ones.

Steering traffic with DNS

An authoritative server does not have to give everyone the same answer. Many DNS providers, Cloud DNS included (its "routing policies"), can choose the answer per query. If Kadé later runs kade-api in two regions, DNS can decide who goes where:

#PolicyHow it answers api.kade.lkKadé use
1WeightedReturns each address a set share of the time, e.g. 90% old / 10% newMoving slowly to the load balancer: send 10% first, watch errors, then more (a "canary")
2GeolocationAnswers based on where the query comes fromSri Lankan shoppers → Singapore; shoppers in Europe → a European region
3Latency-basedAnswers with the region measured to be fastest for that area (some providers)Same goal as geolocation, based on measurements
4FailoverHealth-checks the primary; answers with the backup only while the primary is downA standby copy of kade-api in a second region
"Where the query comes from" usually means the resolver's location, not the user's. A user in Colombo using a resolver abroad can be sent to the wrong region. Some resolvers pass part of the user's IP along (EDNS Client Subnet) to improve this.

The big limit is caching (sections 7 and 8). After kade-api's primary region fails:

0 sregion fails~30 shealth checks noticeup to TTL (300 s) and beyondresolvers and apps still use the cached old answerlong-lived connectionsstay on the dead region until they break
#DNS steeringAnycast load balancer (chapter 12)
1Failover speedMinutes (TTL and caches)Seconds: one IP, routing and health checks inside the provider
2ControlCoarse: per resolver, per TTLPer request
3Cost and setupCheap, works with any servers anywhereNeeds a global load balancer product
Short TTLs (30-60 s) make DNS steering faster at the cost of more queries, but some resolvers and apps hold answers longer than asked. For fast failover, Kadé's planned global load balancer is the stronger tool; DNS weighting is great for gradual migrations.

Summary

#IdeaIn one lineNew terms
1-2NamesLabels read right to left, ending at the rootDNS, label, FQDN
3TreeRoot → TLD → authoritative, joined by delegationzone, delegation, TLD, authoritative
4CastBrowser/OS cache, hosts file, stub, forwarder, recursive resolverstub resolver, recursive resolver
5WalkRoot and TLD send referrals; the authoritative server answersreferral, root hints, glue
6Query stylesRecursive to the resolver; iterative from itrecursive, iterative
7-8CachingEvery record has a TTL; negative answers are cached tooTTL, NXDOMAIN, negative caching
9Root13 names, over a thousand anycast machines
10WirePort 53; UDP normally, TCP when truncated or for zone transfersTC flag, AXFR, SERVFAIL
11SecurityPoisoning, DNSSEC for authenticity, DoT/DoH for privacyDNSSEC, DoT, DoH
12GCPCloud DNS public and private zones; internal VM namesCloud DNS
13SteeringWeighted, geo, latency and failover answers; limited by TTL and cachingrouting policy, GeoDNS, EDNS Client Subnet

Try it yourself

The full walk, done by your laptop itself

  • What to look for: Root servers, then the TLD's servers, then the domain's, then the answer.
  • From section: 5. The full walk
dig +trace example.com

Caching

  • Steps: dig example.com, twice
  • What to look for: The TTL in the ANSWER section counts down; "Query time" drops on the second run.
  • From section: 7. Caching and TTL
dig example.com

Asking a specific resolver

  • Steps: dig @8.8.8.8 example.com and dig @1.1.1.1 example.com
  • What to look for: Same answer, different query times.
  • From section: 4. Who does the work
dig @8.8.8.8 example.comdig @1.1.1.1 example.com

DNS header flags

dig example.com

A negative answer

  • What to look for: status: NXDOMAIN and the SOA record that sets how long it is cached.
  • From section: 7. Caching and TTL
dig nosuchname-123.example.com

Clear your OS cache

  • What to look for: The next lookup is slow again.
  • Runs on: macOS · Linux: resolvectl flush-caches · Windows: ipconfig /flushdns
  • From section: 7. Caching and TTL
sudo dscacheutil -flushcache; sudo killall -HUP mDNSResponder

A Cloud DNS zone

  • What to look for: The four nameServers to give the registry.
  • From section: 12. DNS in GCP
gcloud dns managed-zones describe kade-lk

Answers that depend on who asks

  • Steps: dig +short www.google.com @8.8.8.8 and @1.1.1.1, from home and from a VM in another region
  • What to look for: Different IPs for the same name.
  • From section: 13. Steering traffic with DNS
dig +short www.google.com @8.8.8.8dig +short www.google.com @1.1.1.1

Spotted a mistake, or something unclear? Suggest an edit on GitHub