Courses / System Design Interview / Chapter 6
Module 2 · Building Blocks I: Names, Traffic and Data · Chapter 6 of 49
DNS: Turning Names into Addresses
Builds on Building Blocks: The Parts Every Design Reuses. Next up: Load Balancers.
Part 1 · Names, zones and the hierarchy
Names and addresses
Every app and website starts with a name, but networks route packets by number. DNS, the Domain Name System, is the distributed directory that connects the two, and almost every request in a design begins with a DNS lookup.
A machine on a network is found by its IP address: a number such as 104.20.23.154 (IPv4) or a longer hexadecimal form (IPv6). People use names instead, and there is a second reason to prefer them. Addresses change. A server is replaced, a service moves to another provider, a site is spread over more machines. The name stays the same while the address behind it changes. DNS answers one question: what address is behind this name?
No single machine holds every answer. DNS is a distributed database: the work is split among many servers, arranged in a tree. You read a name from right to left to follow the tree. In www.example.com. each dot-separated piece is a label. The final dot stands for the root, the top of the tree. com is a top-level domain (TLD), example is a name registered under it, and www is a host name chosen by the owner of example.com.
| Level | Example | Run by | What it knows |
|---|---|---|---|
| Root | the final dot | The root server operators | Which servers handle each TLD |
| Top-level domain | com, org, in | A registry for that TLD | Which servers handle each registered name below it |
| Authoritative | example.com | The site owner or its DNS provider | The final records for the name |
Zones and delegation
A zone is the part of the namespace that one set of servers is responsible for. The parent zone hands a child zone over with NS records: the root zone lists the servers for com., and the com. zone lists the servers for example.com.. This handing-over is called delegation. The servers named in an NS record are authoritative: they hold the zone's records themselves, rather than a cached copy of someone else's answer.
The program below asks for the NS records of the .in top-level domain and of example.com. It sends the question to the public resolver at 8.8.8.8 through the dnspython library, version 2.9.2. The programs ask public resolvers on 2026-11-22, so live answers on your day may differ.
import dns.resolver r = dns.resolver.Resolver(configure=False) r.nameservers = ["8.8.8.8"] for name in ["in", "example.com"]: answer = r.resolve(name, "NS") print(name, "NS records:", len(answer)) for rr in sorted(answer, key=str)[:4]: print(" ", rr)
ns_query.py: ask for NS records
in NS records: 4 ns1.registry.in. ns2.registry.in. ns3.registry.in. ns4.registry.in. example.com NS records: 2 elliott.ns.cloudflare.com. hera.ns.cloudflare.com.
One real run, from Python 3.12.10.
The .in zone is served by servers in the registry's own domain, while example.com is served by two servers at a DNS provider. They are different organisations, and that is the point of delegation: the owner of a name chooses who answers for it, and the parent only records the choice.
This is also what buying a domain means. You register example.com through a registrar, a company that sells names, and the registrar asks the registry that runs com to publish NS records for your name in its zone. From then on, changing who answers for your name is an edit to those NS records, and the registry's servers point resolvers at whichever servers you chose.
The root has a special size. There are 13 root server names, a to m, run by 12 organisations. Each name is announced from many places, and root-servers.org counted 2,046 instances worldwide on 2026-11-22. The last lesson of this chapter explains how one name can live in so many places.
Part 2 · Resolution: recursive and iterative queries
Who does the walking
Your phone does not walk the tree. It holds a small piece of software called a stub resolver, which sends every question to one recursive resolver. That resolver belongs to your network provider, your company or a public service, and it does the work of finding the answer.
The two words describe the two kinds of question. In a recursive query the asker wants the final answer or an error: the phone asks the resolver this way, and the resolver must come back with an address. In an iterative query the asker accepts a hint. A server that does not have the answer replies with a referral: a list of servers closer to the answer. The resolver asks the root, the TLD servers and the authoritative servers this way.
Watch for the resolver: the phone asks once and the resolver does the walking
Read it as steps
A phone asks a resolver once; the resolver walks root, .com and the authoritative server, then caches the answer.
The scene shows what the phone sees and what it does not. The phone sent one question and received one answer. Three more servers were asked in between, and the resolver kept the result so the next phone to ask the same question skips the walk. That is why public resolvers are fast: they serve many users from one cache.
An iterative walk in code
The program below plays the resolver. It starts at a root server, a.root-servers.net, whose address 198.41.0.4 is published by the root server operators. It clears the recursion-desired flag, so each server answers only for what it knows, and it follows the referrals until an answer comes back.
import dns.flags import dns.message import dns.query import dns.rdatatype def ask(server, name): q = dns.message.make_query(name, "A") q.flags &= ~dns.flags.RD # iterative: no recursion wanted return dns.query.udp_with_fallback(q, server, timeout=3) server, name = "198.41.0.4", "example.com" print("asking a root server", server, "for", name) for step in range(1, 6): resp, used_tcp = ask(server, name) how = "TCP" if used_tcp else "UDP" if resp.answer: first = resp.answer[0].to_text().splitlines()[0] print(f"step {step}: ANSWER {first} ({how})") break ns = [r.target.to_text() for rs in resp.authority if rs.rdtype == dns.rdatatype.NS for r in rs] glue = [r.address for rs in resp.additional if rs.rdtype == dns.rdatatype.A for r in rs] zone = resp.authority[0].name.to_text() print(f"step {step}: referral to {zone} -> {ns[0]}, {len(ns)} NS") server = glue[0] print(f" {how}, {len(resp.to_wire())} bytes; next {server}")
walk.py: an iterative lookup from the root down
asking a root server 198.41.0.4 for example.com step 1: referral to com. -> l.gtld-servers.net., 13 NS TCP, 825 bytes; next 192.41.162.30 step 2: referral to example.com. -> hera.ns.cloudflare.com., 2 NS UDP, 348 bytes; next 108.162.192.162 step 3: ANSWER example.com. 300 IN A 104.20.23.154 (UDP)
One real run on 2026-11-22. Addresses and TTLs can change.
Three steps matched the scene. The root server did not know example.com, but it knew who runs com. and listed 13 servers, with their addresses in the same reply. An address sent along with a referral is called glue. It saves the resolver a separate lookup, and when a server's name sits inside the zone it serves, such as ns1.registry.in for in, glue is the only way to reach it without a loop. The com. server referred the question on to the two servers of example.com. The last server answered with an A record whose TTL, the time a copy may be cached, is 300 seconds.
The first step also shows a limit from RFC 1035: a DNS message sent over UDP may carry at most 512 bytes. The root's referral, with 13 names and their addresses, came to 825 bytes, so the UDP reply was cut short and flagged as truncated, and udp_with_fallback asked again over TCP, as the line TCP, 825 bytes under it records. A later extension, EDNS(0) in RFC 6891, lets a client say that it accepts larger UDP replies, which avoids most of these retries. The program sends plain queries without it, so you can see the fallback happen.
Part 3 · Record types
What a record holds
A DNS zone is a list of resource records. Each has a name, a type, a TTL (how long it may be cached, in seconds) and a value whose shape depends on the type. A handful of types cover almost every design.
| Type | Holds | Typical use |
|---|---|---|
| A | An IPv4 address | Point a name at a server |
| AAAA | An IPv6 address | The same, for IPv6 clients |
| CNAME | Another name | Make one name an alias of another |
| MX | A mail server and a preference | Say where email for the domain goes |
| NS | A name server | Delegate a zone, or name its servers |
| TXT | Free text | Proofs of ownership, email policy |
| SOA | Zone parameters: serial, timers, a negative-caching value | One per zone, written by its owner |
A CNAME says that a name is only another name for something else, and a resolver then looks up the target. The classic example is a site whose www name points at the hostname of a hosting provider, so the provider can change the address without the owner touching the zone. RFC 1034 says that a name with a CNAME should carry no other data (DNSSEC later added an exception for its own signature records). That is why the bare domain, which must also hold the zone's NS and SOA records, cannot be a CNAME. Some DNS providers offer a non-standard alias feature for this case: the provider looks up the target itself and answers with plain A and AAAA records.
The records in a real zone
The program asks for each type in turn from 8.8.8.8, using dnspython 2.9.2 and Python 3.12.10, and prints how many records came back and the first one. Long values are cut to 34 characters so lines stay short.
import dns.resolver r = dns.resolver.Resolver(configure=False) r.nameservers = ["8.8.8.8"] queries = [("example.com", "A"), ("example.com", "AAAA"), ("www.iana.org", "CNAME"), ("iana.org", "MX"), ("example.com", "NS"), ("example.com", "TXT"), ("example.com", "SOA")] for name, rtype in queries: answer = r.resolve(name, rtype) first = sorted(answer, key=str)[0] shown = str(first)[:34] print(f"{rtype:5} {name:12} {len(answer)} record(s): {shown}")
types.py: one query per record type
A example.com 2 record(s): 104.20.23.154 AAAA example.com 2 record(s): 2606:4700:10::6814:179a CNAME www.iana.org 1 record(s): www.iana.org.cdn.cloudflare.net. MX iana.org 4 record(s): 10 pechora1.icann.org. NS example.com 2 record(s): elliott.ns.cloudflare.com. TXT example.com 2 record(s): "_k2n1y4vw3qtb4skdx9e7dxt97qrmmq9" SOA example.com 1 record(s): elliott.ns.cloudflare.com. dns.clo
One real run.
example.com has two A records and two AAAA records, so a client has a choice of addresses. The name www.iana.org is a CNAME: the answer is another name, at a content delivery network, and a resolver would continue by looking that name up. The domain iana.org has four MX records, and the one shown has preference 10. The TXT value is a verification token, the kind a service asks you to publish to prove that you control the domain.
Two habits follow from the table. Publish both A and AAAA records for a name when your servers speak IPv6, so clients that prefer IPv6 can use it directly. And keep the TTL in mind whenever you edit a record: every record carries its own TTL, and an edit reaches users only as old copies expire.
Why can the bare domain example.com not normally be a CNAME?
- A name with a CNAME may hold no other records, and a zone's top name must hold SOA and NS records.
- So the owner uses A and AAAA records there, and CNAME for names like
www.
A mail domain has MX records with preference 10 and 20. Which server is tried first?
Part 4 · Caching, TTLs and negative caching
Every layer keeps a copy
Looking up a name through three servers for every request would be slow and would flood the authoritative servers. So every layer between the app and the authority keeps a copy of the answer: the program, the operating system, the router, and above all the recursive resolver. The record's TTL, set by the zone owner, says how many seconds a copy may be used before it must be fetched again.
Watch for the cache: the second lookup never leaves the resolver
Read it as steps
A model with a 300 s TTL: a lookup 60 s after the first is served from the cache; once the TTL runs out the resolver asks the authority again.
The scene is a model, not a run: it assumes the 300-second TTL that the authority returned in the walk, and a second lookup 60 seconds after the first, which leaves 240 seconds on the cached copy. After expiry the resolver goes straight to the authoritative server, because it still holds the NS records for example.com, which carry their own TTL. The first lookup pays for the walk. Every phone served by the same resolver within the TTL gets the answer straight from the resolver's memory, without the extra trips. The cost of the cache is staleness: if the owner changes the address while copies are held, some users keep going to the old one until their copy expires.
Seeing the cache work
A resolver object in dnspython can carry its own cache. The program queries the same name three times, with a local Cache attached, and prints the time each lookup took. The programs ask public resolvers on 2026-11-22, so live answers on your day may differ.
import time import dns.resolver r = dns.resolver.Resolver(configure=False) r.nameservers = ["1.1.1.1"] r.cache = dns.resolver.Cache() # a local cache in this process for i in (1, 2, 3): start = time.perf_counter() ans = r.resolve("example.com", "A") ms = (time.perf_counter() - start) * 1000 print(f"lookup {i}: {ms:7.2f} ms, record TTL {ans.rrset.ttl} s")
cache.py: three lookups, one network trip
lookup 1: 5.50 ms, record TTL 93 s lookup 2: 0.05 ms, record TTL 93 s lookup 3: 0.02 ms, record TTL 93 s
One real run. Times vary; the pattern does not.
The first lookup went over the network to 1.1.1.1 and took about 5.5 ms. The next two were answered from the program's own memory in a few hundredths of a millisecond, about a hundred times faster. The TTL stayed at 93 seconds across the three calls because the local cache returned the stored answer unchanged. The 93 is itself a cached value: the authority hands out 300 seconds, and the resolver at 1.1.1.1 reports how much of its own copy is left.
Watching that remaining TTL over a few seconds shows something about a public resolver. Another program asked 1.1.1.1 for the same record three times, two seconds apart, and printed the TTL it saw. It was run several times on this machine; two of those runs are shown.
import time import dns.resolver r = dns.resolver.Resolver(configure=False) r.nameservers = ["1.1.1.1"] for i in range(3): ans = r.resolve("example.com", "A", lifetime=3) ttl = ans.rrset.ttl print(f"query {i + 1}: TTL {ttl} s") time.sleep(2)
ttl.py: three queries with a pause between them
query 1: TTL 93 s query 2: TTL 91 s query 3: TTL 89 s
Run A: a steady countdown.
query 1: TTL 75 s query 2: TTL 61 s query 3: TTL 176 s
Run B, shortly after: the third answer jumps.
Run A counted down by about two seconds per query, as one cache would. Run B fell from 75 to 61 although only about two seconds passed, then jumped to 176; no single cache does either. The program cannot see inside the resolver, so it cannot say why. One explanation that fits is that the address 1.1.1.1 is served by more than one cache, filled at different times, and successive queries reached different ones. Whatever the cause, the design lesson holds: a TTL is an upper bound on how long a copy may live, and you cannot predict which copy a given user will see or how old it is.
Caching a missing name
A lookup can also fail with an answer. NXDOMAIN means the name does not exist at all. NODATA means the name exists but has no record of the requested type. Resolvers cache these negative answers too, otherwise a mistyped name asked ten lakh times would reach the authority ten lakh times. RFC 2308 sets the rule: the negative answer may be cached for the lower of the SOA record's own TTL and the SOA's minimum field. It also asks resolvers to apply their own upper limit, and suggests one to three hours as a default.
import time import dns.message import dns.query import dns.rcode NAME = "no-such-name-7305.iana.org" SERVERS = [("authority", "199.43.135.53"), # a.iana-servers.net ("resolver ", "8.8.8.8"), ("resolver ", "8.8.8.8")] for label, server in SERVERS: q = dns.message.make_query(NAME, "A") resp = dns.query.udp_with_fallback(q, server, timeout=3)[0] soa = [rs for rs in resp.authority if rs.rdtype == 6][0] print(f"{label} {server:13} {dns.rcode.to_text(resp.rcode())}, " f"SOA ttl {soa.ttl} s, MINIMUM {soa[0].minimum} s") time.sleep(3)
negative.py: ask for a name that does not exist
authority 199.43.135.53 NXDOMAIN, SOA ttl 3600 s, MINIMUM 3600 s resolver 8.8.8.8 NXDOMAIN, SOA ttl 1800 s, MINIMUM 3600 s resolver 8.8.8.8 NXDOMAIN, SOA ttl 1797 s, MINIMUM 3600 s
One real run for a made-up name under iana.org, asked first of the zone's own server, then twice of a public resolver.
The negative reply carries the zone's SOA record in its authority section. Straight from the authority, a.iana-servers.net, it came with a TTL of 3,600 seconds and a minimum of 3,600, so the rule allows the negative answer to be cached for an hour. The public resolver reported 1,800 seconds instead: it keeps the answer for less than the zone allows, which the RFC's upper limit permits. Three seconds later the same resolver said 1,797, so the negative answer was being served from its cache and counting down.
The practical effect: if someone asks for a name just before you create it, resolvers that cached the NXDOMAIN keep saying it does not exist until their copy expires, here for up to half an hour, and up to an hour where a resolver uses the zone's full value.
A site owner changes an address and the record's TTL is 3,600 seconds. What is the longest a user can keep going to the old address?
Part 5 · DNS for spreading load
Many addresses behind one name
DNS can do more than point to one server. A name can have several A records, and the answer carries all of them. Many servers and resolvers vary the order from one answer to the next, and many clients try the first address first, so successive clients tend to land on different servers. This is round-robin DNS, the cheapest form of load spreading.
The program below asks the same question four times and prints the records in the order they came back.
import dns.resolver r = dns.resolver.Resolver(configure=False) r.nameservers = ["8.8.8.8"] for i in range(1, 5): ans = r.resolve("example.com", "A") print(f"query {i}:", ", ".join(str(a) for a in ans))
multi.py: four lookups of one name
query 1: 172.66.147.243, 104.20.23.154 query 2: 104.20.23.154, 172.66.147.243 query 3: 172.66.147.243, 104.20.23.154 query 4: 172.66.147.243, 104.20.23.154
One real run.
The order changed between queries, though not on every one, and nothing promises a strict rotation. Over many users, clients that take the first record spread their traffic over both addresses. These two addresses belong to a content delivery network, and such networks commonly announce one address from many places (anycast, in the last lesson of this chapter), so each address is not one machine.
A smarter authoritative server can pick the answer per question. A geo-aware answer returns the address of the data centre nearest to the resolver that asked. A health-aware answer leaves out a server that failed its checks. The DNS provider does the choosing at lookup time, so the client needs no special code.
Several records also help when one address fails, but only if the client uses them. A client that gets two addresses can try the second when the first does not answer. Browsers and many HTTP libraries do this, and RFC 8305, Happy Eyeballs, describes how a client tries IPv6 and IPv4 addresses in quick succession instead of waiting for one to time out. A client that keeps only the first address gets no such help.
What DNS cannot do
DNS balancing is coarse. The server that answers does not see the load on your machines, and it cannot react after it has answered. Three limits matter in a design.
| Limit | Why it happens | What to do |
|---|---|---|
| Slow failover | Resolvers and clients keep an answer for its TTL, so a dead address stays in use | Use a short TTL for names that need fast failover, and accept the extra queries |
| Uneven shares | One resolver may serve a whole company, so one answer carries all of that traffic | Put a load balancer behind the DNS answer for fine-grained spreading |
| Stuck clients | Some programs look up a name once and keep the address until they restart | Make clients retry with a fresh lookup after a failure |
A rough bound for failover time follows from the TTL. If the answer's TTL is 60 seconds and a server dies, users whose resolvers cached the answer one second before the failure keep trying the dead address for up to 59 more seconds. A TTL of 300 seconds stretches that to nearly five minutes. DNS is good at sending users to the right region and the right front door. Spreading load across servers inside a region is usually done by a load balancer, which the next chapter describes.
Why does round-robin DNS spread load only roughly?
- The authority does not see server load, and a resolver that caches the answer sends all its users to the same address.
- Shares become equal only across many independent users.
A server fails and its record's TTL is 120 seconds. How long can some users still be sent to it?
- Up to about two minutes, from the users whose resolvers cached the answer just before the failure.
Part 6 · Failures and attacks
When a resolver or an authority stops answering
DNS sits in front of everything, so its failures look like the failure of everything. Two different parts can break, and they break differently.
If the recursive resolver is down, the user's phone cannot look up names it has not cached. Apps that already hold an address keep working until they need a new lookup. Switching to another resolver restores service, which is why public resolvers exist as a second choice. RFC 8767 describes serve-stale, a feature in which a resolver that cannot reach the authority answers with an expired record rather than with nothing, because an old address is usually better than none.
If the authoritative servers are down, nobody can learn the name's address once the cached copies expire. This is why RFC 1034 asks for every zone to be available on at least two servers, and why careful owners put them on separate networks, and sometimes with separate providers. A long TTL gives resolvers more time to ride through a provider outage, and it also slows every planned change, so the TTL is a trade between the two.
Before a planned address change, lower the TTL a few TTLs in advance. Once copies of the short-lived record are everywhere, the switch takes effect in minutes.
A dead resolver in code
A device is usually given more than one resolver, and the stub tries them in order. What a failure costs depends on how the first one fails. The program below starts three tiny DNS servers on this machine: one that never replies, like a resolver that has crashed or is unreachable, one that answers every query with SERVFAIL, the code a resolver returns when it could not get an answer, and one that answers. It then looks up a made-up name with the servers in different orders, using dnspython 2.9.2 with a one-second timeout per server and three seconds for the whole lookup.
import socket import threading import time import dns.message import dns.rcode import dns.resolver import dns.rrset from dns.nameserver import Do53Nameserver def fake_server(port, mode): """A tiny DNS server: 'silent' never replies, 'servfail' fails.""" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.bind(("127.0.0.1", port)) def loop(): while True: data, addr = sock.recvfrom(512) if mode == "silent": continue # like a dead resolver query = dns.message.from_wire(data) reply = dns.message.make_response(query) if mode == "servfail": reply.set_rcode(dns.rcode.SERVFAIL) else: reply.answer.append(dns.rrset.from_text( "shop.example.", 60, "IN", "A", "192.0.2.10")) sock.sendto(reply.to_wire(), addr) threading.Thread(target=loop, daemon=True).start()
resolver_fail.py, part 1: a tiny DNS server in three moods
PORTS = {"silent": 55442, "servfail": 55443, "good": 55444}
for mode, port in PORTS.items():
fake_server(port, mode)
def lookup(order):
r = dns.resolver.Resolver(configure=False)
r.nameservers = [Do53Nameserver("127.0.0.1", PORTS[m])
for m in order]
r.timeout, r.lifetime = 1.0, 3.0 # per server, whole lookup
start = time.perf_counter()
try:
ans = r.resolve("shop.example.", "A")
result = f"{ans[0]} from port {ans.port}"
except Exception as e:
result = type(e).__name__
ms = (time.perf_counter() - start) * 1000
print(f"{' then '.join(order):20} {ms:6.0f} ms {result}")
lookup(["good"])
lookup(["silent", "good"])
lookup(["servfail", "good"])
lookup(["silent", "servfail"])resolver_fail.py, part 2: the same lookup with the servers in different orders
good 3 ms 192.0.2.10 from port 55444 silent then good 1010 ms 192.0.2.10 from port 55444 servfail then good 1 ms 192.0.2.10 from port 55444 silent then servfail 3415 ms LifetimeTimeout
One real run on Python 3.12.10. Everything stays on this machine; the address is from the range reserved for documentation.
Attacks on the lookup
Because everyone trusts the answer, DNS is a target. Three attacks come up often.
| Attack | What the attacker does | Defence |
|---|---|---|
| Cache poisoning | Tricks a resolver into storing a false answer, by forging a reply that matches the query | Random query ids and source ports; signed records (DNSSEC) that the resolver can check |
| Flooding the authority | Sends a flood of queries to the zone's servers so real users cannot get through | Many servers, anycast, a provider with spare capacity, long TTLs |
| Reflection | Spoofs a victim's address so that large DNS replies go to the victim | Rate-limit responses and filter spoofed traffic at the edge |
DNSSEC adds digital signatures to DNS data so a resolver can verify that an answer came from the zone's owner and was not changed. It protects the content of the answer, not the privacy of the question. Privacy is a separate fix: DNS over TLS (RFC 7858) and DNS over HTTPS (RFC 8484) encrypt the query between the client and its resolver.
Anycast
Anycast is the main tool against floods. Many machines in many places announce the same IP address, and the network routes each packet to the nearest one in routing terms, which is usually, though not always, a nearby site. A flood is then spread over all those places instead of landing on one. It is also how 13 root server names reach 2,046 instances: each name is one address announced from many sites.
| Term | Meaning |
|---|---|
| Zone | The part of the namespace one set of servers is responsible for |
| Authoritative server | A server that holds a zone's records itself |
| Recursive resolver | A server that finds the final answer on behalf of a client |
| Referral | A reply that names servers closer to the answer |
| TTL | How many seconds a cached record may be used |
| NXDOMAIN | The answer that a name does not exist |
| Anycast | One address announced from many places, served by the nearest |
A resolver is down. Which users notice first?
- Those whose phones need a name they have not cached. Apps that already hold an address keep working until they look up a new name.
- Switching to a different resolver restores service.
What does anycast change for a flood aimed at one DNS address?
- The flood is split across the machines in many places that announce the address, rather than hitting one machine.
- It does not stop the flood, but it raises the capacity needed to cause an outage.
All chapters · Previous: Building Blocks: The Parts Every Design Reuses