Skip to main content

DNS

Learning objectives
  • Trace a lookup from the application's stub resolver through recursive, root, TLD and authoritative servers, including every cache along the way
  • Choose the right record type (A, AAAA, CNAME, ALIAS, MX, TXT, SRV, NS, CAA) for a given need, and explain why CNAME cannot sit at the zone apex
  • Pick TTLs deliberately and calculate the real failover time of a DNS-based design
  • Design GeoDNS / weighted / health-checked routing for a multi-region bank or e-commerce platform, and state its limits
  • Explain DNSSEC, internal DNS and Kubernetes service discovery, and recognize the classic DNS outage patterns

TL;DR​

  • DNS maps names to records through a hierarchy: stub resolver (in your process/OS) → recursive resolver (ISP, 1.1.1.1, VPC resolver) → root → TLD (.com, .vn) → authoritative server for the zone. Answers are cached at every layer for the record's TTL.
  • Key records: A/AAAA (IPv4/IPv6), CNAME (alias to another name; not allowed at the apex), ALIAS/ANAME (provider-specific apex alias), MX (mail), TXT (SPF, DKIM, DMARC, verification), SRV (host + port for a service), NS (delegation), CAA (which CAs may issue certificates).
  • TTL is a trade-off between change agility and resilience/cost. Low TTLs (30–60 s) enable fast failover but increase query load and dependence on DNS availability; high TTLs (hours) survive DNS outages but make changes slow. Lower TTLs before a planned migration.
  • DNS load balancing (round robin, weighted, latency, GeoDNS, health-checked failover) is coarse: clients and resolvers cache, long-lived connections never re-resolve, and resolver location is not user location.
  • DNSSEC signs records to prevent spoofing; it does not encrypt (DoT/DoH do). Misconfigured DNSSEC makes a domain unresolvable for validating resolvers.
  • Inside clusters, DNS is service discovery (CoreDNS in Kubernetes). Watch ndots:5 query amplification and UDP conntrack races that cause 5-second lookups.
  • "It's always DNS" is a joke because it is so often true: registrar mistakes, expired domains, bad automation, overloaded resolvers and DDoS on providers have all caused major outages.

Why it matters​

Every request your customers make starts with DNS, and DNS is often the first thing to fail or the hidden reason a failover did not work:

  • A bank's DR runbook says "switch DNS to the secondary data center, RTO 15 minutes". But the TTL is 1 hour, some resolvers ignore low TTLs, and connection pools in partner systems keep using the old IP for days. Real RTO is much longer than the runbook claims.
  • An e-commerce platform uses GeoDNS to send users to the nearest region. During a flash sale, one region degrades, health checks flip, and traffic moves — but only as caches expire, so the degraded region keeps receiving traffic for minutes.
  • A Kubernetes service calling an external payment gateway sees occasional exactly-5-second latency spikes. The cause is not the gateway — it is DNS lookups being dropped and retried inside the cluster.
  • A phishing campaign uses a look-alike domain. Your defenses — DMARC, CAA, monitoring Certificate Transparency — are all DNS-adjacent.

Core concepts​

The resolution path​

ComponentRoleExamplesCaches?
Stub resolverLibrary in your process/OS; sends one recursive query and waitsglibc getaddrinfo, Go's resolver, /etc/resolv.confUsually not itself (Go's resolver does not cache); the OS may (systemd-resolved, nscd, mDNSResponder)
Recursive resolverDoes the iterative walk on behalf of clients, validates DNSSECISP resolvers, 1.1.1.1, 8.8.8.8, VPC resolver (AWS: VPC base + 2), CoreDNS forwardingYes — the main cache
Root serversKnow the NS records of every TLD13 named identities (a–m.root-servers.net), served by well over a thousand anycast instancesAnswers are cached by resolvers for days
TLD serversKnow the NS records of every domain under the TLD.com (Verisign), .vn (VNNIC)—
Authoritative serversHold the actual records for a zoneRoute 53, Cloudflare DNS, NS1, on-prem BIND/PowerDNS—

Notes that come up in interviews:

  • The stub asks a recursive question ("give me the final answer"); the recursive resolver asks iterative questions (follows referrals).
  • Browsers have their own DNS cache and may use DNS-over-HTTPS to a resolver of their choosing.
  • Glue records (IP addresses of name servers, served by the parent zone) break the chicken-and-egg problem when ns1.bank.example is the name server for bank.example.
  • DNS uses UDP port 53 for most queries and TCP 53 for large responses and zone transfers. EDNS(0) allows larger UDP responses; keeping them below ≈1,232 bytes avoids fragmentation problems.
  • Negative answers (NXDOMAIN) are cached too, for a duration derived from the zone's SOA record. Querying a name before creating it can leave resolvers caching "does not exist".

Record types​

TypePurposeExampleGotcha
A / AAAAName → IPv4 / IPv6api.bank.example. 60 IN A 203.0.113.10Clients may prefer IPv6; a broken AAAA path causes slow fallbacks (Happy Eyeballs helps)
CNAMEAlias to another namewww.shop.example. 300 IN CNAME shop.cdn-provider.net.Cannot coexist with other records at the same name, so not at the zone apex (which has SOA and NS); adds a lookup step
ALIAS / ANAME / CNAME flatteningApex alias resolved by the provider into A/AAAAshop.example → load balancer DNS nameProvider-specific (Route 53 Alias, Cloudflare flattening); not a standard record type
MXMail servers with prioritybank.example. MX 10 mx1.bank.example.Lower number = preferred
TXTFree text: SPF, DKIM, DMARC, domain verification_dmarc.bank.example. TXT "v=DMARC1; p=reject; rua=mailto:dmarc@bank.example"Banks should run DMARC p=reject to stop email spoofing
SRVHost and port for a service, with priority and weight_grpc._tcp.ledger.internal. SRV 10 50 50051 ledger-1.internal.Clients must explicitly support SRV; browsers do not
NSDelegates a zone to name serversbank.example. NS ns-123.awsdns-15.com.NS at the parent and child must agree
SOAZone metadata: serial, refresh, negative-cache TTL—Serial must increase for secondaries to pick up changes
PTRReverse lookup (IP → name)10.113.0.203.in-addr.arpa. PTR api.bank.example.Mail servers check it; useful in logs
CAAWhich CAs may issue certificatesbank.example. CAA 0 issue "digicert.com"Cheap protection against mis-issuance
HTTPS / SVCBService binding: ALPN (e.g. h3), alternate endpoints, ECH keysshop.example. HTTPS 1 . alpn="h3,h2"Lets clients use HTTP/3 on the first connection

TTL trade-offs​

TTLStrengthsWeaknessesTypical use
30–60 sFast failover and traffic shiftingMore queries (cost, latency on cache miss), stronger dependence on DNS provider availability, some resolvers clamp low TTLsRecords used in health-checked failover, GeoDNS, blue/green cutovers
5–15 minBalancedFailover takes minutesMost application endpoints
1–24 hSurvives DNS provider outages; few queriesChanges take hours to propagateNS records, MX, rarely changing apex records
Days (root/TLD NS)Very stable—Delegations

Rules of thumb:

  • Before a planned migration, lower the TTL at least one old-TTL period in advance (if the TTL is 24 h, lower it 24–48 h before), migrate, then raise it again.
  • Long TTLs act as a buffer against DNS outages: when a DNS provider was knocked offline by a DDoS in 2016 (Dyn), sites with longer TTLs stayed reachable longer for users whose resolvers still had cached answers.
  • Some resolvers and clients ignore or clamp TTLs. Some JVM versions and configurations historically cached lookups for a long time (check networkaddress.cache.ttl); some mobile OSes and corporate resolvers enforce minimums.

DNS-based load balancing and GeoDNS​

Authoritative DNS can return different answers per query:

PolicyHow it worksLimit
Round robinMultiple A records; resolvers/clients rotateUneven: caches pin users to one IP; no health awareness
WeightedReturn endpoint X for 90% of queries, Y for 10%Weight applies to resolver queries, not users or requests
Latency-basedReturn the region with lowest measured latency from the resolver's locationResolver location ≠ user location (unless EDNS Client Subnet is used)
Geolocation (GeoDNS)Answer based on the country/continent of the resolver or client subnetVPNs and public resolvers distort location; not a compliance control
Health-checked failoverProvider probes endpoints and stops returning unhealthy onesFailover only as fast as TTL + detection + client caching

EDNS Client Subnet (ECS) lets the recursive resolver pass a truncated client subnet to the authoritative server so it can geolocate the user rather than the resolver. Support varies by resolver; some privacy-focused resolvers do not send it.

Anycast is the alternative: the same IP is announced from many locations via BGP, and the network routes each client to the nearest one. CDNs and DNS providers themselves use anycast. It reacts to failures at routing speed, not TTL speed, but requires owning IP space and BGP operations — which is why most companies get anycast by using a CDN or global load balancer rather than running it.

Failover: computing the real RTO​

For a DNS-based active/passive failover:

Worst-case switch time ≈ health-check detection + DNS propagation + TTL + client-side caching + connection lifetime

Example: health checks every 10 s, 3 failures to mark unhealthy (≈30 s), provider propagation (seconds to a minute), TTL 60 s, then clients:

  • Browsers re-resolve on new connections, but keep existing HTTP/2 connections open to the old IP.
  • Go's http.Transport resolves only when dialing a new connection; pooled connections keep talking to the old IP until they break or idle out.
  • A partner's Java service with long-lived connection pools may not move for hours.

So the design must also break connections: make the failed region refuse connections (rather than hang), set max connection lifetimes in clients, send HTTP/2 GOAWAY, and test the whole path in DR drills. See High Availability & Disaster Recovery.

DNSSEC​

Classic DNS is unauthenticated: a resolver accepts the first plausible-looking answer. Cache poisoning attacks (famously the 2008 Kaminsky attack) inject forged answers; source-port randomization made them much harder, and DNSSEC makes them detectable.

  • Each zone signs its record sets (RRSIG) with keys published as DNSKEY. The parent zone publishes a hash of the child's key (DS), forming a chain of trust from the signed root zone down.
  • A validating resolver checks signatures and returns SERVFAIL if validation fails. Authenticated answers carry the AD flag.
  • NSEC/NSEC3 records prove that a name does not exist.
  • DNSSEC gives integrity and authenticity, not confidentiality. Encryption between client and resolver is DNS over TLS (port 853) or DNS over HTTPS.

Operational risk: key rollovers and DS updates at the registrar are error-prone, and a mistake makes the whole domain unresolvable for every validating resolver — a self-inflicted total outage (Slack's 2021 DNSSEC rollout incident is a well-known example). Banks enabling DNSSEC should use a provider with automated signing and rollover, monitor validation from outside, and rehearse rollback.

Internal DNS and service discovery​

  • Private hosted zones / split-horizon DNS: api.bank.example resolves to a private IP inside the VPC and to the public load balancer outside. Useful, but debugging is confusing when "it resolves differently on my laptop".
  • Hybrid resolution: cloud resolvers forward corp.bank.local to on-prem DNS and on-prem forwards cloud zones back (e.g. Route 53 Resolver inbound/outbound endpoints). Core banking on-prem and microservices in the cloud depend on this path being highly available.
  • Kubernetes: CoreDNS serves service.namespace.svc.cluster.local.
    • A normal (ClusterIP) Service name resolves to one stable virtual IP; kube-proxy or the CNI balances per connection behind it.
    • A headless Service (clusterIP: None) returns the pod IPs directly — used for StatefulSets (Kafka, databases) and for gRPC client-side load balancing.
    • SRV records exist for named ports.
  • Consul, Eureka, etcd-based registries offer DNS or API-based discovery with health checks. DNS interfaces are convenient; API watches react faster.

The ndots:5 trap in Kubernetes. Pods get /etc/resolv.conf with search domains and options ndots:5. A name with fewer than 5 dots, like api.partner-bank.com, is first tried with every search suffix:

api.partner-bank.com.payments.svc.cluster.local A + AAAA → NXDOMAIN
api.partner-bank.com.svc.cluster.local A + AAAA → NXDOMAIN
api.partner-bank.com.cluster.local A + AAAA → NXDOMAIN
api.partner-bank.com. A + AAAA → answer

That is up to 8 queries for one lookup. Fixes: use FQDNs with a trailing dot (api.partner-bank.com.), lower ndots via the pod's dnsConfig, and run NodeLocal DNSCache.

The 5-second lookup. Parallel A and AAAA queries over UDP from the same socket can race in Linux conntrack under DNAT; one packet is dropped and the resolver retries after its default 5-second timeout. Symptoms: latency spikes of exactly ≈5 s. Mitigations: NodeLocal DNSCache, the glibc single-request-reopen option (not supported by musl/Alpine), and newer kernels.

DNS as an outage cause​

PatternExamplePrevention
DNS provider DDoS or outageDyn, October 2016 (Mirai botnet) made many major sites unreachableSecondary DNS provider, sensible TTLs
Authoritative servers become unreachableFacebook, October 2021: a backbone change withdrew BGP routes, and Facebook's DNS servers became unreachable, taking down all its appsOut-of-band access, DNS hosted independently of the main network
Bad automation writes wrong or empty recordsAWS us-east-1, October 2025: AWS attributed the incident to a race condition in automated DNS management that left a DynamoDB regional endpoint with an empty recordGuardrails on record changes, staged rollouts, validation that never publishes empty answers
Expired domain or registrar account compromiseDomains lapsing, hijacked registrar logins redirecting NSAuto-renew, registry lock, MFA and change alerts at the registrar
Dangling CNAME / subdomain takeoverpromo.shop.example CNAME to a deleted cloud bucket that an attacker re-registersInventory and scan DNS for records pointing to deprovisioned resources
Resolver overloadCoreDNS under-provisioned during a scale-out; every service fails lookupsScale and cache DNS, alert on SERVFAIL and latency
DNSSEC misconfigurationBroken key rollover → SERVFAIL everywhereAutomated signing, external validation monitoring

Trade-offs​

OptionStrengthsWeaknessesChoose when
Low TTL (≤60 s)Fast traffic shifting and failoverQuery volume, more exposure to DNS outages, clamped by some resolversActive/active or failover records, migrations
High TTL (hours)Resilient, cheapSlow changesStable records: MX, NS, rarely changing apex
DNS load balancing (weighted/geo/latency)Global, cheap, no extra hopCoarse, cache-bound, resolver ≠ userMulti-region routing at region granularity
Anycast (via CDN / global LB)Routing-speed failover, single IPNeeds provider or BGP expertise; harder to steer preciselyGlobal edge, DDoS absorption
L7 global load balancerPer-request decisions, health-awareAnother critical dependency, costFine-grained regional failover
Single DNS providerSimpleProvider outage = your outageSmall systems
Two DNS providersSurvives provider outageKeeping records in sync; advanced features (geo, alias) differBanks, large e-commerce
DNSSECPrevents spoofing and poisoningOperational risk, larger responsesHigh-value domains with an automated provider
DNS-based service discoveryUniversal, simple clientsCaching delays, no rich health metadataKubernetes Services, simple setups
API-based discovery (xDS, Consul watches)Fast updates, metadata, weightsClient libraries or proxies requiredService mesh, gRPC client-side LB

In practice​

Typical public setup for a bank or large shop:

  • Apex bank.example → ALIAS to the CDN or global load balancer; www → CNAME to the CDN.
  • api.bank.example → health-checked records per region with TTL 60 s.
  • NS records with long TTLs; a secondary DNS provider for the main brand domains.
  • CAA records restricting issuance to your chosen CAs; DMARC p=reject, SPF and DKIM for every sending domain.
  • Registry lock on brand domains; auto-renew; registrar MFA and alerts on NS changes.
  • Monitoring: external probes resolving key names from several networks; alerts on SERVFAIL, NXDOMAIN spikes and answer changes.

Go: explicit resolver timeouts and SRV lookups. Go's resolver does not cache, and every new connection triggers a lookup — so DNS latency shows up as connect latency. Bound it.

package main

import (
"context"
"fmt"
"log"
"net"
"time"
)

func main() {
resolver := &net.Resolver{
PreferGo: true,
Dial: func(ctx context.Context, network, address string) (net.Conn, error) {
// Fail fast on a dead resolver instead of waiting the default 5 s.
d := net.Dialer{Timeout: 500 * time.Millisecond}
return d.DialContext(ctx, network, address)
},
}

ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()

start := time.Now()
addrs, err := resolver.LookupNetIP(ctx, "ip", "www.example.com")
if err != nil {
log.Fatalf("lookup failed after %s: %v", time.Since(start), err)
}
fmt.Printf("resolved in %s: %v\n", time.Since(start), addrs)

// SRV gives host and port, e.g. for a headless Kubernetes Service with a named port.
_, srvs, err := resolver.LookupSRV(ctx, "grpc", "tcp", "ledger.payments.svc.cluster.local")
if err != nil {
log.Printf("srv lookup: %v", err) // expected outside a cluster
return
}
for _, s := range srvs {
fmt.Printf("%s:%d priority=%d weight=%d\n", s.Target, s.Port, s.Priority, s.Weight)
}
}

// newDialer makes outbound connections (e.g. http.Transport.DialContext)
// use the same bounded resolver.
func newDialer(r *net.Resolver) *net.Dialer {
return &net.Dialer{Timeout: 2 * time.Second, Resolver: r}
}

Kubernetes pod DNS tuning (only where you call many external names):

apiVersion: v1
kind: Pod
metadata:
name: payment-gateway-client
spec:
dnsConfig:
options:
- name: ndots
value: "2"
containers:
- name: app
image: example.com/payments/gateway-client:1.4.2

Common pitfalls​

  • Assuming TTL = failover time. Symptom: DR test shows traffic still hitting the failed site long after the DNS switch, from clients with pooled connections or TTL-clamping resolvers.
  • CNAME at the apex. Symptom: provider rejects it, or mail breaks because MX records disappear. Use ALIAS/flattening.
  • Forgetting negative caching. Symptom: a new hostname "doesn't exist" for some users for minutes after you create it, because someone queried it earlier.
  • Changing records without lowering TTL first. Symptom: migration cutover takes a day instead of minutes.
  • Kubernetes ndots:5 with chatty external calls. Symptom: CoreDNS CPU high, external call latency includes several NXDOMAIN round trips.
  • Exactly-5-second latency spikes. Symptom: p99 of outbound calls shows a spike at ≈5 s; cause is dropped UDP DNS queries and resolver retry timeout.
  • Single DNS provider, no registry lock. Symptom: provider outage or registrar account takeover takes down the whole brand.
  • Dangling DNS records. Symptom: a security researcher reports that old-campaign.shop.example serves their content.
  • Using DNS for fine-grained load balancing. Symptom: one backend overloaded because a big corporate resolver cached its IP for thousands of users.

Interview angle​

  • "What happens when you resolve a domain name?" Walk the chain (stub → recursive → root → TLD → authoritative), mention caching and TTLs at each step, and note the browser and OS caches.
  • "Design multi-region failover for internet banking." Health-checked DNS or a global load balancer, TTL choice, how long failover really takes (detection + TTL + client behaviour), forcing connection re-establishment, data replication constraints (RPO), and regular DR drills.
  • "Why not just use DNS round robin for load balancing?" Caching, uneven distribution, no health checks, resolver ≠ user location; use it for region selection, not per-request balancing.
  • Follow-ups: CNAME vs ALIAS, what DNSSEC does and does not do, internal service discovery in Kubernetes, how to protect a bank's domains (registry lock, CAA, DMARC, CT monitoring).
  • Red flags: believing DNS changes are instant, using GeoDNS as a data-residency control, not knowing that Go/HTTP clients keep using old IPs on pooled connections.

Self-check​

1. What is the difference between a stub resolver and a recursive resolver?

The stub resolver lives in the client (libc, Go's resolver) and sends one query asking for the final answer, usually without caching. The recursive resolver (ISP, 1.1.1.1, VPC resolver) does the work: it follows referrals from root to TLD to authoritative servers, caches answers for their TTL, and may validate DNSSEC.

2. Why can't you put a CNAME at shop.example (the zone apex), and what do you use instead?

A CNAME cannot coexist with any other record at the same name, and the apex must have SOA and NS records (and often MX/TXT). Instead use a provider-specific ALIAS/ANAME or CNAME flattening, which the authoritative server resolves into A/AAAA records at query time, or point the apex to static anycast IPs.

3. Your DR plan uses health-checked DNS failover with a 60-second TTL. Why might it take 20 minutes for a partner's traffic to move?

Detection takes time (several failed health checks), then the TTL must expire in their resolver — which might clamp TTLs to a minimum — and then their application must open new connections. A partner with long-lived pooled connections (or a JVM caching DNS) keeps sending traffic to the old IP until those connections break. Making the failed side refuse connections and setting max connection lifetimes shortens this.

4. What does DNSSEC protect against, and what does it not do?

It protects integrity and authenticity: validating resolvers can detect forged or modified records (cache poisoning, on-path spoofing). It does not encrypt queries or hide which names you look up (use DoT/DoH for that), does not protect the last hop to a non-validating stub unless that path is secured, and does not help if your registrar account is hijacked and the attacker re-signs the zone.

5. A Go service in Kubernetes calls api.partner-bank.com and you see CoreDNS handling 8 queries per lookup. Explain and fix.

With ndots:5, the name has fewer than five dots, so the resolver tries each search domain first (.payments.svc.cluster.local, .svc.cluster.local, .cluster.local), each for A and AAAA, before the absolute name. Fix by using a trailing-dot FQDN, lowering ndots in the pod dnsConfig, and adding NodeLocal DNSCache.

6. When would you lower TTLs ahead of a data-center migration, and by how much?

At least one full old-TTL period before the cutover, so every cache has picked up the new short TTL by migration time — e.g. lower from 86,400 s to 60 s two days before. After the migration is stable, raise TTLs again to reduce load and improve resilience.

7. List four DNS-related controls a bank should have for its brand domains.

Registry lock and registrar MFA with change alerts; CAA records limiting which CAs may issue certificates; DMARC p=reject with SPF and DKIM to stop email spoofing; Certificate Transparency and look-alike domain monitoring; a secondary DNS provider; and scanning for dangling records that enable subdomain takeover.

🧠 Flashcards0/10 learned · 0 retries

Exercise​

Part A — walk the hierarchy yourself.

dig +trace www.example.com # every referral from root to authoritative
dig www.example.com A +noall +answer # run twice; watch the TTL count down (cached)
dig @1.1.1.1 www.example.com AAAA +noall +answer
dig example.com NS +short
dig example.com CAA +short
dig _dmarc.google.com TXT +short
dig example.com SOA +noall +answer # last field relates to negative caching
dig cloudflare.com HTTPS +noall +answer # ALPN hints for HTTP/3 (needs a recent dig)
dig +dnssec cloudflare.com A | grep -E 'RRSIG|flags'

Part B — measure lookup cost from Go. Run the Go program above against a name you control, then against a non-existent name, and compare timings for first and second lookups. Explain why the second lookup is faster even though Go does not cache (hint: the recursive resolver does).

Part C — Kubernetes (if you have a cluster, e.g. kind or minikube).

kubectl run dnsutils --image=registry.k8s.io/e2e-test-images/jessie-dnsutils:1.3 --restart=Never -- sleep 3600
kubectl exec dnsutils -- cat /etc/resolv.conf
kubectl exec dnsutils -- nslookup kubernetes.default

To see the search-domain expansion, temporarily add the log plugin to the CoreDNS ConfigMap (kubectl -n kube-system edit configmap coredns), then run kubectl exec dnsutils -- nslookup www.example.com while tailing kubectl -n kube-system logs -l k8s-app=kube-dns -f. Remove the log plugin afterwards.

Part D — design. Write a one-page DNS design for bank.example: records for apex, www, api, mail; TTLs with justification; failover policy between two regions with a calculated worst-case switch time; and the domain-protection controls.

Done when: you can explain every line of dig +trace, you have shown the search-domain expansion in a pod, and your design states a realistic failover time with each component of the sum.

Further reading​

Finished this page?

Do the self-check first. Marking it complete schedules spaced reviews (1, 3, 7, 14, 30… days).