Summary#
DNS turns names like shop.example.com into IP addresses. It is a global, hierarchical, heavily cached database: root servers point to TLD servers (.com), which point to the domain's authoritative servers, which hold the actual records. A recursive resolver does this walk for clients and caches answers for the record's TTL. Managed DNS can also route traffic by weight, latency, geography or health, but caching makes DNS-based changes slow and coarse.
Why It Exists#
Humans remember names; networks route by IP address. Addresses also change: servers are replaced, traffic moves between regions, providers change. DNS adds a layer of indirection so the name stays fixed while the addresses behind it change.
Because every request starts with a DNS lookup, DNS is also the first place you can steer traffic: send European users to the EU region, or drain a failed region. This page goes deeper than the brief overview in What Happens When You Type a URL.
How It Works#
Where DNS came from#
Before DNS, every computer on the ARPANET found others through a single file, HOSTS.TXT, maintained centrally at SRI's Network Information Center and copied by every host. By the early 1980s the file was changing constantly, copies were always out of date, and downloading it was becoming a real load on the network. Paul Mockapetris designed DNS in 1983 (RFCs 882 and 883, replaced in 1987 by RFCs 1034 and 1035, which still define the core protocol). The design principles explain almost everything on this page:
- Delegate authority. No central list. Each organisation runs its own part of the name space, and the parent only records who that is.
- Cache everywhere. Answers carry a TTL, so any server can keep them for a while, and the load on authoritative servers stays small.
- Keep the protocol small and stateless. One UDP packet each way, with no connection to set up.
The trade-off chosen in 1983, aggressive caching in exchange for slow change, is the same trade-off you make today every time you pick a TTL.
The hierarchy#
- Root servers know where each top-level domain's servers are. There are 13 named root server identities, each served from many anycast sites.
- TLD servers handle top-level domains like
.com,.orgor.uk, and know which name servers are authoritative for each domain under them. - Authoritative servers hold the actual records for a domain (often run by a managed DNS provider). Their answers are the source of truth.
The hierarchy in more depth#
A domain name is a path in a tree, read from right to left. shop.example.com. really ends with a dot: the unnamed root. Below it sit top-level domains (com), below those registered domains (example), and below those any names the owner creates (shop). Each level can hand responsibility for a subtree to someone else. That act is delegation, and the unit of responsibility is a zone.
How delegation works. The .com servers do not know your IP addresses. They hold only NS records saying which name servers are authoritative for example.com. If those name servers live inside the zone they serve (for example ns1.example.com), the parent also publishes their IP addresses as glue records. Without glue there would be a chicken-and-egg problem: you would need to resolve ns1.example.com to find the server that resolves example.com.
Why exactly 13 root names? The full list of root servers, with addresses, had to fit in a single 512-byte UDP response, the classic DNS size limit. Thirteen names, a.root-servers.net to m.root-servers.net, fit. The names stayed at 13, but each is now served by anycast from many locations, well over a thousand instances worldwide, so the root is among the most widely replicated services on the internet. Because resolvers cache TLD referrals for a long time (two days is typical), the root sees only a tiny fraction of all lookups.
Who owns what. IANA, a function of ICANN, maintains the root zone. A registry runs each TLD (Verisign runs .com). A registrar (such as a domain-selling company) sells names and passes your NS records to the registry. You, the registrant, hold the name for as long as you pay. There are three kinds of TLD: generic ones (.com, .org), country codes (.uk, .de, .in), and more than a thousand newer generic TLDs (.app, .dev) added since 2013. Some of these enforce rules: .app and .dev are on the browser HSTS preload list, so they only work over HTTPS.
Expiry is a real outage cause. If a domain lapses, the registry stops publishing its NS records and everything under it disappears at once: website, API, email, and every certificate validation that depends on it. Large companies have had public outages from forgotten renewals. Auto-renewal, registry locks against unauthorised transfers, and monitoring of expiry dates belong in the runbook of any production domain.
Recursive vs iterative resolution#
Your device asks a recursive resolver (from your ISP, company, or a public service such as 1.1.1.1 or 8.8.8.8) to find the full answer. The resolver performs iterative queries: it asks root, gets a referral to the TLD, asks the TLD, gets a referral to the authoritative server, and asks that server for the record.
A cold lookup can take tens to a couple of hundred milliseconds. Most lookups are answered from a cache in under a few milliseconds.
Resolution in more depth#
The first resolver is on your machine. Applications call the operating system's stub resolver (for example getaddrinfo). It checks the local hosts file, its own cache (systemd-resolved on many Linux systems, mDNSResponder on macOS), and only then sends a query to the configured recursive resolver. The stub asks one question and expects a complete answer. It does not walk the tree itself. That is the real difference between the two modes:
| Recursive query | Iterative query | |
|---|---|---|
| Who sends it | A stub resolver to a recursive resolver | A recursive resolver to authoritative servers |
| What it asks for | "Give me the final answer" | "Answer if you can, otherwise tell me who to ask" |
| What comes back | The answer, or an error | The answer, or a referral to another server |
| Who caches | The recursive resolver, for all its clients | The recursive resolver, for referrals and answers |
CNAME chains add steps. Many names point at a CDN or cloud load balancer through a CNAME. The resolver must then resolve the target too, which may involve the CDN's own DNS deciding which edge to return:
Each extra hop in a chain costs a lookup when it is not cached, so keep chains to one or two links.
Transport. Queries go over UDP port 53 in a single packet each way, which is why DNS is fast: there is no handshake. Answers larger than the client's advertised buffer (512 bytes classically, typically about 1,232 bytes with EDNS0 today) are truncated, and the client retries over TCP. Encrypted variants run over TLS (DoT, port 853), HTTPS (DoH, port 443) or QUIC (DoQ).
Typical timings. A cached answer from a resolver in the same city: 1-10 ms. A cold lookup needing referrals from root, TLD and authoritative servers: 50-200 ms, sometimes more if a far-away authoritative server is involved. In practice the TLD referral is almost always cached, so a "cold" lookup usually costs one round trip from the resolver to the authoritative servers. A managed DNS provider with anycast keeps that round trip short everywhere.
Spoofing and the Kaminsky attack. A resolver accepts an answer if it matches the query it sent. For years the only secret in that match was a 16-bit query ID, which an attacker could guess by flooding forged answers. In 2008 Dan Kaminsky showed how to make this practical: by asking for many random non-existent subdomains, an attacker gets endless chances to win the race, and a forged answer can then inject a false record for the whole domain. The urgent fix, coordinated across vendors, was source port randomisation, which adds about 16 more bits that the attacker must guess. The lasting fix is DNSSEC (see the deep dive at the end).
Public resolvers. Instead of an ISP's resolver, users and companies can use Google Public DNS (8.8.8.8, launched in 2009), Cloudflare (1.1.1.1, 2018) or Quad9 (9.9.9.9, which blocks known malicious domains). They are fast and well run, but they also change what authoritative servers see: the query appears to come from the resolver's location, which may be far from the user. That matters for geographic routing.
Caching and TTL#
Every record has a TTL (time to live) in seconds. Browsers, operating systems and resolvers cache the answer for that long. Caching makes DNS fast and keeps load on authoritative servers low, but it means changes are not instant: after you change a record, some clients use the old answer until their cached copy expires. Some resolvers and clients also hold records longer than the TTL.
Typical choices: 300-3600 seconds for stable records; 30-60 seconds for records you may need to fail over quickly. Lower TTLs mean more queries and slightly slower average lookups.
Caching and TTL in more depth#
Many caches, not one. An answer can be cached in the browser (Chrome keeps its own short cache), the operating system, a local network device, the recursive resolver, and the application runtime itself. Runtimes are the usual surprise. The Java virtual machine caches successful lookups according to networkaddress.cache.ttl, and older setups could cache them for the life of the process. Long-lived connections ignore DNS entirely: a connection pool opened yesterday still talks to yesterday's IP, however short the TTL.
"DNS propagation" is really cache expiry. Nothing is pushed out when you change a record. The authoritative server answers with the new value at once, and each cache keeps serving the old value until its copy reaches the end of its TTL. A safe change therefore follows a timeline:
- Days before: lower the record's TTL from, say, 3,600 to 60 seconds.
- Wait at least the old TTL (one hour) so every cache has picked up the short TTL.
- Make the change. Within about a minute most clients follow it.
- Keep the old target running until traffic on it has drained, which can take hours for clients that cache badly.
- Raise the TTL again.
TTL and query volume. A resolver sends at most one query per TTL period per record, however many users ask it. With a 300-second TTL, each busy resolver asks about 288 times a day. With 30 seconds, 2,880 times. Spread over thousands of resolvers, short TTLs multiply authoritative traffic and the chance of a cold, slower lookup for users. Managed providers charge per query, so a 10x shorter TTL can mean a noticeably larger bill on a popular domain. A common pattern is long TTLs (hours) on records that rarely change, such as MX, NS and verification TXT records, and 30-60 seconds only on records used for failover.
Negative caching. "No such name" (NXDOMAIN) answers are cached too, for the negative TTL defined in the zone's SOA record. If a client asks for new.example.com a minute before you create it, it may keep getting "does not exist" until that negative TTL runs out. Keep negative TTLs modest, such as 5 minutes, and create records before announcing them.
Serve-stale. RFC 8767 lets resolvers keep answering from expired cache entries when the authoritative servers cannot be reached, while retrying in the background. Large public resolvers do this. It turns a short outage of your DNS provider into slightly stale answers instead of total failure, which is a strong argument for not setting TTLs so short that caches empty within seconds of a problem.
Reading a DNS answer#
When DNS misbehaves, dig shows exactly what a server said. A few fields in every response tell you most of what you need:
$ dig api.example.com A
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 40211
;; flags: qr rd ra; QUERY: 1, ANSWER: 2, AUTHORITY: 0, ADDITIONAL: 1
;; ANSWER SECTION:
api.example.com. 42 IN A 203.0.113.10
api.example.com. 42 IN A 203.0.113.11
;; Query time: 3 msec
;; SERVER: 10.0.0.2#53- Status (RCODE).
NOERRORmeans the query succeeded. It can still have zero answers, which means the name exists but has no record of that type.NXDOMAINmeans the name does not exist at all.SERVFAILmeans the resolver could not get a valid answer: often the authoritative servers are unreachable, or DNSSEC validation failed.REFUSEDmeans the server will not answer you, such as an authoritative server asked about a zone it does not host. - Flags.
rd(recursion desired) was set by the client.ra(recursion available) means the server is a recursive resolver.aa(authoritative answer) appears only when you asked the authoritative server directly.tc(truncated) means the answer did not fit and the client should retry over TCP. - The TTL in the answer counts down. From a resolver's cache,
42means 42 seconds remain before this cached copy expires, not that the record's TTL is 42. Asking the authoritative server directly (dig @ns1.provider.net api.example.com) shows the configured value. - Query time separates a cache hit (a few milliseconds) from a full lookup (tens to hundreds).
Two habits save time. Compare the answer from your usual resolver with the answer straight from the authoritative server: if they differ, you are looking at a cache. And use dig +trace to follow the delegation from the root yourself, which reveals broken NS records or missing glue.
Record types#
| Type | Maps | Example use |
|---|---|---|
| A | Name to IPv4 address | shop.example.com -> 203.0.113.10 |
| AAAA | Name to IPv6 address | shop.example.com -> 2001:db8::10 |
| CNAME | Name to another name (alias) | www.example.com -> shop.cdn-provider.net |
| MX | Domain to mail servers, with priority | Email delivery |
| NS | Domain to its authoritative name servers | Delegation from the TLD |
| TXT | Name to free text | Domain verification, SPF/DKIM email security |
A CNAME cannot sit at the domain apex (example.com) alongside other records, so providers offer "ALIAS" or "ANAME" records that behave like a CNAME at the apex.
More record types, and what they are for#
The six common types cover most designs, but several others show up as soon as you run a real domain:
| Type | What it holds | Why you meet it |
|---|---|---|
| SOA | Zone metadata: primary server, admin contact, serial number, refresh timers, negative-cache TTL | Every zone has exactly one. Its serial number tells secondary servers when to copy changes |
| PTR | IP address back to a name (reverse DNS) | Mail servers reject or downgrade mail from IPs without sensible reverse DNS |
| SRV | Service location: priority, weight, port and host | SIP and XMPP, mongodb+srv:// connection strings, Kubernetes named ports |
| CAA | Which certificate authorities may issue certificates for the domain | Stops other CAs from issuing for your name, even if tricked |
| HTTPS / SVCB | Connection hints: supported protocols such as HTTP/3, alternative endpoints, ECH keys | Lets browsers use QUIC on the very first connection |
| DS, DNSKEY, RRSIG | DNSSEC keys and signatures | Proving records are authentic (see the deep dive) |
Email depends on DNS. Three TXT-based mechanisms decide whether your mail is trusted:
- SPF lists which servers may send mail for your domain.
- DKIM publishes a public key, and your mail servers sign each message with the matching private key.
- DMARC tells receivers what to do when SPF or DKIM checks fail (nothing, quarantine, or reject) and where to send reports.
Large mailbox providers now require all three from anyone sending bulk mail, so a system that sends notifications, receipts or password resets needs them configured correctly from day one.
CNAME rules. A name with a CNAME may have no other records, because the CNAME says "this name is really that other name". That is why a CNAME cannot sit at the zone apex, which must also hold SOA and NS records. Providers' ALIAS, ANAME or "CNAME flattening" features solve this by resolving the target themselves and returning plain A or AAAA records. One subtle cost: the target, often a CDN, now sees the lookup coming from your DNS provider instead of from the user's resolver, so the CDN's own geographic steering can be less precise unless the provider forwards client subnet information.
Wildcards. A record such as *.example.com answers for any name that has no record of its own. Multi-tenant products use this (customer1.example.com, customer2.example.com all reach the same load balancer, which reads the Host header). Wildcard TLS certificates pair naturally with it.
DNS traffic routing#
Managed DNS providers can return different answers to different users:
| Policy | How it decides | Use |
|---|---|---|
| Simple / round robin | Returns several IPs, rotating order | Basic spreading over a few servers |
| Weighted | Returns targets in proportion to weights | Canary releases (5% to new stack), migrations |
| Latency-based | Returns the region with the lowest measured latency for the resolver | Multi-region apps |
| Geolocation / geoproximity | Based on the user's (resolver's) location | Data residency, localised content |
| Failover | Returns a primary unless its health check fails, then a secondary | Disaster recovery |
Traffic routing in more depth#
How the provider decides. A DNS server only sees the query, which comes from a resolver, not from the user. It decides from the resolver's IP address, plus anything the resolver forwards:
- Geolocation maps the resolver IP (or the forwarded client subnet) to a country or region using an IP geolocation database.
- Latency-based routing uses the provider's own measurements of latency from networks around the world to each of your regions, and returns the region that is fastest for the network the query came from.
- EDNS Client Subnet (ECS, RFC 7871) lets a resolver include a truncated prefix of the user's address, such as a /24, so the authoritative server can answer for the user's real location. It improves accuracy for users of distant public resolvers but reveals a little about the user, so some privacy-focused resolvers (Cloudflare's 1.1.1.1, for example) do not send it.
Health checks drive failover. The provider probes each endpoint from several locations every 10 or 30 seconds, and marks it unhealthy only when probes from multiple locations fail several times in a row. Requiring agreement prevents one flaky probe location from failing over a healthy region. The total failover time is the sum of several parts:
- Detection: 3 failed checks x 10 s = about 30 s.
- Cached answers expiring: up to the TTL, say 60 s.
- Clients that cache longer or keep connections open: anything from seconds to hours.
So "DNS failover" in practice means one to two minutes for most users, and a long tail. That is fine for disaster recovery and too slow for fast failover inside a region.
Combining policies. Real setups nest policies into a decision tree:
Weighted records for safe change. To move traffic to a new stack or provider, start with weights such as 99 to 1, watch error rates and latency, then shift step by step: 10%, 50%, 100%. Because caches hold answers, every step takes at least one TTL to take full effect, and the split is approximate. One large resolver serving millions of users counts as one client to DNS, so a 1% weight can land as 0% or 5% for a while.
DNS as load balancing, and its limits#
Returning several IPs or different IPs per region spreads traffic, but DNS is a coarse tool:
- Caching delays changes. Failover takes at least the TTL, often longer for misbehaving clients.
- No per-request control. DNS picks a server once per lookup, not per request, and cannot see server load.
- Resolver location, not user location. A user using a distant public resolver may be routed to the wrong region (the EDNS Client Subnet extension helps when supported).
- Clients cache unevenly, so traffic splits are approximate.
So DNS usually picks a region, and a load balancer spreads requests across servers inside it.
DNS as client-side load balancing#
DNS load balancing is really client-side load balancing. The server side (DNS) hands out a list of addresses, often in rotated order, and each client decides which one to connect to. Different clients get different orders, so they spread across servers without any central balancer on the data path.
That model has a clear rule for when it works. Client-side balancing is good when either the clients are few and under your control (gRPC clients inside your services, the Redis Cluster client that learns the shard map and follows MOVED redirects), or the clients are many but slow updates are acceptable, which is the DNS case. Updates reach DNS clients only as fast as caches expire. That is the price of serving billions of clients without contacting each one.
The most useful application is not spreading load across application servers, but removing the load balancer as a single point of failure. Run two or more load balancers, ideally in different zones or regions, and publish all their addresses for the name. If one fails, health-checked DNS stops returning it, and clients that already have both addresses can try the other one at once.
How clients actually use multiple addresses.
- Browsers try the next address when a connection fails, and use Happy Eyeballs (RFC 8305) to race IPv6 and IPv4 attempts a few hundred milliseconds apart, so a broken path costs little.
- Many HTTP client libraries and older applications take the first address only. If that host is down, they fail even though other addresses would work.
- Connection pools and long-lived connections (HTTP/2, gRPC, WebSockets) stay on the address they connected to until the connection closes, whatever DNS says later. Forcing a maximum connection age is how such clients eventually follow DNS changes.
- Resolvers may reorder, trim or cache the list, so you do not control which address a given user gets.
Do not forget the client. Client behaviour is part of the design. For mobile apps, it can be worth building logic into the app itself: retry the next address, keep a warm connection, cache the last good endpoint, or adapt how often to contact the server. Ride-hailing apps, for instance, send driver location updates more or less often depending on speed and trip state, to cut load without losing accuracy. A few lines of client logic often do more than any server-side DNS trick.
| Mechanism | Granularity | Failover speed | Sees server load? | Typical role |
|---|---|---|---|---|
| DNS round robin or weighted | Per lookup, per resolver | TTL plus caching tail (minutes) | No | Spreading across load balancers or regions |
| DNS latency or geo routing with health checks | Per resolver location | About 1-2 minutes for most users | No, only up or down | Choosing a region |
| Anycast (one IP announced from many sites) | Per packet, by BGP routing | Seconds, when a site withdraws its route | No | DNS servers, CDNs, global front ends |
| Global L7 load balancer (anycast front end) | Per request | Seconds | Yes | Multi-region apps needing fast failover |
| Regional load balancer | Per connection or request | Health-check interval (seconds) | Yes | Spreading across servers in a region |
Estimating DNS load and cost#
Authoritative query volume depends on the number of resolvers asking and on the TTL, not directly on the number of users, because each resolver answers its own users from cache. A back-of-the-envelope estimate:
- Suppose 100,000 distinct resolvers around the world look up
api.example.comsteadily throughout the day. - With a 60-second TTL, each one asks at most once a minute: 100,000 x 1,440 = 144 million queries per day, about 1,700 queries per second on average for one name.
- With a 300-second TTL, that falls to about 29 million per day, around 330 per second.
Managed providers typically charge a few tenths of a dollar per million standard queries, and more for latency or geo-routed records. At those rates, the 60-second version costs a few thousand dollars a month for this single name, and the 300-second version a fifth of that. For most products the cost is small next to compute, but it is a real line item for very popular names with very short TTLs. Multiply by every hostname a page loads, and add random-subdomain attack traffic, which bypasses caches entirely and is billed like any other query unless the provider filters it.
The estimate also shows why authoritative DNS scales so well. Even a hugely popular service sees only thousands of queries per second at its authoritative servers, because the resolver caches absorb nearly all of the billions of user lookups.
Encrypted DNS and what it changes#
Classic DNS travels in clear text, so anyone on the network path can see which names a user looks up, and can tamper with answers. DNS over TLS (DoT, port 853) and DNS over HTTPS (DoH, port 443) encrypt the connection between the client and its resolver. DNS over QUIC does the same over QUIC.
For users this means privacy from the local network and protection from tampering on the way to the resolver. For companies it changes some assumptions:
- A browser using DoH with a public resolver bypasses the company's resolver, and with it any internal split-horizon names and security filtering. Browsers therefore disable their own DoH when they detect managed enterprise settings. Firefox, for example, checks a special "canary" domain,
use-application-dns.net, which a network can make fail to signal that DoH should stay off. - Network-level DNS monitoring for malware loses visibility. Security teams move to controlling the endpoints and running their own encrypted resolvers instead.
- Encryption covers only client to resolver. The resolver itself still sees every query, so choosing a resolver means choosing whom to trust.
Managed DNS#
Running authoritative DNS yourself is rarely worth it. Managed providers run global anycast networks, absorb DDoS attacks, offer health checks and routing policies, and give an API for automation.
Managed DNS and internal DNS in more depth#
What a managed provider gives you. A global anycast network of authoritative servers, so lookups are answered close to every resolver. Capacity to absorb DDoS floods. Health checks and routing policies. An API, so records are managed as code. Route 53 even promises 100% availability in its service-level agreement, which shows how much the provider invests in redundancy. Pricing is typically a small monthly fee per zone plus a charge per million queries, which is one reason extremely short TTLs on very popular names have a visible cost.
Two providers for critical domains. The 2016 Dyn attack showed that even a well-run provider can fail. The fix is to serve the same zone from two independent providers and list both sets of name servers in the NS records at the registrar. Resolvers then try another server when one does not answer. The hard part is keeping both zones identical, especially with provider-specific features such as latency routing, which do not translate directly. Teams usually manage records in one source of truth (Terraform, or tools such as OctoDNS) and push them to both providers, and they use only features both support for the records that must survive a provider outage.
Private zones and split horizon. Cloud providers offer private DNS zones visible only inside your VPCs, such as Route 53 private hosted zones or Cloud DNS private zones. That lets db.internal.example.com resolve to a private IP inside the network and not exist at all outside it. A name that resolves to different answers inside and outside is split-horizon DNS. It is convenient but can confuse debugging, because the same name gives different answers depending on where you ask.
DNS inside Kubernetes. Every service gets a name such as payments.prod.svc.cluster.local, served by CoreDNS, which resolves to a stable virtual IP for the service. A common performance trap is the resolver setting ndots:5: a name with fewer than five dots, such as api.example.com, is first tried with each cluster search suffix appended. One external lookup can become several failed internal queries before the real one, which multiplies DNS load and adds latency. Using fully qualified names with a trailing dot, or lowering ndots, avoids it. Node-local DNS caches are another common fix when CoreDNS becomes a bottleneck.
Service discovery beyond DNS. DNS works for discovery when membership changes slowly. When instances come and go every minute, clients caching stale answers send traffic to dead instances. Registries such as Consul, etcd-based systems or a service mesh push membership changes to clients within seconds, and usually also offer a DNS interface for simple clients.
Custom domains for customers#
Many SaaS products let customers serve the product on their own domain: shop.customer.com for a store builder, status.customer.com for a status page. DNS is the heart of this feature:
- The customer creates a CNAME such as
shop.customer.com → customers.yourplatform.net. Using a CNAME, not your IP addresses, lets you change your infrastructure without asking thousands of customers to edit their DNS. - You verify that they own the domain, usually by asking them to publish a TXT record containing a random token, or by checking that the CNAME points at you.
- You obtain a TLS certificate for their name automatically through ACME. The HTTP-01 challenge works once the CNAME points at you. The DNS-01 challenge, a TXT record under
_acme-challenge, is needed for wildcard certificates. - Your edge picks the right tenant and certificate from the SNI and
Hostheader of each request.
The hidden risk is the dangling record. When a customer leaves, or a team deletes a cloud resource, a CNAME may still point at a hostname on a shared platform (a cloud storage bucket, an app-hosting subdomain) that someone else can now claim. An attacker who claims that name can serve content, and sometimes obtain certificates, on the victim's subdomain: a subdomain takeover. This has happened to many well-known companies. Defences are to delete DNS records before deleting the resources they point to, scan your zones regularly for records that point at unclaimed targets, and, as a platform, refuse to let a new tenant claim a hostname that an existing customer's verified domain still points to.
Anycast versus DNS steering in CDNs. CDNs use DNS in two different ways. Some, Akamai being the classic example, use DNS-based mapping: their authoritative DNS returns the IP of a nearby, lightly loaded edge server for each resolver, with short TTLs, so steering decisions can take server load into account. Others, Cloudflare being the classic example, use anycast: the same IP addresses are announced from every location, and BGP routing carries each user to a nearby site. DNS-based mapping gives finer control but depends on the resolver's location and TTLs. Anycast steers per packet and fails over as fast as routes change, but leaves the choice of site to internet routing. Many large providers combine both. See CDN.
DNS in the page-load budget. Every new hostname a page touches costs a lookup, and on mobile networks an uncached lookup can take 100 ms or more. Front-end teams reduce this by limiting the number of distinct hostnames, and by giving browsers early hints such as dns-prefetch and preconnect for third-party origins the page will need. Native apps can resolve and connect to their API host at start-up, before the user taps anything.
Designing your names#
How you lay out hostnames decides how much control DNS gives you later. A few conventions pay off:
- Separate hostnames by job.
wwwfor the web app,apifor the API,staticorcdnfor assets,wsfor WebSockets,authfor login. Each can then have its own TTL, its own routing policy, its own CDN or load balancer, and its own certificate, and you can move one without touching the others. Putting everything on one name ties all of them together for good. - Add regional names next to global ones. Alongside
api.example.com(latency-routed), publishapi-eu.example.comandapi-us.example.compointing at one region each. Health checks, debugging and region pinning for data residency all use them. - Keep internal names in internal zones. Use a private zone or a separate domain for internal services, so internal hostnames, IP plans and service names never leak into public DNS. Public DNS is effectively world-readable.
- Delegate subzones to the teams that own them. NS records for
dev.example.comoreu.example.comlet a team or a region manage its own records without access to the critical top-level zone. - Never point a name at a single server IP. Point it at a load balancer, a CDN or a stable virtual address, so replacing a server never needs a DNS change.
What to say if asked about failover. "Detection is three failed health checks, about 30 seconds. Cached answers expire within the 60-second TTL. So most users move within about 90 seconds. Clients holding open connections move when those connections fail, and they reconnect through DNS to the healthy region. Our RTO is five minutes, so DNS failover is enough here. If we needed under 30 seconds, we would put an anycast global load balancer in front instead."
When to Use It#
- Every public service needs DNS; use a managed provider.
- Use latency or geo routing for multi-region deployments.
- Use weighted records for gradual migrations and canaries.
- Use failover records with health checks for region-level disaster recovery.
When NOT to Use It#
- Do not rely on DNS alone to balance load between servers in a region.
- Do not expect DNS failover to be instant; if you need sub-minute failover, use anycast or a global load balancer.
How to Implement It#
- Host the zone on a managed provider, ideally with a second provider for critical domains.
- Point names at load balancers or CDNs (CNAME/ALIAS), not at individual servers.
- Set TTLs on purpose: short (30-60 s) for records you might fail over; long for stable ones.
- Lower TTLs before a planned change, wait for the old TTL to expire, make the change, then raise them again.
- Add health checks to failover and latency records.
; Example zone (simplified)
example.com. 300 IN ALIAS lb-eu.example-cloud.net.
www.example.com. 300 IN CNAME example.com.
api.example.com. 60 IN A 203.0.113.10 ; latency record, EU
api.example.com. 60 IN A 198.51.100.20 ; latency record, US
example.com. 3600 IN MX 10 mail.example.com.
example.com. 3600 IN TXT "v=spf1 include:_spf.example-mail.com ~all"| Technology | Fits when |
|---|---|
| Amazon Route 53 | AWS workloads; latency, geo, weighted and failover routing with health checks |
| Cloudflare DNS | Fast anycast DNS, often with Cloudflare's CDN and proxy |
| Google Cloud DNS, Azure DNS | Workloads on those clouds |
| NS1, Akamai Edge DNS | Advanced traffic steering, multi-provider setups |
| CoreDNS | Service discovery inside Kubernetes clusters |
Records as code#
Zones grow to hundreds of records, and a typo can take a product offline, so production teams manage DNS like code: reviewed, versioned and applied by automation. A latency-routed API name with health checks, written as Terraform for Route 53, shows the pieces:
resource "aws_route53_health_check" "api_eu" {
fqdn = "api-eu.example.com"
type = "HTTPS"
resource_path = "/healthz"
request_interval = 10 # seconds between checks
failure_threshold = 3 # about 30 s to declare unhealthy
}
resource "aws_route53_record" "api_eu" {
zone_id = var.zone_id
name = "api.example.com"
type = "A"
set_identifier = "eu-west-1"
latency_routing_policy { region = "eu-west-1" }
health_check_id = aws_route53_health_check.api_eu.id
alias {
name = var.eu_lb_dns_name
zone_id = var.eu_lb_zone_id
evaluate_target_health = true
}
}
# A matching record with set_identifier "us-east-1" covers US users.The health check path should test what users need (the service can reach its database) without being so deep that a minor dependency failure fails over a whole region. Keep a manual override, such as a flag that forces a region out of rotation, for the cases automation gets wrong.
Trade-offs#
| Choice | Pros | Cons | Pick when |
|---|---|---|---|
| Long TTL | Fewer queries, resilient if DNS provider hiccups | Slow changes and failover | Stable records |
| Short TTL | Fast changes and failover | More queries, slightly slower lookups | Failover and migration targets |
| DNS-based routing | Simple, global, cheap | Coarse, cached, no per-request control | Choosing a region |
| Anycast / global LB | Fast failover, per-request | More cost or complexity | Strict failover targets |
| One DNS provider | Simple, all features available | Provider outage takes every name down | Non-critical domains |
| Two DNS providers | Survives a provider outage | Keeping zones identical, common-denominator features | Critical public domains |
| ALIAS / CNAME flattening at the apex | Apex points at a CDN or load balancer | Less precise geo steering by the target | Apex names on CDNs and clouds |
| EDNS Client Subnet | Better geo accuracy for public resolver users | Less privacy, lower cache efficiency | Geo-sensitive content and CDNs |
| DNS-based service discovery | Works with any client | Stale answers when instances churn | Slowly changing internal services |
Common Pitfalls#
- Pointing DNS straight at server IPs, so replacing a server needs a DNS change.
- Making a change with a long TTL still cached, then wondering why traffic does not move.
- Forgetting that the DNS provider itself can be a single point of failure.
- Letting a domain or certificate-validation TXT record expire.
- Letting the domain itself expire, or leaving the registrar account protected only by a password.
- Assuming clients follow DNS changes, when connection pools and runtimes keep using old addresses.
- Setting TTLs so short that caches empty within seconds of a DNS provider problem.
- Long CNAME chains that add a lookup per hop.
- Missing SPF, DKIM and DMARC records, so transactional email lands in spam.
- Kubernetes
ndotsdefaults multiplying external lookups. - Health-check-driven DNS automation with no safeguard against removing every endpoint at once.
Real-World Examples#
In October 2016, a large DDoS attack on the managed DNS provider Dyn made many popular websites unreachable for parts of a day, a widely cited example of DNS as a single point of failure and a reason companies add a second DNS provider.
Amazon Route 53 offers weighted, latency-based, geolocation and failover routing policies, all used widely for multi-region designs.
Dan Kaminsky's 2008 disclosure of a practical DNS cache-poisoning technique led to one of the largest coordinated patch efforts in internet history, as resolver vendors shipped source port randomisation together.
Facebook's October 2021 outage made its own DNS unreachable after a backbone configuration error, and the company's engineering write-up is a standard reference for how routing and DNS failures cascade.
In October 2018 the DNS root's key-signing key was replaced for the first time since DNSSEC was deployed at the root in 2010. The rollover had been postponed a year after measurements showed many resolvers were not yet ready for the new key. It is a reminder of how carefully changes to shared internet infrastructure have to be staged.
Subdomain takeovers through dangling CNAME records, pointing at deleted cloud storage buckets or app-hosting names, have been reported against many large companies through bug-bounty programmes. That is why scanning zones for dangling records has become a routine security control.
In the Interview#
Using DNS in a design interview#
DNS appears in nearly every high-level design as the first arrow, and usually deserves one sentence. It earns more time in four situations:
- Multi-region designs. "Users resolve
api.example.comthrough latency-based DNS with health checks, so each gets the nearest healthy region. Failover takes about a minute because of the 60-second TTL, which meets our disaster-recovery target." - CDNs. "Static and cacheable content lives under
cdn.example.com, a CNAME to the CDN, whose DNS returns the nearest edge." - Removing single points of failure. "Two load balancers in different zones, both published in DNS, so losing one does not take the site down."
- Disaster recovery and migrations. Lower TTLs before planned changes, use weighted records for canaries, keep a second DNS provider for critical names.
A worked example: the edge of a read-heavy system. In a ticketing system like Ticketmaster, event pages are read far more often than they change, and traffic spikes when popular events go on sale. The edge chain is: DNS returns the nearest CDN edge for static assets, and the regional load balancer for the API. Behind the balancer, the event service is stateless, so it scales horizontally by adding instances, and the balancer spreads requests with round robin or least connections. Event details (name, date, venue, performer bios) are read-heavy and rarely change, so they sit in a Redis or Memcached read-through cache keyed by event ID. Venue data gets a long TTL, availability a short one. Changes in the database trigger invalidation of the affected cache entries. DNS's job in this design is small but essential: get each user to the right region and edge, and stay up when everything behind it is under load. The hard parts are keeping cache and database consistent, and safe deployment and rollback across many instances.
Numbers worth knowing. A cached lookup costs a few milliseconds and a cold one 50-200 ms. A 60-second TTL gives roughly 1-2 minutes of failover for most users, with a tail. Root and TLD referrals are almost always cached.
By level. A junior candidate knows DNS maps names to IPs and is cached. A senior candidate uses DNS deliberately for region selection and knows its failover time and limits. A staff candidate also covers what clients actually do with DNS answers (pools that ignore TTLs, resolvers far from users), the DNS provider as a dependency, and when anycast or a global load balancer is needed instead.
Follow-ups to be ready for.
- "Why not set the TTL to 1 second?" Many resolvers enforce a minimum anyway. Query volume and cost rise sharply. Lookups get slower on average. And caches no longer cover a short outage of the DNS provider.
- "A user in Asia uses a public resolver whose nearest site is in Europe. Where do they go?" Probably the wrong region, unless the resolver sends EDNS Client Subnet. Anycast front ends avoid the problem, because routing follows the user's own packets.
- "How do you move a domain between DNS providers without downtime?" Copy the zone, verify both answer identically, switch NS records at the registrar, and keep the old provider serving until the NS TTL (often 48 hours at the TLD) has fully passed.
Red flags. Claiming instant failover through DNS. Using DNS round robin as the only load balancer inside a region. Forgetting that DNS itself can be the outage.
Deep Dive: Negative caching, DNSSEC and service discoveryShow
Negative caching. Resolvers also cache "this name does not exist" answers (NXDOMAIN), for a time set in the zone's SOA record. Creating a record right after clients queried for it can still fail for a while.
DNSSEC signs records so resolvers can verify they came from the real zone owner and were not forged (cache poisoning). It adds operational complexity (key rotation, larger responses) and is unevenly deployed, but is important for high-value domains.
Encrypted DNS. DNS over HTTPS (DoH) and DNS over TLS (DoT) encrypt lookups so networks cannot read or alter them. Browsers increasingly use DoH, which can bypass company resolvers and their split-horizon setups.
Split-horizon DNS returns different answers inside and outside a network, such as private IPs to internal clients. Service discovery inside clusters often uses DNS too: Kubernetes gives each service a DNS name, but many systems prefer a registry (Consul, etcd) or a service mesh because DNS caching makes membership changes slow.
Thundering herds on resolvers. When a popular record's TTL expires, many clients query at once. Resolvers mitigate this with prefetching and "serve stale" (answering from an expired cache while refreshing), which also keeps sites reachable during short authoritative outages.
Deep Dive: How DNSSEC builds a chain of trustShow
DNSSEC does not encrypt anything. It signs records, so a validating resolver can prove an answer really came from the zone owner and was not changed or forged on the way.
- Each zone has a key pair. The public key is published in a DNSKEY record, and every set of records in the zone carries an RRSIG record: a signature made with the private key.
- To trust that DNSKEY, the resolver looks in the parent zone for a DS (delegation signer) record, which holds a hash of the child's key. The parent signs that DS record with its own key.
- The chain continues upward until it reaches the root zone's key, which validating resolvers have built in as a trust anchor.
So the chain for shop.example.com runs: root key → signs the DS for com → com key → signs the DS for example.com → example.com key → signs the A record for shop. Forging the A record now needs the zone's private key, not just a winning race.
Proving that a name does not exist is harder, because there is no record to sign. DNSSEC signs statements of the form "there are no names between alpha and delta" (NSEC records). That lets anyone list a whole zone by walking from one gap to the next, so NSEC3 uses hashed names to make walking harder. Online signers can also generate minimal denial answers on the fly.
The operational costs are why deployment is uneven. Responses become larger, which increases the risk of fragmentation and amplification. Keys must be rotated, and a mistake (an expired signature, or a DS record at the registrar that no longer matches the key) makes the whole domain fail validation, so validating resolvers return SERVFAIL to all their users. Even the root's key-signing key has been rotated only once so far, on 11 October 2018, after years of careful preparation. Many large sites accept that risk, while others rely instead on TLS to authenticate the server they eventually reach.
Deep Dive: DNS as an attack target and an attack toolShow
Flooding the authoritative servers. In October 2016 the Mirai botnet, made of hijacked cameras and home routers, flooded Dyn's managed DNS with traffic. Major sites whose servers were fine became unreachable for many users, because their names could not be resolved. The lessons were redundancy (a second provider), anycast capacity, and reasonable TTLs plus serve-stale, so that resolvers ride out short outages using cached answers.
Random-subdomain attacks. Queries for random, non-existent names (x7f3k.example.com) cannot be answered from cache, so every one reaches the authoritative servers, through every resolver the attacker can use. Providers defend with rate limits, by spotting abnormal NXDOMAIN rates, and with aggressive negative caching based on DNSSEC's denial records.
Reflection and amplification. DNS over UDP lets attackers forge the victim's address as the source, and a small query can trigger a much larger answer, historically by asking for "ANY" record type or for big DNSSEC responses. Open resolvers on the internet, which answer anyone, are the classic amplifiers. Defences include closing open resolvers, response rate limiting on authoritative servers, minimal responses to ANY queries (RFC 8482), and source address validation by networks so forged packets never leave them.
Hijacking at the registrar. An attacker who takes over the account at your registrar can change your NS records and redirect everything: web, API and mail. They can even obtain valid certificates by passing domain validation. Registry locks, hardware-key multi-factor authentication on registrar accounts, CAA records and monitoring of Certificate Transparency logs for unexpected certificates are the countermeasures. For a production domain these matter more than any routing feature.
DNS as a dependency of your own outage. Facebook's six-hour outage in October 2021 began as a backbone configuration error, but users experienced it as DNS failing, because Facebook's DNS servers withdrew their BGP routes as designed when they lost contact with the data centres. See Networking Fundamentals. Health-check logic that removes DNS servers needs a "last one standing" safeguard, so it cannot remove all of them at once.
Deep Dive: Inside a large recursive resolverShow
A public resolver such as 8.8.8.8 or 1.1.1.1 answers an enormous number of queries per second from one anycast address served at many sites. A few design choices make that possible, and they explain behaviour you will see from the outside:
- Caches are per site, sometimes per machine. Anycast sends each user to a nearby site, and each site has its own cache. Two users in different cities may get differently aged answers for the same name, and a record you just changed can appear updated in one city and stale in another. Large resolvers reduce this with shared cache tiers inside a site, but no global cache exists.
- Prefetching. When a popular entry is close to expiring and still being asked for, the resolver refreshes it in the background, so users almost never wait for a cold lookup on popular names.
- Coalescing. If thousands of clients ask for the same uncached name at the same moment, the resolver sends one upstream query and answers them all from it. This is the same request-coalescing idea used in caches and database gateways.
- Protecting authoritative servers. Resolvers limit how many queries they send to any one authoritative server and back off when it is slow. This protects small zones from being overwhelmed by a resolver's huge client base.
- Validation and privacy. Most large public resolvers validate DNSSEC, support encrypted transports, and minimise what they reveal upstream. With QNAME minimisation (RFC 7816, updated by RFC 9156), a resolver asks the root only about
com, and askscomonly aboutexample.com, instead of sending the full name to every server on the way.
The practical lessons for system designers are that the TTL you set is an upper bound on freshness, not a guarantee of it, that different users will see changes at slightly different times, and that DNS caching works in your favour during short outages of your own DNS provider.
Deep Dive: A regional failover, step by stepShow
Consider an API served from eu-west and us-east, behind latency-routed DNS with health checks every 10 seconds, a failure threshold of 3, and a 60-second TTL. At 12:00:00 the eu-west region loses its database and the health check, which tests database reachability, starts failing.
Reading the timeline:
- 0-30 s, detection. The region is down but DNS still points at it. Requests fail unless the client retries elsewhere.
- 30-90 s, cache drain. New lookups get
us-east, but resolvers that cached the old answer keep handing it out until it expires. On average a cached entry has half its TTL left, so most users switch within 30-60 seconds after detection. - The tail. Clients that pinned connections to
eu-westkeep failing until those connections error out and they reconnect. Badly behaved clients that cache for longer than the TTL fail for longer still. - The capacity question.
us-eastsuddenly receives Europe's traffic as well. If it was running at 60% utilisation and Europe is about as large as the US, it is now asked for 120%. Failover only works if each surviving region keeps spare capacity, or can scale up fast enough, and if its own dependencies (databases, caches, rate limits) can absorb the extra load. - Data. Users who fail over need their data in
us-east. That depends on the replication design, which DNS cannot fix. See Multi-region Data.
Failing back is a separate, deliberate decision. Flapping between regions as a health check recovers and fails again is worse than staying put, so most teams fail back manually or only after a long period of stable health.
Key Takeaways#
- DNS maps names to addresses through a hierarchy: root, TLD, then authoritative servers.
- Recursive resolvers do the iterative walk and cache answers for each record's TTL.
- Know A, AAAA, CNAME, MX, NS and TXT records, and use ALIAS at the apex.
- Managed DNS can route by weight, latency, geography and health, which is ideal for choosing a region.
- Caching makes DNS slow to change and coarse for load balancing; use load balancers within a region.
- Delegation runs through NS records (and glue) from root to TLD to your zone. Only 13 root names exist, but each is anycast from many sites.
- Stub resolvers send recursive queries. Recursive resolvers send iterative ones and cache for everyone behind them.
- "Propagation" is cache expiry. Lower TTLs before a change, wait out the old TTL, and expect a long tail of clients that ignore it.
- DNS is client-side load balancing: ideal for picking regions and removing load-balancer single points of failure, too coarse and slow for spreading load within a region.
- DNS failover is detection plus TTL plus a caching tail: about a minute or two at best. Use anycast or a global load balancer for faster failover.
- Protect the domain itself: auto-renew, lock the registrar account, publish CAA, SPF, DKIM and DMARC, and consider a second DNS provider.
- Lay out names by job and by region (
api,static,api-eu), keep internal names in private zones, and never point a name at a single server. - Authoritative load is resolvers x (86,400 ÷ TTL) per name, which is why even huge services see modest authoritative QPS and why very short TTLs cost money.
- Delete DNS records before the resources they point at, and scan for dangling CNAMEs to prevent subdomain takeover.
- Keep DNS out of your hot path during incidents: cache answers in clients, honour TTLs, serve stale answers when upstream is down, and test that your own control plane can still reach its dependencies when DNS is broken.