The Domain Name System (DNS) turns names people can remember, like www.example.com, into the IP addresses machines route packets to. It is a globally distributed, hierarchical, heavily cached database, and it is the first hop of almost every request your system serves. Because it decides which IP a client connects to, DNS is also one of the most powerful (and most misunderstood) tools for load balancing, geographic routing and failover.
Think of it like
A hotel concierge with a notepad
You ask the concierge (the recursive resolver) for a restaurant's address. They don't know it, so they call the city tourist office (a root server), which says "for Italian places, ask the Italian restaurant association" (a TLD server). The association gives the number of the restaurant itself (the authoritative server), which finally answers. The concierge jots the address on a notepad (the cache) so the next guest gets it instantly, and crosses it out when the note expires (the TTL).
Why DNS exists
IP addresses are hard to remember and, more importantly, they change: servers are replaced, traffic moves between regions, providers renumber. A name is a stable indirection layer on top. One name can also map to many addresses, which is how a single hostname can front thousands of servers worldwide.
DNS mostly runs over UDP port 53 because a lookup is a single tiny request and response. It falls back to TCP port 53 when an answer is too large for one UDP datagram (the server sets the truncation flag) and for zone transfers between name servers.
The DNS hierarchy
The namespace is a tree read right to left. www.example.com. sits under example.com, under the .com top-level domain, under the root (the invisible trailing dot). Each level delegates authority for the level below it using NS records, so no single server needs to know every name.
- Root servers
- 13 named server identities (
a.root-servers.nettom.root-servers.net) run by 12 organizations and replicated to well over a thousand sites via anycast. They only know who runs each TLD. - TLD servers
- Run by registries (Verisign operates
.comand.net). They know which name servers are authoritative for each registered domain. - Authoritative name server
- Holds the actual records for a zone such as
example.com. Usually a managed service: Route 53, Cloudflare DNS, NS1, Google Cloud DNS. - Recursive resolver
- Does the legwork for clients: walks the hierarchy, caches answers and returns the final result. Run by ISPs, enterprises and public services such as
1.1.1.1and8.8.8.8. - Stub resolver
- The tiny client inside your OS. It does not walk the tree; it just forwards questions to a recursive resolver and caches the answers.
- Registrar vs registry
- You buy a domain from a registrar (Namecheap, GoDaddy), which tells the registry (Verisign) to publish your NS records in the TLD zone.
The simulation above animates a full lookup. The diagram below shows the same journey; press play on a flow to watch the queries hop through the hierarchy.
Recursive vs iterative resolution
Recursive query
- Client to resolver: "return the final answer or an error"
- The resolver does all the work and caching
- Stub resolvers on laptops and phones always use this mode
- Puts the burden on a server built for it, close to the client
Iterative query
- Resolver to root, TLD and authoritative servers
- Each server returns the best it has: an answer or a referral
- The resolver follows referrals down the tree itself
- Root and TLD servers refuse recursion: it would overload them and make them a DDoS amplifier
# Ask your default resolver; the number is the remaining TTL in its cache
dig www.example.com A +noall +answer
# www.example.com. 245 IN A 203.0.113.10
# Walk the hierarchy yourself, iteratively, starting at the root
dig +trace www.example.com
# Ask a specific public resolver, or the authoritative server directly
dig @1.1.1.1 example.com MX
dig @ns1.example.com www.example.com +norecurse
# Reverse lookup (IP -> name, via a PTR record)
dig -x 203.0.113.10Caching and TTLs at every layer
Every answer carries a TTL (time to live) in seconds, set by the zone owner. Each cache along the path may reuse the answer until the TTL runs out. Caching is why DNS can serve the whole internet, and it is also why DNS changes are never instant.
| Layer | Examples | Lifetime | Notes |
|---|---|---|---|
| Browser | Chrome, Firefox host caches | Short, often about a minute | Inspect Chrome's at chrome://net-internals/#dns |
| Operating system | systemd-resolved, Windows DNS Client, mDNSResponder | Respects TTL | Shared by every app on the machine |
| Application runtime | JVM networkaddress.cache.ttl, connection pools | JVM: 30 s by default; pools: forever | Pooled connections never re-resolve until they reconnect |
| Recursive resolver | ISP resolvers, 1.1.1.1, 8.8.8.8 | Respects TTL (some clamp min or max) | One cache shared by millions of users |
| Negative cache | Any resolver | SOA minimum field (RFC 2308) | "This name does not exist" (NXDOMAIN) is cached too |
Low TTL (30–60 s)
- Changes and failovers take effect quickly
- More queries hit your authoritative servers (and your DNS bill)
- More users pay the cold-lookup latency
- Good for records you may need to move in an emergency
High TTL (hours to days)
- Fewer queries and faster average lookups
- Resilient if your DNS provider has a brief outage
- Mistakes and migrations take hours to undo
- Good for stable records: MX, NS, verification TXT
- 1
Lower the TTL early
Days before a migration, drop the TTL from, say, 86,400 to 60. Then wait at least one old TTL so every cache has picked up the short value.
- 2
Make the change
Point the record at the new IP. Fresh lookups see it immediately; cached copies expire within 60 s.
- 3
Verify from outside
Query several public resolvers (
dig @1.1.1.1,dig @8.8.8.8) and the authoritative server directly. - 4
Keep the old target alive
Some clients ignore TTLs or hold pooled connections. Leave the old server running and watch its traffic drain.
- 5
Raise the TTL again
Once stable, restore a long TTL to cut query volume and latency.
Record types
| Type | Purpose | Example |
|---|---|---|
| A | Name → IPv4 address | www.example.com. 300 IN A 203.0.113.10 |
| AAAA | Name → IPv6 address | www.example.com. 300 IN AAAA 2001:db8::10 |
| CNAME | Alias to another name; the resolver restarts the lookup at the target | blog.example.com. CNAME example.ghost.io. |
| MX | Mail servers for the domain, with a preference (lower is tried first) | example.com. MX 10 mail1.example.com. |
| NS | Delegates a zone to its authoritative name servers | example.com. NS ns1.dnsprovider.net. |
| TXT | Free text: SPF, DKIM, DMARC, domain-ownership proofs | example.com. TXT "v=spf1 include:_spf.google.com ~all" |
| SRV | Service location: priority, weight, port and host | _sip._tcp.example.com. SRV 10 60 5060 sip1.example.com. |
| SOA | Zone metadata: primary NS, admin mailbox, serial, refresh, retry, expire, negative TTL | example.com. SOA ns1.example.com. hostmaster.example.com. 2026102901 7200 3600 1209600 300 |
| CAA | Which certificate authorities may issue certificates for the domain | example.com. CAA 0 issue "letsencrypt.org" |
| PTR | Reverse lookup: IP → name (lives under in-addr.arpa) | 10.113.0.203.in-addr.arpa. PTR www.example.com. |
DNS as a traffic-steering tool
Because the authoritative server chooses what to answer, it can give different users different IPs. Managed DNS providers expose this as routing policies.
| Policy | Answer is chosen by | Typical use |
|---|---|---|
| Round robin / multivalue | Return several A records, rotating their order | Cheap spreading across a few servers |
| Weighted | Probability proportional to configured weights | Canary releases (send 5% to the new stack), blue/green |
| Geolocation | Country or continent of the resolver (or client subnet) | Data residency, localized content |
| Latency-based | Region with the lowest measured latency from the client's network | Multi-region active-active services |
| Failover | Primary unless its health check fails, then secondary | Disaster recovery |
GeoDNS, latency routing and failover
A GeoDNS server looks at where the query comes from. By default it only sees the resolver's IP, which may be far from the user (a corporate VPN, or a public resolver). The EDNS Client Subnet extension (RFC 7871) lets resolvers pass a truncated client subnet such as /24 so the answer can match the user's real location. Pair it with health checks and DNS becomes a global failover switch.
Anycast
With anycast, the same IP address is announced over BGP from many locations at once, and the internet's routers deliver each packet to the topologically nearest site. Root servers, 1.1.1.1, 8.8.8.8 and most CDNs work this way. Unlike GeoDNS, there is no TTL to wait for: if a site goes down, it withdraws its route and traffic flows to the next-nearest site within seconds.
GeoDNS
- Different IPs for different users
- Fine-grained control: weights, countries, health checks
- Changes wait on cached TTLs
- Location is guessed from the resolver, not the user
Anycast
- One IP for everyone, routed by BGP
- Failover in seconds, no client caches involved
- Spreads DDoS traffic across every site
- "Nearest" is BGP's opinion, not always lowest latency; needs your own IP space and network
Securing DNS
Classic DNS is unauthenticated and unencrypted. An attacker who can forge responses can poison a resolver's cache and send every user of that resolver to a fake site; Dan Kaminsky's 2008 attack showed how practical this was, and resolvers responded by randomizing source ports and query IDs. Two complementary technologies close the remaining gaps.
DNSSEC: is this answer genuine?
- Zones sign their records (RRSIG) with keys published as DNSKEY records
- Parents vouch for children via DS records, forming a chain of trust up to the root key
- Validating resolvers reject forged or tampered answers
- Provides authenticity and integrity, not privacy: queries remain visible
DoH / DoT: can anyone read it?
- DNS over HTTPS (RFC 8484, port 443) and DNS over TLS (RFC 7858, port 853)
- Encrypts the hop between the client and its resolver
- Hides lookups from Wi-Fi operators and on-path observers
- Does not authenticate the data itself: the resolver could still lie
Where DNS shows up in system design
- Entry point: the first box in every request diagram; mention it, then move on unless the question is about global traffic.
- Multi-region routing: GeoDNS or latency-based records pick a region; see Content Delivery Networks for edge networks that build on the same idea.
- Service discovery: internal DNS (Kubernetes CoreDNS, Consul DNS) and SRV records map service names to instances. See Service Discovery & Service Mesh.
- Email and trust: MX, SPF, DKIM, DMARC and CAA records are part of shipping any real product.
- Failure domain: DNS outages and misconfigurations are a classic cause of global incidents. Plan for them in Availability & Reliability discussions.
Implementation
Look up A, MX and CNAME records programmatically, including the TTL the resolver returned.
import dns.resolver # pip install dnspython
answer = dns.resolver.resolve("example.com", "A")
print("TTL remaining:", answer.rrset.ttl)
for rr in answer:
print("A:", rr.address)
for rr in dns.resolver.resolve("example.com", "MX"):
print("MX:", rr.preference, rr.exchange)
# Use a specific resolver instead of the OS default
r = dns.resolver.Resolver(configure=False)
r.nameservers = ["1.1.1.1"]
print([rr.to_text() for rr in r.resolve("www.example.com", "AAAA")])Key takeaways
- DNS is a hierarchy: root servers delegate to TLD servers, which delegate to each domain's authoritative servers.
- Clients send one recursive query; the recursive resolver performs the iterative walk and caches every answer.
- TTLs control caching at every layer, so changes are never instant: lower TTLs well before a migration.
- DNS can steer traffic (weighted, GeoDNS, latency, failover), but it is coarse-grained; pair it with real load balancers.
- Anycast gives one IP many locations and fails over in seconds without waiting on caches.
- DNSSEC authenticates answers; DoH/DoT encrypts the client-to-resolver hop. They solve different problems.
Common pitfalls
- Changing a record with a 24-hour TTL and expecting users to move within minutes.
- Relying on round-robin DNS as a load balancer: no health checks, uneven distribution, slow removal of dead servers.
- Forgetting that application runtimes and connection pools cache IPs, so DNS failover never reaches long-lived clients.
- Putting a CNAME at the zone apex or alongside other records at the same name.
- Using a single DNS provider, turning it into a single point of failure for the whole business.
Interview tips
- When asked "what happens when you type a URL", walk through browser cache → OS → recursive resolver → root → TLD → authoritative, then TCP/TLS/HTTP.
- For multi-region designs, say explicitly how users reach a region: GeoDNS or latency routing with health checks, or anycast, and state the failover time each implies.
- Mention TTL trade-offs whenever you propose DNS-based failover; interviewers like hearing that DNS failover takes TTL plus detection time.
Real-world applications
- Routing users to the nearest region or CDN edge.
- Weighted DNS for canary and blue/green deployments.
- Disaster recovery via health-checked failover records.
- Email delivery and anti-spoofing (MX, SPF, DKIM, DMARC).
- Internal service discovery in Kubernetes and Consul.
Test yourself
Which server returns the final A record for www.example.com during a cold lookup?
Related topics
Finished this lesson? Track it to see your progress on the roadmap.