Skip to content

IP, DNS, GeoDNS, TTL & DNS as a Routing Weapon ​

"If a change can be anticipated, the TTL can be reduced prior to the change to minimize inconsistency during the change, and then increased back to its former value following the change." — P. Mockapetris, RFC 1034 Domain Names: Concepts and Facilities, section 3.6 (November 1987)

Summary: Your authoritative DNS is the first load balancer every user meets: before a single packet reaches your edge, a name server you control has already decided which address, which region and which provider that user will talk to, and every cache on the way will remember that decision for as long as the TTL says. Focus: Record types that matter for architecture (A/AAAA, CNAME, ALIAS/ANAME at the apex, NS, SOA, glue, TXT, SRV, CAA, HTTPS/SVCB), TTL as a control knob (failover time vs query load, negative caching, resolver clamping, serve-stale, client caches), DNS-based load balancing (round-robin, multivalue, weighted, latency, geolocation/GeoDNS with EDNS Client Subnet, failover with health checks in Amazon Route 53, Cloudflare Load Balancing, Google Cloud DNS and NS1), anycast and BGP, DNS failover vs load-balancer failover vs GSLB, split-horizon, service discovery (SRV, Kubernetes CoreDNS), blue/green and canary via DNS, DNSSEC, DoH/DoT, DNS as attack surface (amplification, cache poisoning, subdomain takeover), and IP addressing decisions (public/private, elastic IPs, NAT gateways, egress allowlists, IPv6). Learning goal: For any public or internal name, choose its record type, TTL and routing policy, compute how long a failover really takes, wire health checks to an endpoint that tells the truth, know which caches ignore you, and close the DNS-shaped security holes (open resolvers, dangling CNAMEs, unsigned zones) before someone else finds them.

This chapter sits in the Networking & Protocols group, after The Client-Server Model and before Forward vs Reverse Proxies. It looks at DNS from the authoritative side, as a design tool. How a host resolves a name (stub resolver, /etc/resolv.conf, nsswitch.conf, ndots, DNS inside containers) belongs to DNS Resolution for Developers; address math, CIDR and private ranges to IP Addressing; NAT mechanics to NAT, PAT & Port Forwarding; the pod network and CoreDNS deployment to Kubernetes Networking. Load-balancer algorithms and L4/L7 health checks are in Load Balancing, edge caching in CDNs, DDoS defence in DDoS & Network Security, and registry-based discovery in Service Discovery. This page tells you how DNS decides where traffic goes, how fast that decision can change, and where it breaks.

Page map ​

If you are looking forGo to
The whole page in three tablesEverything in one minute
Why DNS is a routing layer at allWhy it exists
RFC 1034 to RFC 9460 in one timelineWhere it comes from
Public vs private IPs, elastic IPs, NAT gateways, egress allowlists, IPv6IP addressing at design level
Delegation, NS, SOA, glue, root and TLD serversAuthoritative DNS and delegation
Which record type for which jobRecord types, The apex problem
TTL, negative caching, resolver behaviourTTL, Negative caching, Caches you do not control
Round-robin, weighted, latency, geo, failoverRound-robin, Weighted, Latency, GeoDNS and ECS, Failover and health checks
DNS failover vs LB failover vs GSLBGSLB
Anycast, BGP, unicastAnycast
Internal vs external answersSplit-horizon
SRV, Kubernetes DNS, CoreDNSService discovery
Blue/green and canary by DNSBlue/green and canary
DNSSEC, DoH, DoTDNSSEC, DoH and DoT
Amplification, cache poisoning, subdomain takeoverDNS as attack surface
Flags, RCODEs, knobs, failover arithmetic, error messagesMechanics
CodeGo, Laravel
Classic incidents and their fixesSolving the classic problems
Which policy, which TTL, which productChoosing
Monolith to multi-regionIn architecture
A GeoDNS server you can query with digLab
Wrong beliefs, summary, quiz, termsMisconceptions, Cheat sheet, Self-check, Glossary

Everything in one minute ​

The records an architect actually decides about.

RecordIn plain wordsTiny exampleDesign decision it carries
A / AAAAName to IPv4 / IPv6 addressapi.example.com. 60 IN A 192.0.2.10Which endpoint, how long caches keep it
CNAMEThis name is an alias of that namewww 300 IN CNAME d111111abcdef8.cloudfront.net.Delegating an endpoint to a provider; not allowed at the apex
ALIAS / ANAME / CNAME flatteningProvider-side alias that answers with A/AAAA, so it works at the apexRoute 53 alias example.com -> my-alb-123.eu-west-1.elb.amazonaws.comApex pointing at a load balancer or CDN
NSWhich servers are authoritative for a zoneexample.com. 172800 IN NS ns-2048.awsdns-64.net.Which DNS provider(s), delegation
SOAZone metadata: serial, timers, negative TTL... 1 7200 900 1209600 86400How long "does not exist" is cached
TXTFree textSPF, DKIM, _acme-challenge, domain verificationOwnership proofs; keep an inventory
SRVService at host:port with priority and weight_sip._tcp 300 IN SRV 10 60 5060 sip1.example.com.Port-aware discovery (Kubernetes, SIP, XMPP, LDAP)
CAAWhich certificate authorities may issueexample.com. CAA 0 issue "letsencrypt.org"Limits certificate mis-issuance
HTTPS / SVCBConnection hints: ALPN (h2, h3), ports, IP hints, ECH; apex aliasingexample.com. 300 IN HTTPS 1 . alpn="h3,h2"HTTP/3 discovery, apex alias without CNAME

The routing policies, across products.

PolicyDecides byAmazon Route 53CloudflareGoogle Cloud DNSWhat it cannot do
Simple / round-robinNothing; returns all recordsSimple, Multivalue answer (up to 8 healthy)Multiple records, DNS-onlyStandard record setKnow load or health (unless multivalue)
WeightedYour percentagesWeighted (0-255)Load Balancing: pool/endpoint weights, Random steeringWeighted round robinGuarantee per-user stickiness
LatencyMeasured network latency to provider regionsLatency (per AWS Region)Dynamic steering (RTT from health monitors)(geolocation as proxy)See your servers' load
Geolocation / GeoDNSCountry/continent of the resolver or ECS subnetGeolocation, Geoproximity (bias), IP-based (CIDR)Geo steering, Proximity steeringGeolocationKnow where a user behind a far-away resolver really is
FailoverHealth check resultFailover (primary/secondary)Pool fallback, monitorsFailover (with health checks)Move existing connections

Time and blast radius: the three numbers to know.

KnobTypical valueLower meansHigher means
Record TTL for steered names30-300 sFaster failover and canary shifts; more queries, more cost, more exposure to a DNS outageFewer queries; slow to change; resolvers ride out a provider outage longer
Negative TTL (min of SOA TTL and SOA MINIMUM)Route 53 default SOA: TTL 900, MINIMUM 86400, so 900 sNew names appear sooner after an NXDOMAIN was cachedA typo'd lookup or early probe pins NXDOMAIN for hours
Health check interval x failure thresholdRoute 53: 30 s or 10 s x 3Faster detection; more flapping riskSlower failover
Failover time (rough)detection + TTL + client cachesUse anycast or an L7 global LB when you need secondsDNS failover is a minutes-scale tool
Browser / appown host cacheGo: none in net pkglibcurl: 60 s defaultOS stub resolver/etc/resolv.confsystemd-resolved,mDNSResponder cacheRecursive resolverISP, 8.8.8.8, 1.1.1.1,VPC resolver, CoreDNScache: TTL, clamped,negative + stale (RFC 8767)Root servers (13 named, a-m)referral: "ask .com NS"anycast, hundreds of instancesTLD servers (.com)referral: NS + glue forexample.com (delegation)Authoritative: example.comRoute 53, Cloudflare, NS1answer + TTL, routing policy,health checks, GeoDNS, ECSThe part you control1 query2 RD=13 miss45 answerEvery cache keeps the answer for up to its TTL. Changing a record changes only the box on the bottom right; the rest catch up when their copy expires.Detail of steps 1-2 (stub, resolv.conf, ndots): /foundations/dns-resolution-for-developers.

The picture is the path of one lookup, seen from the side you own. Steps 1 and 2 happen on the user's machine and are taught in DNS Resolution for Developers. Steps 3 to 5 are what a recursive resolver does on a cache miss. Only the bottom-right box, your authoritative zone, is under your control; every box to its left keeps a copy for up to the TTL you published.

Why it exists ​

A name has to become an address before any connection starts. Whoever answers that question decides where the user goes, and the answer can differ per user, per moment and per health state. That makes the authoritative DNS server a routing layer: global, cheap, available before your load balancer, and controlled by a single API call. It is also the slowest-reacting and least observable routing layer you have, because once an answer leaves your server you cannot recall it.

Steering with DNSSteering with a load balancer or anycast proxy
Works before any packet reaches you; spans providers, clouds and regionsWorks after the packet arrives at your edge
Decision per resolver (or per ECS subnet), not per user or per requestDecision per connection or per HTTP request
Change takes effect only when caches expire (TTL plus clients that ignore it)Change takes effect in seconds for new requests
Cannot see open connections; cannot drain themCan drain, retry, and fail over mid-request
No extra hop, no extra bill per request (Route 53 alias queries to AWS resources are free)One more hop, one more service to run or pay for
Fails static: a down DNS provider means cached answers keep working until they expireFails closed: a down LB stops all traffic behind it
Health checks from the outside, every 10-30 sHealth checks from the inside, every 1-10 s

The analogy we reuse on this page: the printed phone directory. Your authoritative zone is the publisher of the directory; every resolver, OS and browser keeps a printed copy. The TTL is the "valid until" date on the cover: a copy is not thrown away before that date, whatever you publish meanwhile. GeoDNS prints regional editions (the Paris edition lists the Paris branch). Failover routing is a publisher who prints a new edition when a branch burns down, which helps only readers whose copy has expired. Anycast is one national phone number that the phone network connects to the nearest branch: nobody needs a new directory when a branch closes. Negative caching is a reader who learned "no such company" and will not look again until the date on that page. And a dangling CNAME is a directory entry still pointing at a shop you closed, which a stranger has since rented.

Three common misunderstandings, up front ​

  1. "Set TTL to 60 and failover takes 60 seconds." Failover time is detection (Route 53: interval x failure threshold, 30-90 s) plus the TTL plus whatever the client keeps: connection pools, keep-alive connections, JVMs or Go processes that resolved once, libcurl's 60-second cache. DNS changes only new lookups.
  2. "GeoDNS knows where the user is." It knows where the recursive resolver is, unless the resolver sends EDNS Client Subnet (ECS). A user in Jakarta on a corporate resolver in Frankfurt gets the Frankfurt answer. Cloudflare's 1.1.1.1 does not send ECS; Google Public DNS sends it to name servers that support it.
  3. "DNSSEC encrypts DNS" / "DoH secures my zone." DNSSEC signs answers and provides no confidentiality (RFC 4033: "These extensions do not provide confidentiality"). DoH and DoT encrypt the hop between client and resolver and prove nothing about whether the zone data is authentic. They solve different problems; you may want both.

Where it comes from ​

RFC 1034 and RFC 1035, November 1987. Paul Mockapetris's two documents still define the system: the name space, zones and delegation, resource records with a TTL, the message format, the master file format, and the rule that a CNAME owner holds no other data ("If a CNAME RR is present at a node, no other data should be present"). The apex problem of the 2010s is a direct consequence of that sentence, because the apex must hold SOA and NS records.

RFC 2181, July 1997 clarified RRsets (all records of one name and type share one TTL) and TTL semantics. RFC 2308, March 1998 made negative caching mandatory ("negative caching should no longer be seen as an optional part of a DNS resolver") and defined the negative TTL as the minimum of the SOA's TTL and its MINIMUM field.

RFC 2782, February 2000 defined SRV records (_Service._Proto.Name TTL Class SRV Priority Weight Port Target), the first DNS-native form of service discovery with load sharing.

RFC 4033, March 2005 introduced DNSSEC as deployed today: "data origin authentication and data integrity", explicitly not confidentiality. RFC 4786, December 2006 (BCP 126) documented operating services with anycast: "the practice of making a Service Address available to a routing system at Anycast Nodes in two or more discrete locations".

July 2008, the Kaminsky attack. CERT VU#800113, "Multiple DNS implementations vulnerable to cache poisoning", showed that a 16-bit transaction ID was not enough entropy; source-port randomization was deployed across resolvers in weeks. RFC 5358, October 2008 told operators to close open recursive resolvers used in reflector attacks.

2013-2016. RFC 6891 (EDNS(0), April 2013) became the extension mechanism. RFC 7858 (DNS over TLS, May 2016) and RFC 7871 (EDNS Client Subnet, May 2016) appeared the same month: one to hide queries, one to reveal part of the client address so CDNs and GeoDNS can answer for the user rather than the resolver. RFC 8484 (DNS over HTTPS, October 2018) mapped "each DNS query-response pair" into an HTTP exchange.

2019-2024. RFC 8659 (CAA, November 2019) replaced RFC 6844. RFC 8767 (serve-stale, March 2020) let resolvers answer with expired data when authorities are unreachable. RFC 9460 (SVCB and HTTPS records, November 2023) finally standardised apex aliasing: the records "also enable aliasing of apex domains, which is not possible with CNAME". RFC 9499 (March 2024) is the current DNS terminology reference.

text
     Year   Document / event                     What changed for system design
1    1987   RFC 1034/1035                         Zones, delegation, TTL, CNAME rule
2    1997   RFC 2181                              One TTL per RRset; TTL semantics fixed
3    1998   RFC 2308                              Negative caching mandatory; SOA MINIMUM = negative TTL
4    2000   RFC 2782                              SRV: host, port, priority, weight
5    2005   RFC 4033-4035                         DNSSEC: integrity, not confidentiality
6    2006   RFC 4786                              Anycast as an operating practice
7    2008   Kaminsky (CERT VU#800113), RFC 5358   Port randomization; close open resolvers
8    2016   RFC 7858 DoT, RFC 7871 ECS            Encrypted stub-to-resolver; GeoDNS per subnet
9    2018   RFC 8484 DoH                          DNS inside HTTPS on port 443
10   2020   RFC 8767 serve-stale                  Expired answers survive an authority outage
11   2023   RFC 9460 SVCB/HTTPS                   ALPN hints, ECH, apex aliasing in the standard

The concept catalogue ​

Each block follows the same order: plain words, the usual wrong belief, a definition, a request flow, real scenarios, how products provide it, and the fix.

IP addressing at design level: public, private, elastic, NAT, egress, IPv6 Must-know ​

In plain words: some of your addresses are reachable from the internet (public), most are not (private, RFC 1918 or IPv6 ULA); a few public ones must stay fixed for years because a partner wrote them into a firewall, and those are the ones you design around.

Common misunderstanding: "Our service has an IP address." A modern service has many and they change: load balancers like AWS ALB change addresses (which is why you point DNS at them by name), autoscaled instances get new private addresses, and outbound traffic leaves through a NAT gateway with an address that has nothing to do with the inbound one. The only stable addresses are the ones you explicitly reserve: an elastic IP, a static anycast IP, a provider-assigned prefix, or your own BGP-announced range.

Definition: Public addresses are globally routed; private addresses (10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16 per RFC 1918; fc00::/7 for IPv6 ULA) are routed only inside your networks. An elastic IP (AWS) is "a static IPv4 address designed for dynamic cloud computing" that stays allocated to your account until you release it and can be remapped between instances. A NAT gateway lets private-subnet instances open outbound connections; a public NAT gateway in AWS must have an elastic IP associated at creation, and the internet sees that elastic IP as the source of every outbound packet. The egress IP is therefore a design artefact: whatever address a third party will see and allowlist. IPv6 gives every host a globally unique address and removes NAT from the picture, at the cost of running dual-stack (A and AAAA) for years.

text
     Inbound (users -> you)                         Outbound (you -> partner bank API)
1    User resolves api.example.com -> 192.0.2.10    Pod 10.20.3.17 opens TCP to 198.51.100.80:443
2    192.0.2.10 is an ALB/NLB or anycast edge IP    Route table sends 0.0.0.0/0 to the NAT gateway
3    LB forwards to private targets 10.20.x.x       NAT gateway rewrites source to its elastic IP 203.0.113.7
4    LB addresses may change; DNS name does not     Bank firewall allows only 203.0.113.7 -> request accepted
5                                                   New region, new NAT gateway, new EIP -> bank rejects until allowlisted

Real scenario: a payment provider requires a fixed source IP (allowlist); a customer's on-premises firewall only opens to your published ranges; an SMTP server needs a stable address with matching reverse DNS (PTR) for deliverability; an NLB with static elastic IPs per AZ because a customer cannot use DNS names in their firewall; IPv6-only mobile networks reaching your dual-stack edge.

What provides it:

NeedAWSGoogle CloudCloudflare / othersNote
Fixed inbound IPv4Elastic IP on an instance or NLB; Global Accelerator static anycast IPsReserved static external IPCloudflare proxied records answer with Cloudflare anycast IPsALB has no fixed IPs: point DNS at its name
Fixed outbound IPv4NAT gateway with elastic IP(s)Cloud NAT with reserved IPsCloudflare egress IPs (Zero Trust)One EIP per NAT gateway per AZ; publish the list
Private addressingVPC CIDR from RFC 1918; private NAT gateway for overlapping rangesVPC subnets-Plan non-overlapping CIDRs before peering
IPv6Dual-stack VPCs, egress-only internet gatewayDual-stack subnetsIPv6 on by default for proxied recordsAWS charges for all public IPv4 addresses; IPv6 is a cost lever too

Fix / how to use it: never hard-code addresses of things you do not own; point DNS at provider names (alias records); treat egress IPs as a contract (document them, publish them on a status page, add new ones before moving traffic); reserve one elastic IP per NAT gateway per AZ and keep them in your inventory (Solving: egress allowlists); publish AAAA only when the whole path (LB, WAF, logs, rate limiter keyed by IP) handles IPv6. Subnet math and NAT internals: IP Addressing, NAT.

Authoritative DNS, delegation, NS, SOA and glue Must-know ​

In plain words: the internet finds your name servers by asking the root, which points to .com, which points to the NS records your registrar published for you. Those NS servers are authoritative: their answer is the truth, and everyone else is a cache.

Common misunderstanding: "Changing DNS provider is just changing records." It is changing the delegation at the registrar, and the old NS records are cached at the TLD's TTL (often two days for .com). For that period some resolvers still ask the old provider, so both providers must serve identical zones during the migration.

Definition: a zone is a part of the name space served by one set of authoritative servers. Delegation is the parent zone publishing NS records for a child (a zone cut). Glue records are A/AAAA records for name servers that live inside the zone they serve (ns1.example.com for example.com); RFC 1034 calls them "glue" RRs, published in the parent so resolvers can break the chicken-and-egg loop. The SOA record holds the zone's serial (bumped on every change, used by secondary servers' zone transfers), refresh/retry/expire timers and the MINIMUM field, which today means the negative-caching TTL. The root servers are "13 named authorities" (a to m) served by "hundreds of servers in many countries" (IANA). A recursive resolver walks this chain; an authoritative server only answers for its zones and should refuse everything else.

text
     Recursive resolver (cold cache)               Servers
1    -> a.root-servers.net: A api.example.com?     root: referral, NS for com. (+ glue)
2    -> a.gtld-servers.net: A api.example.com?     .com: referral, NS ns-2048.awsdns-64.net. ... (TTL 2 days)
3    -> ns-2048.awsdns-64.net: A api.example.com?  authoritative (AA bit): 192.0.2.10, TTL 60
4    caches: com. NS (days), example.com. NS (days), api A (60 s)
5    next query for api.example.com after 60 s: goes straight to step 3

Real scenario: moving from a registrar's DNS to Route 53 or Cloudflare; running two providers at once (Route 53 + NS1, or Cloudflare secondary DNS) so one provider's outage is survivable; delegating internal.example.com to a private zone; delegating eu.example.com to a team's own account (sub-delegation keeps blast radius small).

What provides it:

ProductAuthoritative modelMulti-providerNotes
Amazon Route 53Hosted zone, 4 name servers across TLDsPossible, but traffic policies and alias records are Route 53-onlySOA default TTL 900 s, MINIMUM 86400
Cloudflare DNSZone on Cloudflare's anycast networkPrimary or secondary DNS (zone transfer)Proxied records return Cloudflare IPs
Google Cloud DNSManaged zones, public and privateVia zone transfer toolingRouting policies on record sets
NS1 (IBM NS1 Connect)Managed DNS with a filter-chain traffic engineCommonly used as the second providerSteering logic is provider-specific
BIND, Knot, PowerDNS, CoreDNSSelf-hosted authoritativeAXFR/IXFR to secondariesYou run anycast yourself

Fix / how to use it: keep NS TTLs long (hours to days) and A/AAAA TTLs short for steered names; never change NS and records in the same step; for a provider migration, copy the zone, lower TTLs, switch delegation, wait out the old NS TTL, then decommission. If you run two providers, use only record types and policies both support, or accept that advanced steering exists on one of them only.

Record types that matter for architecture Must-know ​

In plain words: each record type is a small promise: "this name is at that address", "this name is really that other name", "this service lives on that port", "only these CAs may issue".

Common misunderstanding: "TXT records are harmless junk." They carry SPF and DKIM for e-mail, ACME DNS-01 challenges and verification tokens for SaaS providers; a stale verification TXT can let a former vendor or an attacker who controls that vendor account claim your domain.

Definition and design use:

TypeRFCHoldsDesign useGotcha
A1035IPv4 addressEndpoint; several records = round-robinNever point at addresses you might release
AAAA3596IPv6 addressDual stack; Happy Eyeballs prefers itBroken IPv6 path causes slow connects, not errors
CNAME1034Canonical nameHand a name to a provider (CDN, SaaS, LB)No other data at that name; not at the apex; each hop adds a lookup
ALIAS / ANAMEProvider featureTarget name, answered as A/AAAAApex to LB/CDNNon-standard; TTL controlled by provider
NS1035Name serversDelegation, sub-delegationLong TTL; mismatched parent/child NS confuse resolvers
SOA1035, 2308Serial, timers, MINIMUMNegative TTL, zone transfersMINIMUM is not a minimum TTL any more
MX1035Mail exchangers with preferenceE-mail routingCNAME at the target is not allowed
TXT1035TextSPF, DKIM, DMARC, ACME, verificationInventory and expire them
SRV2782Priority, weight, port, targetService discovery with portsBrowsers do not use SRV for HTTP
CAA8659Allowed CAsStops other CAs issuing for youChecked at issuance, not by browsers
PTR1035Reverse name for an addressMail deliverability, logsLives in the address owner's zone (ask AWS/your ISP)
HTTPS / SVCB9460Priority, target, ALPN, port, ipv4hint/ipv6hint, ECHHTTP/3 discovery, apex alias, encrypted ClientHelloClient support varies; keep A/AAAA too
DS, DNSKEY, RRSIG4034DNSSEC keys and signaturesChain of trustExpired signatures = SERVFAIL for validating resolvers
text
     Browser, HTTPS RR aware                       Authoritative (example.com)
1    -> HTTPS? example.com, A? example.com, AAAA? (in parallel)
2    <- HTTPS 1 . alpn="h3,h2" ipv4hint=192.0.2.10
3    <- A 192.0.2.10, AAAA 2001:db8::10
4    connects with QUIC (HTTP/3) at once: no Alt-Svc round trip needed
5    an older client ignores HTTPS RR and uses A/AAAA + TCP, as before

Real scenario: www CNAME to a CloudFront or Cloudflare hostname; _dmarc TXT for mail policy; _acme-challenge TXT records created by cert-manager or Laravel Forge; CAA issue "letsencrypt.org" plus iodef for a security mailbox; SRV records generated by Kubernetes for named ports; HTTPS RR to advertise HTTP/3.

Fix / how to use it: keep a machine-readable inventory of every record (the Laravel migration below) with an owner; manage zones as code (Terraform, OctoDNS, DNSControl) so review catches mistakes; add CAA on every zone; publish HTTPS RR where your CDN supports it.

The apex problem: ALIAS, ANAME, CNAME flattening and HTTPS AliasMode Must-know ​

In plain words: example.com itself (the zone apex) cannot be a CNAME, because it must also hold SOA and NS records and a CNAME owner may hold nothing else. But your load balancer or CDN only gives you a name. Providers solved it by resolving the name themselves and answering with addresses.

Common misunderstanding: "ALIAS is just a CNAME with another label." A CNAME is resolved by the user's resolver; an ALIAS is resolved by your DNS provider, which then answers with A/AAAA. That changes three things: GeoDNS and latency decisions made by the target (for example a CDN) see your provider's location, not the user's resolver; the TTL is the provider's choice; and it only works while both are in one provider's world (Route 53 alias to AWS resources) or the provider re-resolves often (Cloudflare CNAME flattening).

Definition: Route 53 alias records can be created "at the top node of a DNS namespace, also known as the zone apex"; when the alias points at an AWS resource "you can't set the time to live (TTL); Route 53 uses the default TTL for the resource", and Route 53 "doesn't charge for alias queries to AWS resources". Cloudflare CNAME flattening "allows you to use a CNAME record at your zone apex": Cloudflare "finds the IP address that a CNAME points to" and "returns the final IP address instead of a CNAME record". ANAME is the generic name used by other providers. The standard answer is RFC 9460's HTTPS/SVCB AliasMode (example.com. HTTPS 0 cdn.provider.net.), which clients that support HTTPS RR follow; until all do, keep a provider alias for A/AAAA as well.

text
     CNAME at www (resolver does the work)          ALIAS / flattening at apex (provider does the work)
1    resolver: A www.example.com?                   resolver: A example.com?
2    auth: CNAME my-alb-1.eu-west-1.elb...          auth (Route 53/Cloudflare) resolves my-alb-1... itself
3    resolver: A my-alb-1.eu-west-1.elb...?         auth: A 192.0.2.31, 192.0.2.32 (TTL chosen by provider)
4    resolver caches both, each with its TTL        resolver caches only A records; it never sees the target name

Real scenario: apex example.com on an AWS ALB (Route 53 alias); apex on a Heroku or Vercel hostname (Cloudflare flattening or an ANAME provider); a third-party domain verification that expects to see the CNAME and fails once flattening is on (Cloudflare warns about exactly this).

What provides it:

ProductMechanismTTLHealth-aware
Amazon Route 53Alias record to ELB, CloudFront, S3 website, API Gateway, Global Accelerator, other records in the zoneTarget's default (not settable) for AWS targets; target record's TTL inside the zone"Evaluate target health"
CloudflareCNAME flattening (default at apex; all CNAMEs optionally; proxied CNAMEs always)300 s "Auto" for proxied recordsVia Load Balancing
Azure DNSAlias record sets to Azure resourcesResource-drivenTraffic Manager profiles
GenericANAME (DNSimple, NS1 and others)Provider-definedProvider-defined
StandardHTTPS / SVCB AliasMode (RFC 9460)Your TTLNo (it is data, not a policy)

Fix / how to use it: use the provider alias at the apex and a CNAME for www; redirect one to the other at the edge; do not flatten CNAMEs used for third-party verification; if the target is a GeoDNS-steered CDN, prefer a CNAME on a subdomain so the CDN sees the user's resolver.

TTL as a control knob Must-know ​

In plain words: the TTL is how many seconds any cache may keep your answer. Short TTL: you can change your mind quickly, and you pay with more queries and more dependence on your DNS provider being up. Long TTL: cheap and resilient, and slow to change.

Common misunderstanding: "TTL 0 means always fresh." RFC 8767 states that a zero TTL means the record "can only be used for the transaction in progress, and should not be cached", yet many resolvers and clients apply a floor, and every lookup now costs a round trip to the authoritative server. Very low TTLs also weaken the most useful property DNS has: answers survive an authoritative outage only as long as they are cached (or served stale).

Definition: RFC 1034 section 3.6: "The meaning of the TTL field is a time limit on how long an RR can be kept in a cache." All records in an RRset share one TTL (RFC 2181). A resolver counts the TTL down; downstream caches receive the remaining TTL (PHP's dns_get_record() documents its ttl as the original TTL "minus whatever length of time has passed since the authoritative name server was queried"). The effective TTL of a CNAME chain is the shortest TTL in the chain.

TTLWorst-case stale answer per cacheQueries/hour from one busy resolver30 s60 s300 s3600 s86400 s30 s1 min5 min1 h1 d120601210.04Bars not to scale beyond 1 h. Query counts assume the name is asked at least once per TTL (a busy resolver), one record type.Steered names (failover, weighted, GeoDNS): 30-300 s. Stable names (NS, MX, TXT, CAA): hours to 2 days.Planned change: lower the TTL, wait one OLD TTL, change, verify, raise it again (RFC 1034 section 3.6).Resolvers may clamp: Google Public DNS generally caps at about 6 h; some resolvers raise tiny TTLs.
text
     Planned migration of api.example.com from 192.0.2.10 to 198.51.100.20 (old TTL 86400)
1    D-2   lower TTL 86400 -> 60 (the change itself is cached for up to 86400 s)
2    D-1   wait at least one OLD TTL (24 h) so every cache has picked up TTL 60
3    D0    change A to 198.51.100.20; most caches converge within 60 s
4    D0+1h keep 192.0.2.10 serving (or redirecting) for clients that ignore TTLs
5    D+7   raise TTL back to 3600 or 86400 (RFC 1034 section 3.6)

Real scenario: a data-centre migration; moving a zone from one load balancer to another; a CDN cutover; a canary that needs to be rolled back in minutes; a partner who cached your address for a week because their resolver ignores TTLs.

What each layer really does:

LayerBehaviourKnob
Google Public DNSCaps cached TTLs ("generally limited to six hours even if the actual TTL is longer"); ECS answers cannot be flushed, so keep their TTLs at 15 minutes or lessFlush Cache tool for non-ECS names
Cloudflare proxied recordsTTL fixed at 300 s ("Auto"), not editableUse DNS-only records for custom TTLs
Amazon Route 53 aliasTTL of the AWS target (not settable)-
CoreDNS kubernetes pluginDefault 5 s, max 3600 sttl option
libcurl (PHP, Laravel HTTP client)Caches names 60 s by default on a handleCURLOPT_DNS_CACHE_TIMEOUT
Go net packageNo answer cache; every Dial resolves (through the OS or the Go resolver)Add your own (the Go section)
Long-lived connection poolsKeep the old address for the life of the connectionMax connection age, idle timeouts

Fix / how to use it: 30-60 s for names behind failover or canary policies, 300 s for normal steered names, hours to days for NS, MX, TXT, CAA; lower before planned changes; measure query volume per name (Route 53 charges per query except alias queries to AWS resources) before going below 60 s.

Negative caching Important ​

In plain words: "this name does not exist" is cached too, and for how long is decided by your SOA record, not by the record you are about to create.

Common misunderstanding: "I created the record, so it works now." If anyone (a health checker, a deploy script, a user typing early) asked for the name before it existed, their resolver cached NXDOMAIN for the negative TTL. Route 53's default SOA (TTL 900, MINIMUM 86400) gives 15 minutes; zones with SOA MINIMUM 86400 and a long SOA TTL give a full day.

Definition: RFC 2308 section 3: authoritative servers "MUST include the SOA record of the zone in the authority section" of NXDOMAIN and NODATA responses, and the TTL of that SOA "is set from the minimum of the MINIMUM field of the SOA record and the TTL of the SOA itself, and indicates how long a resolver may cache the negative answer". NXDOMAIN means the name does not exist; NODATA means the name exists but has no record of this type (NOERROR, empty answer), common for AAAA on IPv4-only names. RFC 2308 recommends resolvers cap negative caching: "Values of one to three hours have been found to work well".

text
     Deploy script / user                     Resolver                      Route 53 (SOA TTL 900, MIN 86400)
1    12:00:00 GET https://new.example.com
2                                             A new.example.com? -> NXDOMAIN + SOA (TTL 900)
3                                             caches NXDOMAIN until 12:15:00
4    12:01:00 record created in Route 53
5    12:05:00 retry: "Could not resolve host" <- served from negative cache
6    12:15:01 retry works

Real scenario: a blue/green cutover that creates green.example.com minutes before switching; Kubernetes pods resolving a Service name before the Service exists; certificate issuance probing a name before the record propagates; a typo in a client config that keeps failing after the fix.

Fix / how to use it: create records before anyone queries them (pre-create and test from a resolver you can flush); keep the SOA TTL and MINIMUM moderate (Route 53 lets you edit the SOA: 300-900 s is common); when a new name fails, check for cached NXDOMAIN before debugging the application.

Caches you do not control: clamping, serve-stale and clients Important ​

In plain words: between your authoritative server and the connection there are four or five caches; some raise your TTL, some lower it, some keep answers after they expire, and some never ask again.

Common misunderstanding: "Our clients honour TTLs because the RFC says so." Stubs and resolvers mostly do; applications often do not: a Go or Java process that resolves once at start-up, an HTTP connection pool with keep-alive, a database driver with a fixed host list, a mobile app caching an IP in settings.

Definition: TTL clamping is a resolver applying its own minimum or maximum to your TTL (Google Public DNS caps at about six hours). Serve-stale (RFC 8767) lets a resolver answer with expired data when it cannot refresh: stale answers carry a TTL "greater than 0, with a RECOMMENDED value of 30 seconds", failed refreshes are retried "no more frequently than every 30 seconds", and the maximum stale timer is suggested between 1 and 3 days. Prefetch (Unbound, BIND) refreshes popular names before they expire. Resolver location matters too: Route 53 latency and geolocation routing use the resolver's address unless ECS is present.

text
     t       Authoritative                 Resolver (serve-stale on)          Client
1    0 s     A 192.0.2.10 TTL 60           caches, expires at 60 s
2    90 s    unreachable (DDoS)            refresh fails; serves stale, TTL 30   connects fine
3    120 s   still down                    within 30 s recheck: no new query    connects fine
4    150 s   back                          refresh succeeds; fresh TTL 60        -
5    without serve-stale, step 2 returns SERVFAIL and the site is "down" although servers are fine

What each product does:

CacheProductBehaviour
Public resolverGoogle Public DNSAnycast, ECS to supporting servers, TTL capped near 6 h, Flush Cache tool
Public resolverCloudflare 1.1.1.1Anycast, no ECS ("does not include client IP information"), DoH/DoT/ODoH
Cloud VPC resolverRoute 53 Resolver (AmazonProvidedDNS)Resolves private hosted zones for the VPC (split view)
KubernetesCoreDNS with cache pluginPod queries go to CoreDNS; ndots:5 multiplies queries for external names
Self-hostedUnbound, BINDserve-expired, stale-answer-enable, prefetch
Language runtimeGo netNo cache; GODEBUG=netdns=go or cgo picks the resolver
HTTP clientlibcurl / Guzzle / Laravel Http60 s DNS cache per handle by default

Fix / how to use it: assume the slowest client defines your failover time; set a maximum connection lifetime in pools (Go http.Transport idle timeouts, database pool ConnMaxLifetime); re-resolve on reconnect; run a local caching resolver with serve-stale for your own fleet; never cache an IP in configuration.

Round-robin DNS and multivalue answers Important ​

In plain words: publish several A records for one name and clients spread themselves across them, roughly.

Common misunderstanding: "Round-robin DNS is load balancing." It is load spreading with no knowledge of load or health: a dead address stays in the answer until you remove it, resolvers and stubs reorder or truncate lists, and one big NAT'd office behind one resolver all land on whatever order that resolver cached.

Definition: an RRset with multiple records; servers typically rotate the order, clients usually try the first address (with Happy Eyeballs racing IPv6 and IPv4). Route 53 multivalue answer routing adds health checks: it "responds to DNS queries with up to eight healthy records and gives different answers to different DNS resolvers", and "When all records are unhealthy, Route 53 responds to DNS queries with up to eight unhealthy records". AWS adds: "This isn't a substitute for a load balancer".

text
     Resolver A (office, 2,000 users)          Resolver B (mobile ISP)
1    gets 192.0.2.1, 192.0.2.2, 192.0.2.3      gets 192.0.2.3, 192.0.2.1, 192.0.2.2
2    caches that order for the TTL             caches that order
3    most office clients connect to .1         most mobile clients connect to .3
4    192.0.2.2 dies: clients that picked it retry the next address after a connect timeout

Real scenario: spreading traffic across several NLBs or edge proxies; SMTP and other protocols where clients retry the next address; a quick way to shard read-only APIs across regions; the DNS front of a fleet of HAProxy or NGINX boxes.

Fix / how to use it: use multivalue or failover policies so dead addresses leave the answer; put a real load balancer behind each address; keep the list short (big answers may truncate and force TCP); make clients retry other addresses on connect failure (Go's dialer does, for multiple A/AAAA records).

Weighted routing Must-know ​

In plain words: answer 90% of lookups with the old stack and 10% with the new one, and move the dial.

Common misunderstanding: "Weight 10 sends 10% of users." It sends about 10% of resolver lookups; a resolver serving a million users counts once per TTL. With few, large resolvers the split is lumpy, and each user is sticky only for the TTL.

Definition: Route 53 weighted records share a name and type; each gets traffic "based on the weight you assign to the record as a share of the total weight". Weights are 0-255; "If you want to stop sending traffic to a resource, change the weight for that record to 0", and zero-weight records are considered only "If all the records that have a weight greater than 0 are unhealthy". Cloudflare Load Balancing applies weights to pools and to endpoints inside pools; Google Cloud DNS calls it weighted round robin (WRR).

text
     t      Weights blue/green    Effect
1    0      255 / 0               all on blue
2    +5m    245 / 10              ~4% of lookups get green (10/255)
3    +20m   error rate up on green: set green to 0
4    +21m   new lookups all go blue; users who got green keep it for up to TTL (60 s) + client caching
5    +1d    fixed release: 128 / 128, then 0 / 255

Real scenario: canary of a new region, CDN, or provider; moving 1% of traffic to a new database proxy fleet; migrating from on-premises to cloud gradually; splitting between two CDNs by cost.

Fix / how to use it: pair weights with health checks so a broken target drops out without a human; keep the TTL short (30-60 s) during the shift; measure by request metrics at the targets, not by weight; for per-user stickiness or exact percentages use an L7 traffic split (Envoy, NGINX split_clients, AWS ALB weighted target groups) instead (Blue/green and canary).

Latency-based routing Important ​

In plain words: send each resolver to the region with the lowest measured network latency, not the nearest on a map.

Common misunderstanding: "Latency routing reacts to my servers being slow." It measures network latency between users' networks and the provider's regions over time; it knows nothing about your application latency or load. A region at 100% CPU still wins if it is close in network terms.

Definition: Route 53 latency records route users "from the AWS Region with the lowest latency", using "latency data taken over a period of time"; "A request routed to the Oregon Region this week might go to the Singapore Region next week". With ECS, Route 53 considers "a truncated version of the user's IP address". Cloudflare's Dynamic steering uses round-trip times from its health monitors; Cloudflare Proximity steering uses coordinates you give each pool.

text
     Resolver in London                         Route 53
1    A? api.example.com (no ECS)
2                                               latency table: London->eu-west-2 12 ms, ->us-east-1 75 ms
3    <- eu-west-2 ALB alias, TTL 60
4    eu-west-2 health check fails -> next-lowest healthy Region (with Evaluate Target Health)

Fix / how to use it: combine latency records with health checks (alias records with "Evaluate target health"); keep data residency rules in geolocation policies instead, since latency can send an EU user to a US region; watch for regions that win on latency but lack capacity (cap with weights inside each latency record using nested policies or Route 53 traffic flow).

Geolocation routing, GeoDNS and EDNS Client Subnet Must-know ​

In plain words: answer differently by where the query comes from: German users get Frankfurt, Brazilians get São Paulo, and a default answer catches the rest.

Common misunderstanding: "Geolocation is accurate per user." It is per resolver address, refined to a subnet only when the resolver sends ECS. Users on 1.1.1.1 (no ECS) are located by Cloudflare's resolver site; corporate users by their company's resolver; VPN users by the VPN exit.

Definition: GeoDNS maps the query source to a location and the location to an answer. Route 53 geolocation works "by continent, by country, or by state in the United States", answers the most specific match, and returns "no answer" for unmapped locations unless you create a default record. Route 53 geoproximity routes by distance to your resources with a bias (1 to 99 grows a region, -1 to -99 shrinks it); IP-based routing uses your own CIDR-to-location table. EDNS Client Subnet (RFC 7871) lets a recursive resolver include a truncated client prefix; RFC 7871 recommends truncating "IPv4 addresses to 24 bits. 56 bits are recommended for IPv6", and the authoritative server returns a SCOPE PREFIX-LENGTH telling the resolver how widely it may reuse the answer.

EU usersECS 198.51.100.0/24US usersECS 203.0.113.0/24GeoDNS authoritativeapi.example.com, TTL 60subnet -> region tableunhealthy -> fallback listall unhealthy -> fail openeu-west-1 LB192.0.2.103 failed checks: OUTus-east-1 LB192.0.2.20healthyHealth checkers, many sitesA?A?probe /healthz/deepEU answer: 192.0.2.20 after failoverDetect: 10 s x 3 = ~30 s (fast)Record TTL: 60 sClient caches, pinned pools: 0 s ... foreverFailover time = detection + TTL + whatever the client keeps. DNS can only steer new lookups;open keep-alive connections, connection pools and processes that resolved once keep the old region.Standard 30 s checks x 3 = ~90 s detection.
text
     User 198.51.100.77 -> Google Public DNS (ECS on)         GeoDNS authoritative
1    A? api.example.com, ECS 198.51.100.0/24
2                                                             198.51.100.0/24 -> EU rule (prefix /24)
3    <- A 192.0.2.10 TTL 60, ECS scope /24
4    resolver caches the answer for 198.51.100.0/24 only; a client in 203.0.113.0/24 triggers a new query
5    same user on 1.1.1.1 (no ECS): GeoDNS sees the resolver site's address and answers for that location

Real scenario: data residency (EU users must hit EU infrastructure; enforce it again at the application layer, since DNS is only a hint); serving localized content or a regional checkout; sending a country to a dedicated cluster after a legal requirement; reducing latency for a global API without anycast.

What provides it:

ProductLocation sourceGranularityDefault behaviour
Amazon Route 53 geolocationResolver IP or ECSContinent, country, US state"no answer" without a default record
Amazon Route 53 IP-basedYour CIDR blocksAny prefixDefault (*) location
Cloudflare Load Balancing Geo / ProximityResolver location, ECS (prefer_ecs), Cloudflare PoPRegion, country (ECS: country-level)Fallback pool
Google Cloud DNS geolocationSource regionGCP regionsNearest configured
NS1Filter chain (geotarget filters)Country, region, ASNConfigurable

Fix / how to use it: always define a default record; keep ECS-steered TTLs short (Google: 15 minutes or less, because ECS answers cannot be flushed); test from several resolvers with dig +subnet; enforce residency and compliance at the application and data layer, not only in DNS; the Go GeoDNS server shows the mechanism end to end.

Failover routing and health checks Must-know ​

In plain words: a probe outside your system asks "are you alive?" every few seconds; when the primary stops answering, DNS starts handing out the secondary.

Common misunderstanding: "A health check on / is enough." The page may return 200 from a CDN cache or a static error template while the database is down; or it may fail because of a slow dependency you could have degraded around. A good health endpoint checks what makes this region unable to serve, quickly, and can be forced to fail for a planned drain.

Definition: Route 53 health checkers in several locations probe "every 10 seconds or every 30 seconds"; an endpoint becomes unhealthy after the failure threshold of consecutive failures (default 3); "If more than 18% of health checkers report that an endpoint is healthy, Route 53 considers it healthy". For HTTP/HTTPS checks Route 53 "must be able to establish a TCP connection with the endpoint within four seconds" and the endpoint must answer "2xx or 3xx within two seconds after connecting"; with string matching the string "must appear entirely in the first 5,120 bytes". HTTPS checks "don't validate SSL/TLS certificates". Calculated health checks combine other checks (for example "at least 2 of 3 web servers"); checks can also follow CloudWatch alarms. Failover routing answers the primary while healthy and the secondary otherwise. Cloudflare monitors probe "from every single data center"; pools fail over by priority.

text
     t (s)   Health checkers -> eu-west-1 /healthz/deep      Route 53 answer for EU resolvers
1    0       200 HEALTHY_OK                                 eu-west-1 (TTL 60)
2    10      timeout                                        eu-west-1 (1 of 3 failures)
3    20      timeout                                        eu-west-1 (2 of 3)
4    30      timeout -> unhealthy (<= 18% report healthy)    us-east-1 from now on
5    30-90   resolvers with cached eu-west-1 answers expire  traffic drains to us-east-1
6    90+     clients with pooled connections to eu-west-1 keep failing until they reconnect

Real scenario: active-passive DR region; a static "sorry" page on S3 as the secondary of last resort; failing over to a second CDN; draining a region before maintenance by making its health endpoint return 503.

What provides it:

ProductProbeIntervalThresholdNotes
Amazon Route 53HTTP, HTTPS, TCP, string match, calculated, CloudWatch alarm, private endpoint checks10 s (fast) or 30 sFailure threshold (default 3)18% rule across locations
Cloudflare Load BalancingHTTP(S), TCP, ICMP, SMTP, UDP-ICMP monitorsConfigurableRetries + timeoutProbes from every data center unless limited
Google Cloud DNSHealth checks on internal/external LBsLB health check config-Failover and WRR policies
NS1Monitoring jobs feeding the filter chainConfigurableConfigurable"Up" filter removes failed answers

Fix / how to use it: expose a deep health endpoint that checks only local hard dependencies within a time budget (the Laravel controller); add a manual drain flag; use fast checks and TTL 60 for primary/secondary pairs; alert on health-check state changes; decide fail-open behaviour (Route 53 multivalue and the Go pool return something rather than nothing when everything looks down, because a broken checker is more likely than a total outage).

DNS failover vs load-balancer failover vs GSLB Must-know ​

In plain words: DNS failover changes which address new users get; load-balancer failover changes which server behind one address handles the next request; a global server load balancer (GSLB) is the product category that does the first, often with the second built in.

Common misunderstanding: "We have Route 53 failover, so we do not need a global load balancer." DNS failover takes minutes and cannot move existing connections; an anycast L7 proxy (Cloudflare, AWS Global Accelerator in front of regional LBs, Google Cloud's global external Application Load Balancer) moves new requests in seconds because the client's address never changes.

Definition: GSLB originally meant appliances (F5 BIG-IP DNS, Citrix ADC GSLB) answering DNS with health and load awareness; today the term covers Route 53 traffic policies, Cloudflare Load Balancing, NS1, Azure Traffic Manager and Google Cloud DNS routing policies. LB failover is a regional or anycast proxy changing its upstream. The layers combine: DNS picks the region, the regional LB picks the instance.

text
     Failure: eu-west-1 database primary dies
1    Regional LB (ALB): targets still pass shallow checks -> keeps sending traffic (bad health check design)
2    Deep health endpoint returns 503 -> ALB marks targets unhealthy within ~10-30 s
3    Route 53 sees /healthz/deep failing 3 x 10 s -> answers us-east-1 for new lookups
4    Anycast global LB alternative: proxy sees regional 503s -> shifts requests in seconds, no DNS change
OptionSteersReaction timeMoves existing connectionsCost / complexity
DNS failover (Route 53, Cloud DNS)New lookupsdetection + TTL + client caches: minutesNoLow
DNS GSLB with steering (Cloudflare DNS-only LB, NS1, Azure Traffic Manager)New lookups, by geo, latency, loadMinutesNoMedium
Anycast L7 global LB (Cloudflare proxied LB, Google global external ALB)Each requestSecondsNew requests yes; open streams noMedium-high, traffic through provider
Anycast L4 (AWS Global Accelerator)Each new connectionSecondsNoMedium
Regional LB (ALB, NLB, HAProxy, NGINX, Envoy)Each request inside a regionSecondsCan drainPer region
Client-side failover (SDK, the Laravel router)Each callMilliseconds to secondsNext callCode in every client

Fix / how to use it: use DNS for region selection and coarse failover; a regional LB inside each region; an anycast global LB when minutes of partial outage are not acceptable; client-side failover for service-to-service calls you own. Algorithms, L4 vs L7, and LB health checks: Load Balancing.

Anycast and BGP Must-know ​

In plain words: the same IP address is announced from many places at once, and the internet's routing delivers each packet to the nearest one. No DNS change is needed when a site disappears: it stops announcing and traffic flows to the next.

Common misunderstanding: "Anycast is a load balancer." It balances only by network topology: RFC 4786 says "Load-balancing between Anycast Nodes is typically difficult to achieve (load distribution between nodes is generally unbalanced". A route change can also move a long TCP connection to a site that has never seen it, which is why anycast suits short exchanges (DNS over UDP) and stateless or proxy-terminated HTTP best.

Definition: unicast: one address, one location ("every node on the network gets an IP address which is unique to it", Cloudflare). Anycast (RFC 4786): a service address announced "at Anycast Nodes in two or more discrete locations", where "The routing system decides which node is used for each request". On the internet the routing system is BGP: each site announces the same prefix (in common operator practice at least a /24 for IPv4 or a /48 for IPv6, the shortest prefixes most networks accept) from its own autonomous system or the provider's; routers choose the best path. Withdrawing the announcement removes the site. Google Public DNS "uses anycast routing to send users to the geographically closest data center"; Cloudflare proxied records answer with "Cloudflare anycast IP addresses".

Unicast: one address, one placeAnycast: one prefix, announced from many places (BGP)User, Singapore~200 ms RTT (estimate)Virginia203.0.113.5Frankfurt PoPwithdraws routeVirginia PoP192.0.2.0/24Singapore PoP192.0.2.0/24User, BerlinUser, BostonUser, Jakartaold pathnew best pathSame IP everywhere: no DNS change, failover at BGP speed (seconds to minutes).Catch: a route change mid-connection can move a TCP flow to another PoP.Failover needs DNS or an elastic IP move.Used by: DNS root server instances, Google Public DNS 8.8.8.8, Cloudflare 1.1.1.1 and Cloudflare proxied records.
text
     Berlin user -> 192.0.2.53                 BGP view
1    best path: Frankfurt PoP (AS path length 2)
2    Frankfurt health daemon fails -> withdraws 192.0.2.0/24 announcement
3    BGP converges (seconds to minutes): best path now Amsterdam or Virginia
4    new UDP queries / new TCP connections land on the new PoP
5    TCP connections opened in Frankfurt mid-flight are reset (state lived there)

Real scenario: authoritative and recursive DNS (root server instances, Route 53 and Cloudflare name servers, 8.8.8.8, 1.1.1.1); CDN edges; DDoS absorption (attack traffic is split across all sites near its sources); AWS Global Accelerator static IPs in front of regional NLBs/ALBs; your own anycast with BIRD or FRR on bare metal.

Fix / how to use it: buy anycast rather than build it unless you have your own ASN and transit; use it for the edge, and let the edge proxy talk unicast to your regions; keep TCP-heavy, stateful sessions behind a proxy that terminates them at the edge.

Split-horizon DNS Important ​

In plain words: the same name gets a private answer inside your network and a public answer outside.

Common misunderstanding: "Split-horizon is a security boundary." It hides addresses from casual lookups, not from anyone who connects from inside or reads a leaked config. Its real costs are operational: two zones drift apart, and a laptop on VPN caches the internal answer and keeps using it at home.

Definition: two views of one zone selected by the query source. Route 53 calls it "split-view DNS, also known as split-horizon DNS": create "public and private hosted zones that have the same name", associate the private zone with VPCs, and queries from those VPCs get the private answers. If the queried name does not exist in the matching private zone, the VPC Resolver "returns NXDOMAIN (non-existent domain) to the client and doesn't retry the query against public DNS", unless you enable public DNS fallback for the zone. BIND implements it with view clauses; Cloudflare with internal DNS views; Kubernetes clusters with CoreDNS stub domains and forwarders.

text
     Query source                         api.example.com answer
1    Pod in VPC (private zone associated) 10.20.0.15 (internal NLB), TTL 60
2    User on the internet                 192.0.2.10 (public ALB / CDN), TTL 60
3    Laptop on VPN, then at home          cached 10.20.0.15 until TTL ends -> timeouts
4    New record only in public zone: VPC clients get NXDOMAIN from the private zone

Real scenario: internal services reachable by the same hostname with internal TLS certificates; keeping database and admin endpoints private; hybrid cloud with on-premises resolvers forwarding to Route 53 Resolver inbound endpoints.

Fix / how to use it: generate both views from one source of truth; prefer distinct internal names (api.internal.example.com) unless the same certificate and hostname must work both ways; keep TTLs short for names that cross the VPN boundary.

DNS for service discovery: SRV, Kubernetes DNS and CoreDNS Important ​

In plain words: inside a cluster, a service's name is its discovery mechanism: orders.shop.svc.cluster.local resolves to a stable virtual IP, or to every pod for headless Services.

Common misunderstanding: "DNS-based discovery gives instant updates." CoreDNS answers with a 5-second TTL by default and clients cache on top; pods that died seconds ago can still be returned for headless Services. ClusterIP Services avoid this by giving a stable virtual IP and letting kube-proxy or the CNI change backends.

Definition: Kubernetes gives normal Services A/AAAA records my-svc.my-namespace.svc.cluster-domain.example resolving to the cluster IP; headless Services resolve to the set of pod IPs; SRV records exist for named ports in the form _port-name._port-protocol.my-svc.my-namespace.svc.cluster-domain.example. Pods get options ndots:5, so a name with fewer than five dots is tried against the search domains first (extra queries for every external name). The CoreDNS kubernetes plugin's ttl "default is 5 seconds", maximum 3600. RFC 2782 SRV clients "MUST attempt to contact the target host with the lowest-numbered priority" and spread by weight inside one priority. Go exposes this as net.LookupSRV.

text
     Pod in namespace shop                       CoreDNS
1    A? orders (ndots:5 -> orders.shop.svc.cluster.local first)
2                                                ClusterIP Service: 10.96.12.7, TTL 5
3    SRV? _grpc._tcp.orders.shop.svc.cluster.local
4                                                headless: 0 50 9090 10-244-1-7.orders..., 0 50 9090 10-244-2-9.orders...
5    client connects to a pod; a pod deleted at t=2 s may still be returned until t=5 s plus client cache

Real scenario: gRPC clients doing client-side load balancing over headless Services; StatefulSets with stable per-pod names (kafka-0.kafka.data.svc); Consul DNS interface for VMs; AWS Cloud Map with Route 53 private namespaces.

Fix / how to use it: prefer ClusterIP for most traffic; use headless + client-side balancing only with clients that re-resolve (gRPC dns:/// resolver re-resolves on connection failure); write FQDNs with a trailing dot for external names in pods to skip ndots expansion. Registry-based discovery, health and client-side vs server-side discovery: Service Discovery; CoreDNS deployment: Kubernetes Networking.

Blue/green and canary via DNS, and their limits Important ​

In plain words: keep two stacks, point the name at one, then move the name (all at once for blue/green, a little at a time for canary).

Common misunderstanding: "Switching DNS back is an instant rollback." Lookups made during the bad window stay cached for the TTL, connection pools keep their sockets, and mobile apps or partners that cached the address may take hours. A DNS rollback is fast for new clients only.

Definition: blue/green via DNS: flip a record (or an alias) from blue's load balancer to green's. Canary via DNS: weighted records with a small weight on the new stack. Both are coarse (per resolver, not per user or request) and sticky only for the TTL.

text
     t       Action                                Who is on green
1    T0      green weight 0 -> 10 (TTL 60)         ~4% of resolvers' lookups after their cache expires
2    T0+60s  metrics from green look good           same; heavy resolvers count once per TTL
3    T0+10m  flip: blue 0, green 255                new lookups all green; pooled connections still on blue
4    T0+30m  bug found: flip back                   new lookups blue within ~60 s; long-lived clients stay on green
5    T0+2h   decommission green only after its traffic reaches zero (watch LB request counts, not DNS)

What fits each need:

NeedDNSL7 (Envoy, NGINX, ALB weighted target groups, Istio)
Whole-stack swap including LB, CDN, regionGoodCannot, it lives inside one stack
Exact percentages, per-user stickiness, header-based routingNoYes
Rollback in seconds for everyoneNoYes
Works for non-HTTP protocolsYesProtocol-specific

Fix / how to use it: use DNS to swap whole stacks or providers and an L7 router for request-level canaries; lower TTLs a full old-TTL in advance; keep the old stack serving until its request count is zero; cap connection lifetimes so clients re-resolve.

DNSSEC Important ​

In plain words: your zone signs its records; validating resolvers check the signature chain from the root down, so a forged answer is rejected.

Common misunderstanding: "DNSSEC protects users from spoofing on their Wi-Fi." Only if the resolver validates and the path from the resolver to the user is trusted; DNSSEC does not encrypt and does not protect the last hop unless the stub validates or uses DoH/DoT to a validating resolver.

Definition: RFC 4033: DNSSEC adds "data origin authentication and data integrity"; "These extensions do not provide confidentiality". Records are signed (RRSIG) with zone keys (DNSKEY, often a KSK and a ZSK); the parent publishes a DS record (a hash of the child's key) so trust chains from the root. NSEC/NSEC3 prove non-existence. Cloudflare: "When you enable DNSSEC, Cloudflare signs your zone, publishes your public signing keys, and generates your DS record" which you then add at your registrar. Google Public DNS has validated DNSSEC since January 2013.

text
     Validating resolver                         Zones
1    A? api.example.com + DO bit
2    root DNSKEY (trust anchor) -> com. DS -> com. DNSKEY -> example.com. DS -> example.com. DNSKEY
3    api.example.com A + RRSIG verified -> AD bit set, answer returned
4    signature expired or DS mismatch after a provider move -> SERVFAIL for every validating user

Fix / how to use it: enable DNSSEC through a provider that automates signing and key rollover (Route 53, Cloudflare, Google Cloud DNS); remove the DS at the registrar before moving to a provider that will sign with different keys (or use multi-signer procedures); alert on signature expiry; treat a DS mismatch as a full outage scenario in your runbook.

DoH and DoT Good to know ​

In plain words: wrap DNS queries in TLS (DoT, port 853) or inside HTTPS (DoH, port 443) so the network between the client and its resolver cannot read or change them.

Common misunderstanding: "DoH breaks our internal DNS on purpose." It bypasses it if the browser or app chooses its own DoH resolver: split-horizon names stop resolving and DNS-based filtering stops working. Enterprises manage this with browser policies and by running their own DoH/DoT endpoint.

Definition: RFC 7858 DoT: servers "accept TCP connections on port 853"; its scope is "securing stub-to-recursive traffic". RFC 8484 DoH: "Each DNS query-response pair is mapped into an HTTP exchange", media type application/dns-message. Cloudflare 1.1.1.1 offers DoT on 853, DoH on 443 and Oblivious DoH (ODoH), which "Adds a privacy layer to DoH so that no single entity can see both your identity and your query". None of these changes anything between the resolver and your authoritative servers.

text
     Client                         Network observer        Resolver (1.1.1.1)
1    UDP 53: A? intranet.corp       sees and can spoof      -
2    DoH: POST /dns-query (TLS)     sees TLS to 1.1.1.1     resolves publicly: NXDOMAIN for intranet.corp
3    split-horizon name fails unless the client uses the corporate resolver (policy or local DoH endpoint)

Fix / how to use it: for public services nothing changes; for internal names, make clients use your resolver (MDM, browser enterprise policy) or provide an internal DoH endpoint; for privacy of service-to-service DNS inside a VPC, rely on the VPC resolver rather than public DoH.

DNS as attack surface: amplification, cache poisoning, subdomain takeover Must-know ​

In plain words: DNS can be used against others (your open resolver amplifies attacks), against your users (forged answers in a cache), and against your brand (a forgotten CNAME that someone else can now answer for).

Common misunderstanding: "Our DNS is hosted by Route 53, so DNS security is AWS's problem." The provider protects its servers; your zone content is yours. The most common real-world DNS incident for application teams is a dangling CNAME: a record pointing at a deleted S3 website, Azure App Service, Heroku app or CloudFront distribution that an attacker re-creates under their own account.

Definition:

  • DNS amplification (reflection): spoofed-source UDP queries to open resolvers or authoritative servers make them send large answers to the victim. RFC 5358: "due to the small query-large response potential of the DNS system, it is easy to yield great amplification". Cloudflare measured "a 64 byte query that resulted in a 3,223 byte response", "a 50x amplification".
  • Cache poisoning: getting a forged answer accepted into a resolver's cache. CERT VU#800113 (2008): the DNS transaction ID is 16 bits, so an attacker needs "on average, 32,768 attempts" if it is random; the Kaminsky technique made such attempts cheap. Mitigations: source-port randomization, 0x20 case randomization, DNS cookies, DNSSEC validation.
  • Subdomain takeover: MDN: it "occurs when an attacker gains control over a subdomain of a target domain. Typically, this happens when the subdomain has a canonical name (CNAME) in the Domain Name System (DNS), but no host is providing content for it", which lets the attacker "read cookies set from the main domain, perform cross-site scripting, or circumvent content security policies". A released elastic IP in an A record is the same bug for addresses.
text
     t        Team                                           Attacker
1    Jan      promo.example.com CNAME promo-site.azurewebsites.net.
2    Mar      campaign ends; App Service deleted; DNS record forgotten
3    Apr                                                     scans CNAMEs, finds the unclaimed target name
4    Apr                                                     creates promo-site in own Azure account, binds promo.example.com
5    Apr      promo.example.com serves attacker content with a valid cert; cookies scoped to .example.com exposed

What provides protection:

ThreatYour sideProvider side
Amplification from your serversNo open recursion; authoritative servers answer only their zones (REFUSED otherwise); response rate limiting (BIND RRL)Route 53, Cloudflare absorb at anycast edge
Amplification against youAnycast edge or DDoS service in front (DDoS)Cloudflare, AWS Shield
Cache poisoning of your users' resolversSign the zone (DNSSEC)Resolvers: port + ID randomization, 0x20, DNS cookies, validation (Google Public DNS)
Subdomain takeoverDelete DNS before the resource; inventory; CI audit (Laravel command); avoid wildcard CNAMEs to third partiesSome providers verify domain ownership (TXT) before binding
Unauthorized certificatesCAA recordsCAs must check CAA
Registrar hijackRegistrar lock, MFA, registry lock for key domainsRegistrar

Fix / how to use it: order of operations on decommission is always DNS first, resource second; scan your zones nightly; never run an open resolver; enable DNSSEC and CAA on production zones; scope cookies to the narrowest domain that works.

Mechanics ​

Message anatomy: flags, RCODEs, sizes ​

A DNS message has a header, a question, and answer, authority and additional sections. The fields that matter when you debug routing:

FieldMeaningWhere it bites
QR, AAResponse; Authoritative Answeraa absent in dig output means you are reading a cache
RD, RARecursion Desired / AvailableAn authoritative server answering RA to the internet is an open resolver
TCTruncated: retry over TCPLarge answers (many A records, DNSSEC, TXT) need TCP 53 open
AD, CD, DOAuthenticated Data, Checking Disabled, DNSSEC OKAD set by a validating resolver
ID (16 bits)Matches a response to a queryCache-poisoning target; must be random
EDNS(0) OPT, UDP sizeRFC 6891; payload size beyond 512 bytes1232 bytes is the common safe value to avoid IP fragmentation
ECS optionRFC 7871 SOURCE / SCOPE PREFIX-LENGTHGeoDNS answers cached per subnet
RCODENameWhat it means for you
0NOERRORSuccess; with an empty answer section it is NODATA
1FORMERRMalformed query (or ECS with a bad prefix, RFC 7871)
2SERVFAILResolver could not get a usable answer: authoritative down, DNSSEC validation failed, lame delegation
3NXDOMAINName does not exist; cached for the negative TTL
5REFUSEDServer will not answer (not its zone, recursion not allowed)

Failover arithmetic ​

text
     Worst-case time until a client reaches the healthy region
1    detection  = request_interval x failure_threshold        (Route 53 fast: 10 s x 3 = 30 s; standard: 30 s x 3 = 90 s)
2    + publish  = provider applies the new answer             (small; measure it in a game day)
3    + TTL      = record TTL the resolver cached               (60 s for steered names)
4    + client   = app-level caches and pooled connections      (libcurl 60 s; a pinned pool: until restart)
5    example, fast checks, TTL 60, libcurl default: 30 + 60 + 60 = ~150 s
6    example, standard checks, TTL 300, Go pool with no max lifetime: 90 + 300 + unbounded

Query load is the other side: a resolver that sees steady traffic for a name sends about 3600 / TTL queries per hour per record type (120 at TTL 30, 12 at TTL 300). Multiply by the number of large resolvers (public resolvers, ISPs, cloud VPC resolvers) to size cost on a per-query priced provider; Route 53 does not charge for alias queries to AWS resources.

Exact knobs ​

ProductKnobValue / rangeEffect
Amazon Route 53Health check request interval30 s (standard) or 10 s (fast)Detection speed
Amazon Route 53Failure threshold1-10, default 3Consecutive failures before unhealthy
Amazon Route 53Healthy rulemore than 18% of checkers report healthyAvoids one region's network issue failing you over
Amazon Route 53HTTP timingTCP connect 4 s, status within 2 s, body string in first 5,120 bytes within the next 2 sHealth endpoint must be fast and small
Amazon Route 53Weighted weight0-2550 = only when all non-zero weights are unhealthy
Amazon Route 53Multivalueup to 8 healthy records per answerHealth-aware round-robin
Amazon Route 53Geoproximity bias-99 to 99Shrinks or grows a region's catchment
Amazon Route 53SOA defaultTTL 900, MINIMUM 86400 (negative TTL = 900)NXDOMAIN caching
CloudflareProxied record TTL300 s "Auto", not editableChange propagation for proxied names
Cloudflare Load BalancingSteeringOff/standard, Geo, Dynamic, Proximity, Random, Least Outstanding RequestsPool choice
Cloudflare Load Balancingprefer_ecsproximity / geo / always / neverWhether ECS decides location
Google Public DNSMax cached TTLabout 6 hLong TTLs clamped
CoreDNS kubernetesttldefault 5 s, max 3600 sDiscovery freshness
libcurlCURLOPT_DNS_CACHE_TIMEOUTdefault 60 s; 0 disables; -1 foreverPHP/Laravel client freshness
Guzzleforce_ip_resolvev4 or v6Avoid a broken address family
GoGODEBUG=netdns=go / cgo (+1 for debug)resolver choicePure Go resolver reads resolv.conf itself
RFC 8767stale TTL / recheck / max stale30 s / 30 s / 1-3 daysServe-stale behaviour
RFC 2308max negative TTL at resolver1-3 hours sensibleNegative cache cap

Error messages you will actually see ​

WhereMessageMeaning
Go netlookup api.example.com on 10.0.0.2:53: no such hostNXDOMAIN (or NODATA for every family); DNSError.IsNotFound is true
Go netlookup api.example.com on 10.0.0.2:53: server misbehavingSERVFAIL or a broken answer from the resolver
Go netdial tcp: lookup api.example.com: i/o timeoutResolver did not answer in time
PHP / LaravelcURL error 6: Could not resolve host: api.example.com (ConnectionException)Resolution failed (often a cached NXDOMAIN)
PHP / LaravelcURL error 28: Connection timed out after 2001 millisecondsAddress resolved but endpoint unreachable (old region, released IP)
digstatus: SERVFAIL with aa missingResolver failed: try +cd to see whether DNSSEC validation is the cause
digstatus: REFUSEDServer is not authoritative for that name and will not recurse
dig;; Truncated, retrying in TCP mode.Answer exceeded UDP size; TCP 53 must be reachable
Route 53 consoleHealth check status "Unhealthy" with "Failure: Resolved IP address ... connection timed out"Checker cannot reach the endpoint from the internet
BrowserDNS_PROBE_FINISHED_NXDOMAIN (Chrome)NXDOMAIN, possibly from a negative cache

Go ​

The Go module (academy/ip-dns-geodns) has one package per idea. It uses github.com/miekg/dns v1 for wire-level DNS because the standard library's net.Resolver returns addresses without TTLs. (The README of that repository announces version 2 at codeberg.org/miekg/dns; v1 keeps receiving fixes.) The dependency raised the module's go directive to 1.25.0.

Before ​

The common first version: resolve once at start-up and pin the address for the life of the process. It works until the first DNS-driven change.

go
// Command before shows the common first version: resolve the dependency's
// hostname once at start-up and keep the address for the life of the process.
// It works on day one. It silently ignores every DNS change afterwards:
// a Route 53 failover, a weighted canary shift or an ELB address change is
// invisible until the process restarts.
package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"time"
)

func main() {
	host := os.Getenv("INVENTORY_HOST") // e.g. inventory.example.com
	if host == "" {
		log.Println("set INVENTORY_HOST to run; exiting")
		return
	}

	// Resolved exactly once. No TTL is visible through the net package,
	// so the program has no idea how long this answer was meant to live.
	addrs, err := net.DefaultResolver.LookupHost(context.Background(), host)
	if err != nil {
		log.Fatal(err)
	}
	pinned := addrs[0]

	client := &http.Client{
		Timeout: 5 * time.Second,
		Transport: &http.Transport{
			// Every connection goes to the address seen at boot.
			DialContext: func(ctx context.Context, network, _ string) (net.Conn, error) {
				var d net.Dialer
				return d.DialContext(ctx, network, net.JoinHostPort(pinned, "443"))
			},
		},
	}

	for range time.Tick(10 * time.Second) {
		resp, err := client.Get("https://" + host + "/health")
		if err != nil {
			// After a regional failover this logs forever; DNS already
			// points elsewhere, but we never ask again.
			log.Println("inventory unreachable:", err)
			continue
		}
		fmt.Println(resp.Status)
		resp.Body.Close()
	}
}

After ​

A TTL-aware cache that honours the authoritative TTL, clamps it (min/max, like public resolvers), caches negative answers with a cap (RFC 2308), serves stale data for up to MaxStale when the upstream fails and rechecks at most every 30 s (RFC 8767), and collapses concurrent misses for one name into a single upstream query:

go
// Package ttlcache is a TTL-aware DNS answer cache of the kind a stub or
// sidecar resolver keeps: it honours the TTL from the authoritative answer,
// clamps it like public resolvers do, caches negative answers (RFC 2308),
// serves stale data when the upstream fails (RFC 8767), and collapses
// concurrent misses for the same name into one upstream query.
package ttlcache

import (
	"context"
	"errors"
	"net/netip"
	"sync"
	"time"
)

// ErrNotFound is returned for NXDOMAIN and NODATA answers, cached or fresh.
var ErrNotFound = errors.New("ttlcache: name does not exist")

// Answer is what one upstream lookup returns.
type Answer struct {
	Addrs []netip.Addr
	// TTL is the smallest TTL of the RRset for positive answers, or
	// min(SOA TTL, SOA MINIMUM) for negative answers (RFC 2308 section 3).
	TTL      time.Duration
	Negative bool
}

// Source performs the real lookup (a recursive resolver, DoH endpoint, ...).
type Source interface {
	Lookup(ctx context.Context, name string) (Answer, error)
}

// Config holds the knobs every resolver exposes in some form.
type Config struct {
	MinTTL         time.Duration // floor for positive answers (0 = honour as-is)
	MaxTTL         time.Duration // cap for positive answers (Google Public DNS caps near 6 h)
	MaxNegativeTTL time.Duration // RFC 2308 section 5: one to three hours is sensible
	StaleTTL       time.Duration // TTL put on stale answers; RFC 8767 recommends 30 s
	MaxStale       time.Duration // how long past expiry stale data may be served (1-3 days)
	Now            func() time.Time
}

// Result is one answer handed to the caller.
type Result struct {
	Addrs     []netip.Addr
	TTL       time.Duration // remaining lifetime the caller may rely on
	FromCache bool
	Stale     bool
}

type entry struct {
	addrs      []netip.Addr
	negative   bool
	expires    time.Time
	retryAfter time.Time // failure recheck timer (RFC 8767 section 5)
}

type call struct {
	done chan struct{}
	res  Result
	err  error
}

// Cache is safe for concurrent use.
type Cache struct {
	src Source
	cfg Config

	mu       sync.Mutex
	entries  map[string]*entry
	inflight map[string]*call
	queries  int // upstream queries issued; exported through Queries for tests and metrics
}

// New returns a cache in front of src.
func New(src Source, cfg Config) *Cache {
	if cfg.Now == nil {
		cfg.Now = time.Now
	}
	if cfg.StaleTTL == 0 {
		cfg.StaleTTL = 30 * time.Second
	}
	return &Cache{src: src, cfg: cfg, entries: map[string]*entry{}, inflight: map[string]*call{}}
}

// Queries reports how many upstream lookups have been sent.
func (c *Cache) Queries() int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.queries
}

// Lookup returns cached data while it is fresh and asks the source otherwise.
func (c *Cache) Lookup(ctx context.Context, name string) (Result, error) {
	now := c.cfg.Now()

	c.mu.Lock()
	if e, ok := c.entries[name]; ok {
		if now.Before(e.expires) {
			c.mu.Unlock()
			return e.result(now), e.err()
		}
		// Expired, but the upstream failed recently: do not hammer it.
		if now.Before(e.retryAfter) && c.staleUsable(e, now) {
			c.mu.Unlock()
			return c.staleResult(e), nil
		}
	}
	if cl, ok := c.inflight[name]; ok { // someone is already asking
		c.mu.Unlock()
		select {
		case <-cl.done:
			return cl.res, cl.err
		case <-ctx.Done():
			return Result{}, ctx.Err()
		}
	}
	cl := &call{done: make(chan struct{})}
	c.inflight[name] = cl
	c.queries++
	c.mu.Unlock()

	ans, err := c.src.Lookup(ctx, name)

	c.mu.Lock()
	cl.res, cl.err = c.store(name, ans, err, c.cfg.Now())
	delete(c.inflight, name)
	c.mu.Unlock()
	close(cl.done)
	return cl.res, cl.err
}

// store must be called with c.mu held.
func (c *Cache) store(name string, ans Answer, err error, now time.Time) (Result, error) {
	if err != nil {
		if e, ok := c.entries[name]; ok && c.staleUsable(e, now) {
			e.retryAfter = now.Add(c.cfg.StaleTTL)
			return c.staleResult(e), nil
		}
		return Result{}, err
	}
	ttl := ans.TTL
	if ans.Negative {
		if c.cfg.MaxNegativeTTL > 0 && ttl > c.cfg.MaxNegativeTTL {
			ttl = c.cfg.MaxNegativeTTL
		}
	} else {
		if ttl < c.cfg.MinTTL {
			ttl = c.cfg.MinTTL
		}
		if c.cfg.MaxTTL > 0 && ttl > c.cfg.MaxTTL {
			ttl = c.cfg.MaxTTL
		}
	}
	e := &entry{addrs: ans.Addrs, negative: ans.Negative, expires: now.Add(ttl)}
	c.entries[name] = e
	res := e.result(now)
	res.FromCache = false
	return res, e.err()
}

func (c *Cache) staleUsable(e *entry, now time.Time) bool {
	return !e.negative && c.cfg.MaxStale > 0 && now.Before(e.expires.Add(c.cfg.MaxStale))
}

func (c *Cache) staleResult(e *entry) Result {
	return Result{Addrs: e.addrs, TTL: c.cfg.StaleTTL, FromCache: true, Stale: true}
}

func (e *entry) result(now time.Time) Result {
	return Result{Addrs: e.addrs, TTL: e.expires.Sub(now), FromCache: true}
}

func (e *entry) err() error {
	if e.negative {
		return ErrNotFound
	}
	return nil
}
go
package ttlcache

import (
	"context"
	"errors"
	"net/netip"
	"sync"
	"testing"
	"time"
)

type fakeClock struct{ t time.Time }

func (f *fakeClock) Now() time.Time          { return f.t }
func (f *fakeClock) Advance(d time.Duration) { f.t = f.t.Add(d) }

type fakeSource struct {
	mu    sync.Mutex
	ans   Answer
	err   error
	calls int
	gate  chan struct{} // when set, Lookup blocks until it is closed
}

func (f *fakeSource) Lookup(ctx context.Context, name string) (Answer, error) {
	f.mu.Lock()
	f.calls++
	gate, ans, err := f.gate, f.ans, f.err
	f.mu.Unlock()
	if gate != nil {
		<-gate
	}
	return ans, err
}

var eu = netip.MustParseAddr("192.0.2.10")

func newCache(src Source, clk *fakeClock) *Cache {
	return New(src, Config{
		MinTTL:         5 * time.Second,
		MaxTTL:         6 * time.Hour,
		MaxNegativeTTL: time.Hour,
		StaleTTL:       30 * time.Second,
		MaxStale:       24 * time.Hour,
		Now:            clk.Now,
	})
}

func TestHonoursTTL(t *testing.T) {
	clk := &fakeClock{t: time.Unix(0, 0)}
	src := &fakeSource{ans: Answer{Addrs: []netip.Addr{eu}, TTL: 60 * time.Second}}
	c := newCache(src, clk)
	ctx := context.Background()

	if _, err := c.Lookup(ctx, "api.example.com"); err != nil {
		t.Fatal(err)
	}
	clk.Advance(59 * time.Second)
	r, _ := c.Lookup(ctx, "api.example.com")
	if !r.FromCache || r.TTL != time.Second {
		t.Fatalf("want cached answer with 1s left, got %+v", r)
	}
	clk.Advance(2 * time.Second)
	c.Lookup(ctx, "api.example.com")
	if src.calls != 2 {
		t.Fatalf("want a second upstream query after expiry, got %d", src.calls)
	}
}

func TestClampsTTL(t *testing.T) {
	clk := &fakeClock{t: time.Unix(0, 0)}
	src := &fakeSource{ans: Answer{Addrs: []netip.Addr{eu}, TTL: 0}}
	c := newCache(src, clk)
	r, _ := c.Lookup(context.Background(), "zero.example.com")
	if r.TTL != 5*time.Second {
		t.Fatalf("TTL 0 should be raised to MinTTL, got %v", r.TTL)
	}
	src.ans.TTL = 7 * 24 * time.Hour
	r, _ = c.Lookup(context.Background(), "week.example.com")
	if r.TTL != 6*time.Hour {
		t.Fatalf("one-week TTL should be capped at 6h, got %v", r.TTL)
	}
}

func TestNegativeCaching(t *testing.T) {
	clk := &fakeClock{t: time.Unix(0, 0)}
	// SOA TTL 900, MINIMUM 86400: RFC 2308 says use the smaller, 900 s.
	src := &fakeSource{ans: Answer{Negative: true, TTL: 900 * time.Second}}
	c := newCache(src, clk)
	ctx := context.Background()
	for i := 0; i < 3; i++ {
		if _, err := c.Lookup(ctx, "new.example.com"); !errors.Is(err, ErrNotFound) {
			t.Fatalf("want ErrNotFound, got %v", err)
		}
		clk.Advance(5 * time.Minute)
	}
	if src.calls != 1 {
		t.Fatalf("NXDOMAIN should be cached for 900 s, upstream saw %d queries", src.calls)
	}
	// The record is created now, but the cache still says it does not exist.
	src.ans = Answer{Addrs: []netip.Addr{eu}, TTL: 60 * time.Second}
	if _, err := c.Lookup(ctx, "new.example.com"); err != nil {
		t.Fatalf("after 15 min the negative entry expired; want fresh answer, got %v", err)
	}
}

func TestServeStaleWhenUpstreamFails(t *testing.T) {
	clk := &fakeClock{t: time.Unix(0, 0)}
	src := &fakeSource{ans: Answer{Addrs: []netip.Addr{eu}, TTL: 60 * time.Second}}
	c := newCache(src, clk)
	ctx := context.Background()
	c.Lookup(ctx, "api.example.com")

	src.err = errors.New("SERVFAIL")
	clk.Advance(2 * time.Minute)
	r, err := c.Lookup(ctx, "api.example.com")
	if err != nil || !r.Stale || r.TTL != 30*time.Second {
		t.Fatalf("want stale answer with 30s TTL, got %+v %v", r, err)
	}
	// Within the failure recheck window no new upstream query is sent.
	clk.Advance(10 * time.Second)
	c.Lookup(ctx, "api.example.com")
	if src.calls != 2 {
		t.Fatalf("want 2 upstream queries (initial + one failed refresh), got %d", src.calls)
	}
	// Past MaxStale the error surfaces.
	clk.Advance(25 * time.Hour)
	if _, err := c.Lookup(ctx, "api.example.com"); err == nil {
		t.Fatal("want error after MaxStale")
	}
}

func TestCollapsesConcurrentMisses(t *testing.T) {
	clk := &fakeClock{t: time.Unix(0, 0)}
	gate := make(chan struct{})
	src := &fakeSource{ans: Answer{Addrs: []netip.Addr{eu}, TTL: time.Minute}, gate: gate}
	c := newCache(src, clk)

	var wg sync.WaitGroup
	for i := 0; i < 50; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			c.Lookup(context.Background(), "hot.example.com")
		}()
	}
	for c.Queries() == 0 {
		time.Sleep(time.Millisecond)
	}
	time.Sleep(20 * time.Millisecond) // let the other goroutines join the in-flight call
	close(gate)
	wg.Wait()
	if c.Queries() != 1 {
		t.Fatalf("50 concurrent misses should cost 1 upstream query, got %d", c.Queries())
	}
}

A source that reads TTLs from the wire. It queries A and AAAA with EDNS(0) at 1232 bytes, retries over TCP on TC, takes the shortest TTL along a CNAME chain, treats SERVFAIL as a failure to refresh (so the cache can serve stale), and derives the negative TTL as min(SOA TTL, SOA MINIMUM). The test runs an in-process authoritative server on a random localhost port:

go
// Package dnssource implements ttlcache.Source with github.com/miekg/dns,
// because the standard library's net.Resolver returns addresses without
// their TTLs. It sends A and AAAA queries to one recursive resolver and
// derives the TTL of the answer the way RFC 1034 and RFC 2308 define it.
package dnssource

import (
	"context"
	"fmt"
	"net/netip"
	"time"

	"github.com/miekg/dns"

	"academy/ip-dns-geodns/ttlcache"
)

// Source queries Server (host:port of a recursive resolver).
type Source struct {
	Server string
	Client *dns.Client // nil means UDP with a 2 s timeout
}

// Lookup implements ttlcache.Source.
func (s *Source) Lookup(ctx context.Context, name string) (ttlcache.Answer, error) {
	var out ttlcache.Answer
	var minTTL uint32 = 1<<31 - 1
	negatives := 0
	for _, qtype := range []uint16{dns.TypeA, dns.TypeAAAA} {
		msg, err := s.exchange(ctx, name, qtype)
		if err != nil {
			return ttlcache.Answer{}, err
		}
		switch msg.Rcode {
		case dns.RcodeSuccess:
		case dns.RcodeNameError: // NXDOMAIN
			return negative(msg), nil
		default: // SERVFAIL, REFUSED...: a failure to refresh, not an answer
			return ttlcache.Answer{}, fmt.Errorf("dnssource: %s %s: %s",
				name, dns.TypeToString[qtype], dns.RcodeToString[msg.Rcode])
		}
		found := false
		for _, rr := range msg.Answer {
			// A CNAME chain lives only as long as its shortest link.
			minTTL = min(minTTL, rr.Header().Ttl)
			switch v := rr.(type) {
			case *dns.A:
				out.Addrs = append(out.Addrs, netip.AddrFrom4([4]byte(v.A.To4())))
				found = true
			case *dns.AAAA:
				out.Addrs = append(out.Addrs, netip.AddrFrom16([16]byte(v.AAAA.To16())))
				found = true
			}
		}
		if !found { // NODATA for this type
			negatives++
			if n := negative(msg); negatives == 2 {
				return n, nil
			}
		}
	}
	out.TTL = time.Duration(minTTL) * time.Second
	return out, nil
}

func (s *Source) exchange(ctx context.Context, name string, qtype uint16) (*dns.Msg, error) {
	c := s.Client
	if c == nil {
		c = &dns.Client{Net: "udp", Timeout: 2 * time.Second}
	}
	m := new(dns.Msg)
	m.SetQuestion(dns.Fqdn(name), qtype)
	m.SetEdns0(1232, false) // 1232-byte UDP payload avoids IP fragmentation
	r, _, err := c.ExchangeContext(ctx, m, s.Server)
	if err != nil {
		return nil, err
	}
	if r.Truncated { // TC bit: the answer did not fit, repeat over TCP
		tcp := *c
		tcp.Net = "tcp"
		r, _, err = tcp.ExchangeContext(ctx, m, s.Server)
	}
	return r, err
}

// negative applies RFC 2308 section 3: the negative TTL is the smaller of
// the SOA record's own TTL and its MINIMUM field.
func negative(msg *dns.Msg) ttlcache.Answer {
	for _, rr := range msg.Ns {
		if soa, ok := rr.(*dns.SOA); ok {
			ttl := min(soa.Hdr.Ttl, soa.Minttl)
			return ttlcache.Answer{Negative: true, TTL: time.Duration(ttl) * time.Second}
		}
	}
	// No SOA: the answer must not be cached (RFC 2308 section 5).
	return ttlcache.Answer{Negative: true}
}
go
package dnssource

import (
	"context"
	"net"
	"testing"
	"time"

	"github.com/miekg/dns"
)

// startZone runs an in-process authoritative server for example.com on a
// random localhost UDP port, so the test needs no network.
func startZone(t *testing.T) string {
	t.Helper()
	zone := map[string][]string{
		"www.example.com.":  {"www.example.com. 300 IN CNAME edge.example.com."},
		"edge.example.com.": {"edge.example.com. 60 IN A 192.0.2.10", "edge.example.com. 60 IN AAAA 2001:db8::10"},
		"v4.example.com.":   {"v4.example.com. 120 IN A 198.51.100.7"},
	}
	soa, _ := dns.NewRR("example.com. 900 IN SOA ns1.example.com. hostmaster.example.com. 1 7200 900 1209600 86400")

	mux := dns.NewServeMux()
	mux.HandleFunc("example.com.", func(w dns.ResponseWriter, req *dns.Msg) {
		m := new(dns.Msg)
		m.SetReply(req)
		m.Authoritative = true
		q := req.Question[0]
		name := q.Name
		rrs, ok := zone[name]
		if !ok {
			m.Rcode = dns.RcodeNameError
			m.Ns = []dns.RR{soa}
			w.WriteMsg(m)
			return
		}
		for len(rrs) > 0 { // follow CNAMEs inside the zone, like a real server
			next := ""
			for _, s := range rrs {
				rr, _ := dns.NewRR(s)
				if c, isC := rr.(*dns.CNAME); isC {
					m.Answer = append(m.Answer, rr)
					next = c.Target
				} else if rr.Header().Rrtype == q.Qtype {
					m.Answer = append(m.Answer, rr)
				}
			}
			if next == "" {
				break
			}
			rrs = zone[next]
		}
		if len(m.Answer) == 0 || m.Answer[len(m.Answer)-1].Header().Rrtype == dns.TypeCNAME {
			m.Ns = []dns.RR{soa}
		}
		w.WriteMsg(m)
	})

	pc, err := net.ListenPacket("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	srv := &dns.Server{PacketConn: pc, Handler: mux}
	go srv.ActivateAndServe()
	t.Cleanup(func() { srv.Shutdown() })
	return pc.LocalAddr().String()
}

func TestCNAMEChainUsesShortestTTL(t *testing.T) {
	s := &Source{Server: startZone(t)}
	ans, err := s.Lookup(context.Background(), "www.example.com")
	if err != nil {
		t.Fatal(err)
	}
	if len(ans.Addrs) != 2 || ans.TTL != 60*time.Second {
		t.Fatalf("want A+AAAA with TTL 60s (CNAME 300, A 60), got %v %v", ans.Addrs, ans.TTL)
	}
}

func TestNXDOMAINUsesSOAMinimum(t *testing.T) {
	s := &Source{Server: startZone(t)}
	ans, err := s.Lookup(context.Background(), "missing.example.com")
	if err != nil {
		t.Fatal(err)
	}
	if !ans.Negative || ans.TTL != 900*time.Second {
		t.Fatalf("want negative answer for min(900, 86400)=900s, got %+v", ans)
	}
}

func TestOneFamilyOnlyIsStillPositive(t *testing.T) {
	s := &Source{Server: startZone(t)}
	ans, err := s.Lookup(context.Background(), "v4.example.com")
	if err != nil {
		t.Fatal(err)
	}
	if ans.Negative || len(ans.Addrs) != 1 || ans.TTL != 120*time.Second {
		t.Fatalf("want one A record with TTL 120s, got %+v", ans)
	}
}

Health-checked endpoint selection: failure and success thresholds, weighted choice among healthy primaries, failover to secondaries, fail-open when all are down, multivalue answers capped at eight, and concurrent probes with a per-probe timeout:

go
// Package failover is the decision logic that DNS traffic managers such as
// Amazon Route 53, Cloudflare Load Balancing and NS1 run behind a name:
// health-checked endpoints, a failure threshold before an endpoint is
// declared unhealthy, weighted selection among healthy primaries,
// active-passive failover to secondaries, and "fail open" when everything
// looks down. Use it in a client-side resolver, a GeoDNS server
// (see package geodns) or a control loop that edits records.
package failover

import (
	"context"
	"math/rand/v2"
	"sync"
	"time"
)

// Role decides active-passive behaviour.
type Role int

const (
	Primary Role = iota
	Secondary
)

// Endpoint is one answer the name can return.
type Endpoint struct {
	Name   string // e.g. "eu-west-1"
	Addr   string // e.g. "192.0.2.10"
	Role   Role
	Weight int // relative share; 0 means "never chosen while others are healthy"
}

// Checker probes one endpoint. A nil error means healthy.
type Checker func(ctx context.Context, e Endpoint) error

// Decision explains why Pick returned what it returned (log it).
type Decision string

const (
	HealthyPrimary   Decision = "healthy-primary"
	FailedOver       Decision = "failed-over-to-secondary"
	FailOpen         Decision = "fail-open-all-unhealthy"
	NoEndpointsFound Decision = "no-endpoints"
)

type state struct {
	Endpoint
	healthy bool
	fails   int // consecutive failures
	oks     int // consecutive successes
}

// Pool is safe for concurrent use.
type Pool struct {
	mu               sync.Mutex
	eps              []*state
	failureThreshold int // Route 53 default: 3
	successThreshold int
	intn             func(n int) int
}

// New builds a pool. Every endpoint starts healthy, so a fresh deploy does
// not fail over before the first round of checks.
func New(eps []Endpoint, failureThreshold, successThreshold int) *Pool {
	p := &Pool{failureThreshold: failureThreshold, successThreshold: successThreshold, intn: rand.IntN}
	for _, e := range eps {
		p.eps = append(p.eps, &state{Endpoint: e, healthy: true})
	}
	return p
}

// Report records one probe result and applies the thresholds.
func (p *Pool) Report(name string, err error) {
	p.mu.Lock()
	defer p.mu.Unlock()
	for _, s := range p.eps {
		if s.Name != name {
			continue
		}
		if err != nil {
			s.fails++
			s.oks = 0
			if s.fails >= p.failureThreshold {
				s.healthy = false
			}
		} else {
			s.oks++
			s.fails = 0
			if s.oks >= p.successThreshold {
				s.healthy = true
			}
		}
	}
}

// CheckAll probes every endpoint concurrently, each with its own timeout.
func (p *Pool) CheckAll(ctx context.Context, check Checker, timeout time.Duration) {
	p.mu.Lock()
	eps := make([]Endpoint, len(p.eps))
	for i, s := range p.eps {
		eps[i] = s.Endpoint
	}
	p.mu.Unlock()

	var wg sync.WaitGroup
	for _, e := range eps {
		wg.Add(1)
		go func() {
			defer wg.Done()
			cctx, cancel := context.WithTimeout(ctx, timeout)
			defer cancel()
			p.Report(e.Name, check(cctx, e))
		}()
	}
	wg.Wait()
}

// Healthy reports the current view of one endpoint.
func (p *Pool) Healthy(name string) bool {
	p.mu.Lock()
	defer p.mu.Unlock()
	for _, s := range p.eps {
		if s.Name == name {
			return s.healthy
		}
	}
	return false
}

// Pick returns one endpoint: weighted among healthy primaries, else among
// healthy secondaries, else among all primaries (fail open, because an
// empty answer is a guaranteed outage while a wrong "unhealthy" verdict,
// for example a broken health checker, is not).
func (p *Pool) Pick() (Endpoint, Decision) {
	p.mu.Lock()
	defer p.mu.Unlock()
	if e, ok := p.weighted(func(s *state) bool { return s.healthy && s.Role == Primary }); ok {
		return e, HealthyPrimary
	}
	if e, ok := p.weighted(func(s *state) bool { return s.healthy && s.Role == Secondary }); ok {
		return e, FailedOver
	}
	if e, ok := p.weighted(func(s *state) bool { return s.Role == Primary }); ok {
		return e, FailOpen
	}
	return Endpoint{}, NoEndpointsFound
}

// Multivalue returns up to max healthy endpoints, like Route 53 multivalue
// answer routing (max 8). When none is healthy it returns up to max of all.
func (p *Pool) Multivalue(max int) []Endpoint {
	p.mu.Lock()
	defer p.mu.Unlock()
	var healthy, all []Endpoint
	for _, s := range p.eps {
		all = append(all, s.Endpoint)
		if s.healthy {
			healthy = append(healthy, s.Endpoint)
		}
	}
	out := healthy
	if len(out) == 0 {
		out = all
	}
	rand.Shuffle(len(out), func(i, j int) { out[i], out[j] = out[j], out[i] })
	if len(out) > max {
		out = out[:max]
	}
	return out
}

// weighted must be called with p.mu held.
func (p *Pool) weighted(keep func(*state) bool) (Endpoint, bool) {
	total := 0
	var cands []*state
	for _, s := range p.eps {
		if keep(s) {
			cands = append(cands, s)
			total += s.Weight
		}
	}
	if len(cands) == 0 {
		return Endpoint{}, false
	}
	if total == 0 { // only zero-weight records left: Route 53 then considers them
		return cands[p.intn(len(cands))].Endpoint, true
	}
	n := p.intn(total)
	for _, s := range cands {
		if n < s.Weight {
			return s.Endpoint, true
		}
		n -= s.Weight
	}
	return cands[len(cands)-1].Endpoint, true
}
go
package failover

import (
	"context"
	"errors"
	"testing"
	"time"
)

var down = errors.New("connect: connection refused")

func regions() []Endpoint {
	return []Endpoint{
		{Name: "eu-west-1", Addr: "192.0.2.10", Role: Primary, Weight: 90},
		{Name: "eu-central-1", Addr: "192.0.2.20", Role: Primary, Weight: 10},
		{Name: "us-east-1", Addr: "198.51.100.10", Role: Secondary, Weight: 1},
	}
}

func TestFailureThreshold(t *testing.T) {
	p := New(regions(), 3, 2)
	p.Report("eu-west-1", down)
	p.Report("eu-west-1", down)
	if !p.Healthy("eu-west-1") {
		t.Fatal("two failures must not flip the endpoint (threshold 3)")
	}
	p.Report("eu-west-1", down)
	if p.Healthy("eu-west-1") {
		t.Fatal("third consecutive failure must mark it unhealthy")
	}
	p.Report("eu-west-1", nil)
	if p.Healthy("eu-west-1") {
		t.Fatal("one success must not restore it (success threshold 2)")
	}
	p.Report("eu-west-1", nil)
	if !p.Healthy("eu-west-1") {
		t.Fatal("two consecutive successes restore it")
	}
}

func TestWeightedSplit(t *testing.T) {
	p := New(regions(), 3, 2)
	n := 0
	p.intn = func(int) int { n = (n + 1) % 100; return n } // deterministic sweep
	counts := map[string]int{}
	for i := 0; i < 100; i++ {
		e, d := p.Pick()
		if d != HealthyPrimary {
			t.Fatalf("unexpected decision %s", d)
		}
		counts[e.Name]++
	}
	if counts["eu-west-1"] != 90 || counts["eu-central-1"] != 10 {
		t.Fatalf("want a 90/10 split, got %v", counts)
	}
}

func TestFailoverThenFailOpen(t *testing.T) {
	p := New(regions(), 1, 1)
	p.Report("eu-west-1", down)
	p.Report("eu-central-1", down)
	e, d := p.Pick()
	if d != FailedOver || e.Name != "us-east-1" {
		t.Fatalf("want secondary us-east-1, got %s %s", e.Name, d)
	}
	p.Report("us-east-1", down)
	e, d = p.Pick()
	if d != FailOpen || e.Role != Primary {
		t.Fatalf("all down: want fail-open to a primary, got %s %s", e.Name, d)
	}
}

func TestMultivalueLimit(t *testing.T) {
	var eps []Endpoint
	for i := 0; i < 12; i++ {
		eps = append(eps, Endpoint{Name: string(rune('a' + i)), Weight: 1})
	}
	p := New(eps, 1, 1)
	if got := len(p.Multivalue(8)); got != 8 {
		t.Fatalf("want 8 answers, got %d", got)
	}
	for _, e := range eps {
		p.Report(e.Name, down)
	}
	if got := len(p.Multivalue(8)); got != 8 {
		t.Fatalf("all unhealthy: want up to 8 answers anyway, got %d", got)
	}
}

func TestCheckAllUsesTimeout(t *testing.T) {
	p := New(regions(), 1, 1)
	slow := func(ctx context.Context, e Endpoint) error {
		if e.Name != "eu-west-1" {
			return nil
		}
		<-ctx.Done() // a hung endpoint counts as a failure, not a hang
		return ctx.Err()
	}
	start := time.Now()
	p.CheckAll(context.Background(), slow, 50*time.Millisecond)
	if time.Since(start) > time.Second {
		t.Fatal("CheckAll must not wait for a hung endpoint")
	}
	if p.Healthy("eu-west-1") || !p.Healthy("eu-central-1") {
		t.Fatal("only the hung endpoint should be unhealthy")
	}
}

A GeoDNS authoritative server: ECS-aware region selection with SCOPE PREFIX-LENGTH, health-aware fallback, NXDOMAIN and NODATA with SOA, and REFUSED for zones it does not serve (so it can never be used as an open resolver):

go
// Package geodns is a minimal authoritative GeoDNS server built on
// github.com/miekg/dns. It answers one name with the address of the region
// that serves the client's network, using EDNS Client Subnet (RFC 7871) when
// the recursive resolver sends it and the resolver's own address otherwise,
// and it skips regions whose health check is failing. Products such as
// Amazon Route 53 (geolocation, latency, IP-based routing), Cloudflare Load
// Balancing (geo/proximity steering) and NS1 do the same at global scale.
package geodns

import (
	"net"
	"net/netip"
	"strings"

	"github.com/miekg/dns"
)

// Rule maps a client network to a region (IP-based routing). Real GeoDNS
// uses a geolocation database; a prefix table keeps the example testable.
type Rule struct {
	Prefix netip.Prefix
	Region string
}

// Region is one deployment the name can point at.
type Region struct {
	A, AAAA  []netip.Addr
	Fallback []string // regions to try, in order, when this one is unhealthy
}

// Server answers queries for Name inside Zone.
type Server struct {
	Zone, Name    string // both fully qualified, e.g. "example.com.", "api.example.com."
	TTL           uint32 // short (30-60 s) so failover reaches clients quickly
	Rules         []Rule
	DefaultRegion string
	Regions       map[string]Region
	Healthy       func(region string) bool // nil means always healthy
	SOA           *dns.SOA
}

// ServeDNS implements dns.Handler.
func (s *Server) ServeDNS(w dns.ResponseWriter, req *dns.Msg) {
	m := new(dns.Msg)
	m.SetReply(req)
	m.Authoritative = true
	if len(req.Question) != 1 {
		m.Rcode = dns.RcodeFormatError
		w.WriteMsg(m)
		return
	}
	q := req.Question[0]
	name := strings.ToLower(q.Name)

	client, ecs := clientAddr(w, req)
	region, scope := s.route(client)

	switch {
	case name == s.Name:
		r := s.Regions[s.healthyRegion(region)]
		hdr := dns.RR_Header{Name: q.Name, Class: dns.ClassINET, Ttl: s.TTL}
		switch q.Qtype {
		case dns.TypeA:
			for _, a := range r.A {
				hdr.Rrtype = dns.TypeA
				m.Answer = append(m.Answer, &dns.A{Hdr: hdr, A: net.IP(a.AsSlice())})
			}
		case dns.TypeAAAA:
			for _, a := range r.AAAA {
				hdr.Rrtype = dns.TypeAAAA
				m.Answer = append(m.Answer, &dns.AAAA{Hdr: hdr, AAAA: net.IP(a.AsSlice())})
			}
		}
		if len(m.Answer) == 0 { // NODATA: SOA lets resolvers cache the absence
			m.Ns = []dns.RR{s.SOA}
		}
	case name == s.Zone: // the apex exists: SOA, or NODATA for other types
		if q.Qtype == dns.TypeSOA {
			m.Answer = []dns.RR{s.SOA}
		} else {
			m.Ns = []dns.RR{s.SOA}
		}
	case dns.IsSubDomain(s.Zone, name):
		m.Rcode = dns.RcodeNameError // NXDOMAIN, cached for min(SOA TTL, MINIMUM)
		m.Ns = []dns.RR{s.SOA}
	default:
		m.Rcode = dns.RcodeRefused // not our zone: never act as an open resolver
	}

	if ecs != nil {
		// Tell the resolver how widely it may reuse this answer (RFC 7871 7.2.1).
		ecs.SourceScope = min(scope, ecs.SourceNetmask)
		opt := new(dns.OPT)
		opt.Hdr.Name = "."
		opt.Hdr.Rrtype = dns.TypeOPT
		opt.SetUDPSize(1232)
		opt.Option = append(opt.Option, ecs)
		m.Extra = append(m.Extra, opt)
	}
	w.WriteMsg(m)
}

// route returns the region for a client and the prefix length that decided it.
func (s *Server) route(client netip.Addr) (string, uint8) {
	best, bits := s.DefaultRegion, -1
	for _, r := range s.Rules {
		if r.Prefix.Contains(client) && r.Prefix.Bits() > bits {
			best, bits = r.Region, r.Prefix.Bits()
		}
	}
	if bits < 0 {
		return best, 0
	}
	return best, uint8(bits)
}

func (s *Server) healthyRegion(region string) string {
	if s.Healthy == nil || s.Healthy(region) {
		return region
	}
	for _, fb := range s.Regions[region].Fallback {
		if s.Healthy(fb) {
			return fb
		}
	}
	return region // everything is down: fail open rather than answer nothing
}

// clientAddr prefers the ECS address; it falls back to the resolver's IP.
func clientAddr(w dns.ResponseWriter, req *dns.Msg) (netip.Addr, *dns.EDNS0_SUBNET) {
	if opt := req.IsEdns0(); opt != nil {
		for _, o := range opt.Option {
			if e, ok := o.(*dns.EDNS0_SUBNET); ok {
				if a, ok := netip.AddrFromSlice(e.Address); ok {
					return a.Unmap(), e
				}
			}
		}
	}
	if ap, err := netip.ParseAddrPort(w.RemoteAddr().String()); err == nil {
		return ap.Addr().Unmap(), nil
	}
	return netip.Addr{}, nil
}
go
package geodns

import (
	"net"
	"net/netip"
	"testing"

	"github.com/miekg/dns"
)

func newServer(healthy map[string]bool) *Server {
	soa, _ := dns.NewRR("example.com. 900 IN SOA ns1.example.com. hostmaster.example.com. 1 7200 900 1209600 86400")
	return &Server{
		Zone: "example.com.", Name: "api.example.com.", TTL: 60,
		Rules: []Rule{
			{Prefix: netip.MustParsePrefix("198.51.100.0/24"), Region: "eu"},
			{Prefix: netip.MustParsePrefix("203.0.113.0/24"), Region: "us"},
		},
		DefaultRegion: "us",
		Regions: map[string]Region{
			"eu": {A: []netip.Addr{netip.MustParseAddr("192.0.2.10")}, AAAA: []netip.Addr{netip.MustParseAddr("2001:db8:e::10")}, Fallback: []string{"us"}},
			"us": {A: []netip.Addr{netip.MustParseAddr("192.0.2.20")}, Fallback: []string{"eu"}},
		},
		Healthy: func(r string) bool { h, ok := healthy[r]; return !ok || h },
		SOA:     soa.(*dns.SOA),
	}
}

func start(t *testing.T, s *Server) string {
	t.Helper()
	pc, err := net.ListenPacket("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	srv := &dns.Server{PacketConn: pc, Handler: s}
	go srv.ActivateAndServe()
	t.Cleanup(func() { srv.Shutdown() })
	return pc.LocalAddr().String()
}

// query sends name/qtype, optionally with an ECS option for subnet.
func query(t *testing.T, addr, name string, qtype uint16, subnet string) *dns.Msg {
	t.Helper()
	m := new(dns.Msg)
	m.SetQuestion(name, qtype)
	m.SetEdns0(1232, false)
	if subnet != "" {
		p := netip.MustParsePrefix(subnet)
		e := &dns.EDNS0_SUBNET{Code: dns.EDNS0SUBNET, Family: 1, SourceNetmask: uint8(p.Bits()), Address: net.IP(p.Addr().AsSlice())}
		m.IsEdns0().Option = append(m.IsEdns0().Option, e)
	}
	r, _, err := new(dns.Client).Exchange(m, addr)
	if err != nil {
		t.Fatal(err)
	}
	return r
}

func firstA(t *testing.T, r *dns.Msg) string {
	t.Helper()
	if len(r.Answer) == 0 {
		t.Fatalf("no answer: %v", r)
	}
	return r.Answer[0].(*dns.A).A.String()
}

func TestECSSelectsRegion(t *testing.T) {
	addr := start(t, newServer(nil))
	r := query(t, addr, "api.example.com.", dns.TypeA, "198.51.100.0/24")
	if got := firstA(t, r); got != "192.0.2.10" {
		t.Fatalf("EU client should get the EU address, got %s", got)
	}
	ecs := r.IsEdns0().Option[0].(*dns.EDNS0_SUBNET)
	if ecs.SourceScope != 24 {
		t.Fatalf("scope prefix should be 24, got %d", ecs.SourceScope)
	}
	if r.Answer[0].Header().Ttl != 60 {
		t.Fatalf("want TTL 60, got %d", r.Answer[0].Header().Ttl)
	}
}

func TestWithoutECSUsesResolverAddress(t *testing.T) {
	addr := start(t, newServer(nil))
	// The query comes from 127.0.0.1, which matches no rule: default region.
	if got := firstA(t, query(t, addr, "api.example.com.", dns.TypeA, "")); got != "192.0.2.20" {
		t.Fatalf("want default region (us), got %s", got)
	}
}

func TestUnhealthyRegionFallsBack(t *testing.T) {
	addr := start(t, newServer(map[string]bool{"eu": false}))
	if got := firstA(t, query(t, addr, "api.example.com.", dns.TypeA, "198.51.100.0/24")); got != "192.0.2.20" {
		t.Fatalf("EU down: EU client should get US, got %s", got)
	}
}

func TestAllDownFailsOpen(t *testing.T) {
	addr := start(t, newServer(map[string]bool{"eu": false, "us": false}))
	if got := firstA(t, query(t, addr, "api.example.com.", dns.TypeA, "198.51.100.0/24")); got != "192.0.2.10" {
		t.Fatalf("all down: answer the home region anyway, got %s", got)
	}
}

func TestNXDOMAINAndNODATACarrySOA(t *testing.T) {
	addr := start(t, newServer(nil))
	r := query(t, addr, "old.example.com.", dns.TypeA, "")
	if r.Rcode != dns.RcodeNameError || len(r.Ns) != 1 {
		t.Fatalf("want NXDOMAIN with SOA, got rcode=%d ns=%d", r.Rcode, len(r.Ns))
	}
	// US has no IPv6 address: AAAA is NODATA (NOERROR, empty answer, SOA).
	r = query(t, addr, "api.example.com.", dns.TypeAAAA, "203.0.113.0/24")
	if r.Rcode != dns.RcodeSuccess || len(r.Answer) != 0 || len(r.Ns) != 1 {
		t.Fatalf("want NODATA, got %v", r)
	}
}

func TestRefusesOtherZones(t *testing.T) {
	addr := start(t, newServer(nil))
	if r := query(t, addr, "victim.example.net.", dns.TypeA, ""); r.Rcode != dns.RcodeRefused {
		t.Fatalf("want REFUSED for a zone we do not serve, got %d", r.Rcode)
	}
}
go
// Command geodns runs the example GeoDNS server on 127.0.0.1:5354 (UDP) and
// a tiny admin endpoint on 127.0.0.1:8054 to flip region health:
//
//	curl -s '127.0.0.1:8054/health?region=eu&up=false'
package main

import (
	"fmt"
	"log"
	"net/http"
	"net/netip"
	"sync"

	"github.com/miekg/dns"

	"academy/ip-dns-geodns/geodns"
)

func main() {
	var mu sync.Mutex
	health := map[string]bool{"eu": true, "us": true}

	soa, err := dns.NewRR("example.com. 900 IN SOA ns1.example.com. hostmaster.example.com. 1 7200 900 1209600 86400")
	if err != nil {
		log.Fatal(err)
	}
	srv := &geodns.Server{
		Zone: "example.com.", Name: "api.example.com.", TTL: 60,
		Rules: []geodns.Rule{
			{Prefix: netip.MustParsePrefix("198.51.100.0/24"), Region: "eu"},
			{Prefix: netip.MustParsePrefix("203.0.113.0/24"), Region: "us"},
		},
		DefaultRegion: "us",
		Regions: map[string]geodns.Region{
			"eu": {A: []netip.Addr{netip.MustParseAddr("192.0.2.10")}, Fallback: []string{"us"}},
			"us": {A: []netip.Addr{netip.MustParseAddr("192.0.2.20")}, Fallback: []string{"eu"}},
		},
		Healthy: func(r string) bool { mu.Lock(); defer mu.Unlock(); return health[r] },
		SOA:     soa.(*dns.SOA),
	}

	http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
		region, up := r.URL.Query().Get("region"), r.URL.Query().Get("up") == "true"
		mu.Lock()
		health[region] = up
		mu.Unlock()
		fmt.Fprintf(w, "%s healthy=%v\n", region, up)
	})
	go func() { log.Fatal(http.ListenAndServe("127.0.0.1:8054", nil)) }()

	log.Println("GeoDNS for api.example.com on 127.0.0.1:5354/udp")
	log.Fatal((&dns.Server{Addr: "127.0.0.1:5354", Net: "udp", Handler: srv}).ListenAndServe())
}

The Go angle ​

Go featureUse for DNS designNote
net.Resolver (LookupHost, LookupNetIP, LookupSRV, LookupTXT, LookupNS, LookupCNAME)Everyday lookupsNo TTL in results; no cache
net.Resolver.PreferGo, DialForce the pure Go resolver, point it at a specific server (for example a DoT proxy or a test server)Dial replaces the connection to the DNS server
GODEBUG=netdns=go, netdns=cgo, netdns=go+1Choose and debug the resolverOn Unix the pure Go resolver is preferred unless cgo is required
*net.DNSError (IsNotFound, IsTimeout, IsTemporary)Classify failures: NXDOMAIN vs timeoutRetry timeouts, not NXDOMAIN
net.Dialer with multiple addressesTries each A/AAAA in turn; Happy Eyeballs via FallbackDelayPair with short connect timeouts
http.Transport IdleConnTimeout, MaxConnsPerHost, closing idle connectionsForces re-resolution after a DNS changeLong-lived keep-alive pins the old address
net/netip (Addr, Prefix.Contains)Allocation-free IP and CIDR handling (GeoDNS rules, allowlists)Unmap() IPv4-mapped IPv6
github.com/miekg/dnsWire-level client and server: TTLs, ECS, SOA, DNSSEC recordsUsed by CoreDNS; v2 on codeberg

Laravel ​

Before ​

The same mistake in PHP: resolve once with gethostbyname() (first IPv4 address, no TTL) and pin it with CURLOPT_RESOLVE in a singleton that lives as long as an Octane worker or a queue:work process.

php
<?php

namespace App\Clients;

use Illuminate\Support\Facades\Http;

/**
 * Before: resolve once, pin the address with CURLOPT_RESOLVE, keep it forever
 * (the singleton lives as long as an Octane worker or a queue:work process).
 * DNS failover, weighted canaries and load balancer address changes never
 * reach this process. The TLS certificate still matches because the Host and
 * SNI stay "inventory.example.com", which makes the bug harder to see.
 */
class PinnedInventoryClient
{
    private string $ip;

    public function __construct(private string $host = 'inventory.example.com')
    {
        // gethostbyname() returns the first IPv4 address and no TTL.
        $this->ip = gethostbyname($this->host);
    }

    public function stock(string $sku): array
    {
        return Http::withOptions([
            'curl' => [CURLOPT_RESOLVE => ["{$this->host}:443:{$this->ip}"]],
        ])
            ->get("https://{$this->host}/stock/{$sku}")
            ->throw()
            ->json();
    }
}

After ​

Multi-region configuration: current region from the environment, per-region service URLs, failover order, and the libcurl DNS cache window kept at or below the record TTL:

php
<?php

// config/regions.php: which region this process runs in, where each
// dependency lives per region, and the order to fail over in.
// The public entry point (api.example.com) is routed by Route 53 or
// Cloudflare; this file is for service-to-service calls behind it.

return [

    'current' => env('APP_REGION', 'eu-west-1'),

    'failover_order' => [
        'eu-west-1' => ['eu-central-1', 'us-east-1'],
        'eu-central-1' => ['eu-west-1', 'us-east-1'],
        'us-east-1' => ['us-west-2', 'eu-west-1'],
    ],

    'services' => [
        'inventory' => [
            'eu-west-1' => env('INVENTORY_URL_EU_WEST_1', 'https://inventory.eu-west-1.internal.example.com'),
            'eu-central-1' => env('INVENTORY_URL_EU_CENTRAL_1', 'https://inventory.eu-central-1.internal.example.com'),
            'us-east-1' => env('INVENTORY_URL_US_EAST_1', 'https://inventory.us-east-1.internal.example.com'),
        ],
    ],

    // How long a region stays skipped after a connection failure.
    'down_seconds' => (int) env('REGION_DOWN_SECONDS', 30),

    // libcurl keeps resolved names for 60 s by default (CURLOPT_DNS_CACHE_TIMEOUT).
    // Keep it at or below the record TTL so a DNS failover reaches this process.
    'dns_cache_seconds' => (int) env('HTTP_DNS_CACHE_SECONDS', 30),

];

Client-side regional failover. The router tries the local region first and skips regions another worker marked down in the shared cache; the client uses connectTimeout(2) (the documented default is 10 seconds), one quick in-region retry() for ConnectionException only, and fails over to the next region. The Laravel docs note that with throw: false, if "all of the requests fail because of a connection issue, a Illuminate\Http\Client\ConnectionException will still be thrown", which is exactly the signal the loop catches:

php
<?php

namespace App\Support;

use Illuminate\Support\Facades\Cache;

/**
 * Client-side regional failover for service-to-service calls: try the local
 * region first, then the configured order, skipping regions that failed in
 * the last few seconds. The skip list lives in the shared cache (Redis), so
 * one worker's discovery protects every worker in the region.
 */
class RegionRouter
{
    /** @return array<string, string> region => base URL, in the order to try */
    public function candidates(string $service): array
    {
        $current = config('regions.current');
        $urls = config("regions.services.{$service}", []);
        $order = array_merge([$current], config("regions.failover_order.{$current}", []));

        $healthy = [];
        $skipped = [];
        foreach ($order as $region) {
            if (! isset($urls[$region])) {
                continue;
            }
            if (Cache::has($this->key($service, $region))) {
                $skipped[$region] = $urls[$region];
            } else {
                $healthy[$region] = $urls[$region];
            }
        }

        // Fail open: if every region is marked down, try them all anyway.
        return $healthy !== [] ? $healthy : $skipped;
    }

    public function markDown(string $service, string $region): void
    {
        Cache::put($this->key($service, $region), true, config('regions.down_seconds'));
    }

    private function key(string $service, string $region): string
    {
        return "region-down:{$service}:{$region}";
    }
}
php
<?php

namespace App\Clients;

use App\Support\RegionRouter;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Http\Client\PendingRequest;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
use RuntimeException;

/**
 * After: every call resolves through the normal DNS path with a short
 * libcurl DNS cache, uses tight connect timeouts (a dead region should cost
 * 2 s, not the 10 s default), and fails over to the next region on a
 * connection-level error (DNS failure, refused, timeout). HTTP 4xx/5xx are
 * not failover signals: the region answered.
 */
class InventoryClient
{
    public function __construct(private RegionRouter $router) {}

    public function stock(string $sku): array
    {
        $lastError = null;

        foreach ($this->router->candidates('inventory') as $region => $baseUrl) {
            try {
                $response = $this->request($baseUrl)->get("/stock/{$sku}");

                return $response->throw()->json();
            } catch (ConnectionException $e) {
                $lastError = $e;
                $this->router->markDown('inventory', $region);
                Log::warning('inventory region unreachable, failing over', [
                    'region' => $region,
                    'error' => $e->getMessage(), // e.g. "cURL error 6: Could not resolve host"
                ]);
            }
        }

        throw new RuntimeException('inventory unavailable in every region', previous: $lastError);
    }

    private function request(string $baseUrl): PendingRequest
    {
        return Http::baseUrl($baseUrl)
            ->acceptJson()
            ->connectTimeout(2)
            ->timeout(5)
            ->withOptions([
                'curl' => [CURLOPT_DNS_CACHE_TIMEOUT => config('regions.dns_cache_seconds')],
            ])
            // One quick retry inside the region for a blip; then fail over.
            ->retry(2, 100, fn ($e) => $e instanceof ConnectionException, throw: false);
    }
}

Global HTTP client defaults with Http::globalOptions() (documented for "default options for every outgoing request"), passing raw cURL settings through Guzzle's curl key as the Guzzle FAQ describes:

php
<?php

namespace App\Providers;

use Illuminate\Support\Facades\Http;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        // Defaults for every outgoing request made with the Http facade.
        Http::globalOptions([
            'connect_timeout' => 2,
            'timeout' => 10,
            // Prefer IPv4 only if an upstream publishes broken AAAA records;
            // leave it unset otherwise so dual-stack keeps working.
            // 'force_ip_resolve' => 'v4',
            'curl' => [
                // libcurl default is 60 s; long-lived Octane and queue
                // workers would otherwise keep a stale address that long.
                CURLOPT_DNS_CACHE_TIMEOUT => config('regions.dns_cache_seconds'),
            ],
        ]);
    }
}

A health endpoint Route 53 can trust. Laravel ships a liveness route: "By default, the health check route is served at /up and will return a 200 HTTP response if the application has booted without exceptions", and it dispatches Illuminate\Foundation\Events\DiagnosingHealth so a listener can check the database or cache. Route 53 failover needs more: a fast deep check, a body string for string matching, Cache-Control: no-store, and a drain switch:

php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Response;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\DB;
use Throwable;

/**
 * Deep health endpoint for Route 53 (or Cloudflare Load Balancing monitors).
 *
 * Route 53 HTTP checks need a 2xx/3xx status within two seconds after the
 * TCP connection; with string matching, the string must appear in the first
 * 5,120 bytes of the body. So: cheap checks only, a short fixed body, and a
 * 503 when this region should stop receiving traffic, including a manual
 * "drain" switch used before maintenance or a planned failover.
 */
class HealthController
{
    public function __invoke(): Response
    {
        $region = config('regions.current');

        if (Cache::get('health:draining', false)) {
            return $this->reply(503, "draining region={$region}");
        }

        try {
            DB::select('select 1');           // primary database reachable
            Cache::put('health:probe', now()->timestamp, 60); // cache writable
        } catch (Throwable $e) {
            report($e);

            return $this->reply(503, "unhealthy region={$region}");
        }

        // Route 53 string matching looks for "HEALTHY_OK".
        return $this->reply(200, "HEALTHY_OK region={$region}");
    }

    private function reply(int $status, string $body): Response
    {
        return response($body, $status)
            ->header('Content-Type', 'text/plain')
            ->header('Cache-Control', 'no-store'); // never let a CDN cache a verdict
    }
}
php
<?php

// routes/api.php (excerpt; create the file with `php artisan install:api`).
// The api middleware group is stateless: no session, cookies or CSRF, so a
// probe costs one controller call. Laravel's built-in liveness route stays
// at /up (->withRouting(health: '/up') in bootstrap/app.php); the deep check
// below is what Route 53 calls, at /api/healthz/deep. Keep it out of any
// rate limiter: Route 53 checkers in many locations call it every 10 or 30 s
// and together may send several requests per second.

use App\Http\Controllers\HealthController;
use Illuminate\Support\Facades\Route;

Route::get('/healthz/deep', HealthController::class)->name('health.deep');

Dangling-record audit. An inventory of records and owned resources, and an Artisan command that flags CNAMEs to claimable provider hostnames we no longer own and A records to addresses we released. PHP's dns_get_record() returns each record's remaining ttl and, for CNAMEs, its target:

php
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

// An inventory of every record you publish and every cloud resource you own.
// Comparing the two finds dangling CNAMEs before an attacker does.
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('dns_records', function (Blueprint $table) {
            $table->id();
            $table->string('zone');                 // example.com.
            $table->string('name');                 // promo.example.com.
            $table->string('type', 10);             // A, AAAA, CNAME, ALIAS, TXT, CAA...
            $table->string('value');                // target hostname or address
            $table->unsignedInteger('ttl');
            $table->string('provider');             // route53, cloudflare
            $table->string('owner_team')->nullable();
            $table->timestamp('last_verified_at')->nullable();
            $table->timestamps();
            $table->unique(['zone', 'name', 'type', 'value']);
            $table->index(['type', 'value']);
        });

        Schema::create('cloud_resources', function (Blueprint $table) {
            $table->id();
            $table->string('kind');                 // s3-website, cloudfront, app-service, eip
            $table->string('hostname')->nullable(); // d111111abcdef8.cloudfront.net.
            $table->string('address', 45)->nullable(); // elastic IP
            $table->string('account');
            $table->timestamp('deleted_at')->nullable();
            $table->index('hostname');
            $table->index('address');
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('cloud_resources');
        Schema::dropIfExists('dns_records');
    }
};
php
<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * php artisan dns:audit-dangling
 *
 * Flags CNAMEs that point at provider hostnames we no longer own (subdomain
 * takeover risk) and A records that point at addresses we released.
 * Run it in CI after every infrastructure change and nightly.
 */
class AuditDanglingRecords extends Command
{
    protected $signature = 'dns:audit-dangling';

    protected $description = 'Find DNS records that point at resources we no longer own';

    /** Provider suffixes where a released name can be claimed by someone else. */
    private const CLAIMABLE = [
        '.cloudfront.net.', '.s3-website-', '.azurewebsites.net.', '.cloudapp.net.',
        '.herokuapp.com.', '.github.io.', '.trafficmanager.net.', '.elasticbeanstalk.com.',
    ];

    public function handle(): int
    {
        $findings = 0;

        $cnames = DB::table('dns_records as r')
            ->leftJoin('cloud_resources as c', function ($join) {
                $join->on('c.hostname', '=', 'r.value')->whereNull('c.deleted_at');
            })
            ->where('r.type', 'CNAME')
            ->whereNull('c.id')
            ->get(['r.name', 'r.value']);

        foreach ($cnames as $record) {
            $claimable = collect(self::CLAIMABLE)->contains(fn ($s) => str_contains($record->value, $s));
            // dns_get_record() returns the remaining TTL and the target of each record.
            $resolves = dns_get_record(rtrim($record->value, '.'), DNS_A | DNS_AAAA) ?: [];

            if ($claimable || $resolves === []) {
                $findings++;
                $this->error(sprintf('%s CNAME %s (claimable=%s, resolves=%s)',
                    $record->name, $record->value, $claimable ? 'yes' : 'no', $resolves ? 'yes' : 'no'));
            }
        }

        $released = DB::table('dns_records as r')
            ->leftJoin('cloud_resources as c', function ($join) {
                $join->on('c.address', '=', 'r.value')->whereNull('c.deleted_at');
            })
            ->whereIn('r.type', ['A', 'AAAA'])
            ->whereNull('c.id')
            ->get(['r.name', 'r.value']);

        foreach ($released as $record) {
            $findings++;
            $this->error("{$record->name} -> {$record->value}: address not in our inventory (released elastic IP?)");
        }

        $this->info("{$findings} finding(s)");

        return $findings === 0 ? self::SUCCESS : self::FAILURE;
    }
}

The Laravel angle ​

Laravel 13 / PHP featureUseNote
Http::connectTimeout() / timeout()Make a dead region cost seconds, not the 10 s connect defaultConnectionException on timeout
Http::retry($times, $sleep, $when, throw:)One in-region retry for connection errors onlyFail over to another region after that
Http::withOptions(['curl' => [...]]), Http::globalOptions()CURLOPT_DNS_CACHE_TIMEOUT, CURLOPT_RESOLVE for testsGuzzle passes the curl array to the handler
Guzzle force_ip_resolvev4/v6 when one family is broken upstreamOnly with the cURL handler
Http::pool()Parallel calls; a DNS failure is a ConnectionException entry in the result arrayInspect each entry
->withRouting(health: '/up'), DiagnosingHealth eventLiveness for load balancers and KubernetesThrow from the listener to return 500
Cache::put() / Cache::has() with a TTLShared "region down" flags and a drain switchRedis store so all workers see it
config/*.php + env()Region identity and endpoints per deploymentRun config:cache in production
dns_get_record()TTL-aware lookups and audits in PHPRemaining TTL, target, minimum-ttl for SOA
gethostbyname()First IPv4 only, no TTLAvoid for anything long-lived

Solving the classic problems ​

A region fails and users keep hitting it ​

SolutionHowAdvantageCost / limitation
Route 53 failover or latency + Evaluate target healthPrimary/secondary or per-region records with deep health checks, TTL 60Cheap, provider-nativeMinutes; open connections stay
Anycast global LBCloudflare proxied LB, Google global external ALB, AWS Global AcceleratorSeconds; IP does not changeTraffic through a provider; cost
Client-side regional failoverThe Laravel router and the Go poolWorks for internal calls in millisecondsCode in each client
Bounded connection lifetimeMax connection age in pools; re-resolve on reconnectMakes the other three effectiveSlightly more handshakes

A planned migration without a long tail ​

Lower the TTL one full old TTL before the change, change, keep the old target serving or redirecting until its traffic is zero, then raise the TTL (TTL timeline). For a DNS provider migration, keep both providers serving identical zones until the old NS TTL has passed, and handle DNSSEC (remove or roll the DS) first.

The apex must point at a load balancer or CDN ​

Route 53 alias, Cloudflare CNAME flattening, or an ANAME provider for A/AAAA; add an HTTPS AliasMode record for clients that support RFC 9460; keep www as a plain CNAME (The apex problem).

Users land in the wrong region ​

Check whether their resolver sends ECS (dig +subnet against your authoritative; Cloudflare 1.1.1.1 never does); add IP-based rules for large customers' resolver ranges (Route 53 IP-based routing); use anycast for latency and DNS only for residency; make the application redirect or proxy when a request arrives in the wrong region for its data.

A partner allowlists your egress IP ​

Route outbound traffic to that partner through NAT gateways with elastic IPs you reserve and publish; add new IPs to the partner's allowlist before the new region or NAT gateway carries traffic; alarm when an outbound request leaves through an unexpected address; consider a dedicated egress proxy (Squid, Envoy) with a fixed address for all allowlisted partners.

A forgotten CNAME becomes a takeover ​

Keep an inventory and audit it in CI. The query below finds CNAMEs whose target is a provider hostname we no longer own and A records pointing at addresses we released (schema from the Laravel migration):

sql
-- CNAMEs to claimable provider hostnames we do not own (subdomain takeover risk)
SELECT r.zone, r.name, r.value AS target, r.owner_team
FROM dns_records r
LEFT JOIN cloud_resources c
       ON c.hostname = r.value AND c.deleted_at IS NULL
WHERE r.type = 'CNAME'
  AND c.id IS NULL
  AND (r.value LIKE '%.cloudfront.net.'
    OR r.value LIKE '%.azurewebsites.net.'
    OR r.value LIKE '%.s3-website-%'
    OR r.value LIKE '%.herokuapp.com.'
    OR r.value LIKE '%.github.io.')
ORDER BY r.zone, r.name;

-- A/AAAA records pointing at addresses we released (old elastic IPs)
SELECT r.name, r.value
FROM dns_records r
LEFT JOIN cloud_resources c
       ON c.address = r.value AND c.deleted_at IS NULL
WHERE r.type IN ('A', 'AAAA') AND c.id IS NULL;

-- Records nobody has verified in 90 days
SELECT name, type, value, owner_team
FROM dns_records
WHERE last_verified_at IS NULL OR last_verified_at < now() - interval '90 days';

Clients ignore DNS changes ​

Remove resolve-once code (the Before examples); set max connection lifetimes (Go http.Transport with idle timeouts and periodic CloseIdleConnections, database pool SetConnMaxLifetime); keep libcurl's CURLOPT_DNS_CACHE_TIMEOUT at or below the TTL; for JVM clients set networkaddress.cache.ttl explicitly; test with a game day that changes a record and measures how long traffic takes to move.

The DNS provider itself goes down ​

Long TTLs on NS and stable records; two providers serving the same zone (primary + secondary via zone transfer, or two primaries managed from one source of truth); resolvers with serve-stale for your own fleet; keep health-check-driven steering on one provider and plain records on both.

Choosing ​

Which routing policy ​

SituationRecommendationExtra techniqueReason
One region, one LBSimple alias record (apex) + CNAME (www)TTL 300Nothing to steer
Active-passive DRFailover routing with deep health checksTTL 60, fast checks, drain switchCoarse, cheap, provider-native
Active-active multi-region, latency-sensitiveLatency routing + Evaluate target health, or an anycast global LBCapacity headroom per regionUsers go to the fastest healthy region
Data residency / legalGeolocation (country) with default recordEnforce again in the app and data layerDNS location is a hint, not a guarantee
Big customers behind known resolversIP-based routing (Route 53 CIDR collections)Per-customer rulesOverrides geolocation databases
Gradual migration or provider canaryWeighted routingHealth checks; TTL 30-60Coarse, works across stacks
Request-level canary, per-user stickinessL7 split (Envoy, NGINX, ALB, Istio)Header or cookie routingDNS cannot do per-request
Many equal servers, no LBMultivalue answerClient retries next addressHealth-aware round-robin
Seconds-level failoverAnycast (Cloudflare, Global Accelerator, Google global LB)Regional LBs behindIP never changes
Internal service-to-serviceClusterIP / VPC private zone + client-side failoverShort TTL, re-resolveFast and local

Which TTL ​

NameTTLReason
Failover / weighted / canary names30-60 sSteering must reach resolvers quickly
Normal service names (alias to LB/CDN)300 sBalance between agility and load
NS, MX, TXT, CAA, DS3600-172800 sRarely change; resilience to provider outages
ECS-steered names on Google Public DNS900 s or lessECS answers cannot be flushed
SOA (negative TTL)300-900 sNew names appear quickly after an early NXDOMAIN
Kubernetes Service names5 s (CoreDNS default)Pods churn; ClusterIP is stable anyway

Which product ​

NeedAmazon Route 53CloudflareGoogle Cloud DNSNS1
AWS-native aliases, free alias queriesBest fitCNAME flattening-ANAME-style
Anycast proxy + DNS steering in oneDNS only (add Global Accelerator/CloudFront)Proxied LBGlobal external ALBDNS only
Rich steering logicTraffic flow policies, geoproximity bias, IP-basedSteering policies, ECS controlsGeolocation, WRR, failoverFilter chain
Private zones / split viewPrivate hosted zonesInternal DNSPrivate zonesPrivate DNS (product-specific)
Second provider for resiliencePrimary or secondaryPrimary or secondaryPrimaryCommon as second provider

In architecture: from a single process to a distributed system ​

Monolith: one process, one database ​

One Laravel app on two VMs behind an AWS ALB. DNS work: apex alias to the ALB, www CNAME, CAA and DMARC records, TTL 300, the built-in /up route for the ALB target group. The only DNS-shaped risk is outbound: the app calls a payment provider that allowlists IPs, so the VMs sit in private subnets behind a NAT gateway with an elastic IP published to the provider. Do not resolve-and-pin anything in long-lived workers.

Modular monolith: boundaries without the network ​

Still one deployable, but modules get their own names for things they will one day own: files.example.com (S3 + CloudFront), ws.example.com (Laravel Reverb behind its own LB), api.example.com. Each name has an owner team in the record inventory, so a later split changes a record, not a client. Internal names live in a private hosted zone (*.internal.example.com), which avoids split-horizon on public names.

Microservices: every arrow is a lookup ​

text
     Request: checkout in eu-west-1
1    user -> Route 53 latency record -> eu-west-1 ALB (TTL 60)
2    ALB -> checkout pod (Kubernetes)
3    checkout -> inventory.shop.svc.cluster.local (CoreDNS, TTL 5, ClusterIP)
4    checkout -> payments.internal.example.com (private zone, failover record to eu-central-1)
5    payments -> bank API via NAT gateway EIP 203.0.113.7 (allowlisted)
6    inventory region down -> InventoryClient marks it down in Redis, fails over to eu-central-1 in ~2 s

What survives service boundaries: names, not addresses. Each service publishes a stable name; clients re-resolve, use short connect timeouts and fail over client-side; health endpoints are per service; egress IPs are part of each external integration's contract. Discovery mechanics and registries: Service Discovery.

Distributed data: replicas, caches, regions ​

DNS is often the failover pointer for data: db-primary.internal.example.com CNAME to the current PostgreSQL primary (Amazon RDS and Aurora endpoints work this way), redis.internal... to the current Redis primary. A promotion changes the record; clients with pooled connections keep writing to the old primary (now read-only or fenced) until they reconnect, so pool max lifetime and reconnect-on-error matter as much as the TTL. Multi-region active-active needs the routing policy to agree with data placement: geolocation for users whose data lives in one region, latency only for stateless reads. Replication and failover mechanics: Replication & Failover.

Scaling path: 1x, 10x, 100x ​

ScaleDNS and IP design
1x (one region)Alias at apex, TTL 300, one NAT gateway EIP, CAA, inventory from day one
10x (two regions, active-passive)Route 53 failover + deep health checks, TTL 60, fast checks, drain switch, per-region NAT EIPs published to partners, private hosted zones
100x (many regions, active-active)Anycast edge (CDN or global LB) for user traffic, latency/geo steering behind it, two DNS providers for the zone, ECS-aware GeoDNS for non-proxied names, IPv6 dual stack, automated dangling-record audits, game days that measure real failover time

Lab: a GeoDNS server you can query with dig ​

Steps 1 to 6 are a single Go process on the laptop and were run on macOS with dig 9.10.6; the output below is real. Step 7 queries public resolvers and is labelled expected, not run.

text
1    cd docs/snippets/system-design/ip-dns-geodns/go && go test ./...
     ok  academy/ip-dns-geodns/dnssource
     ok  academy/ip-dns-geodns/failover
     ok  academy/ip-dns-geodns/geodns
     ok  academy/ip-dns-geodns/ttlcache

2    go run ./geodns/cmd/geodns &        # GeoDNS on 127.0.0.1:5354/udp, admin on :8054
     dig @127.0.0.1 -p 5354 api.example.com A +subnet=198.51.100.0/24 +noall +comments +answer
     ;; flags: qr aa rd; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1
     ;; WARNING: recursion requested but not available
     ; CLIENT-SUBNET: 198.51.100.0/24/24
     api.example.com.  60  IN  A  192.0.2.10          <- EU answer, scope /24, authoritative (aa)

3    dig @127.0.0.1 -p 5354 api.example.com A +subnet=203.0.113.0/24 +short
     192.0.2.20                                        <- US answer

4    curl -s '127.0.0.1:8054/health?region=eu&up=false'
     eu healthy=false
     dig @127.0.0.1 -p 5354 api.example.com A +subnet=198.51.100.0/24 +short
     192.0.2.20                                        <- EU users failed over to US

5    dig @127.0.0.1 -p 5354 missing.example.com A +noall +comments +authority
     ;; ->>HEADER<<- opcode: QUERY, status: NXDOMAIN
     example.com.  900  IN  SOA  ns1.example.com. hostmaster.example.com. 1 7200 900 1209600 86400
                                                       <- negative TTL = min(900, 86400) = 900 s

6    dig @127.0.0.1 -p 5354 example.net A +noall +comments
     ;; ->>HEADER<<- opcode: QUERY, status: REFUSED     <- not an open resolver
text
7    (expected, not run) watch a public resolver count the TTL down and cache NXDOMAIN
     dig @8.8.8.8 www.example.com A +noall +answer      # TTL e.g. 3412
     dig @8.8.8.8 www.example.com A +noall +answer      # a few seconds later: TTL 3405 (remaining, not original)
     dig @8.8.8.8 does-not-exist-12345.example.com +noall +comments +authority
     # status: NXDOMAIN; SOA TTL in the authority section counts down the same way
     dig @1.1.1.1 www.example.com A +subnet=198.51.100.0/24
     # 1.1.1.1 does not forward ECS: the CLIENT-SUBNET line is absent or scope 0 in the reply

Things to try: change the TTL in main.go to 0 and see dig still work while a caching resolver in front would query every time; add an AAAA address for the US region and observe NODATA disappear; add a third region with an overlapping /16 rule and confirm the longest prefix wins.

Common misconceptions ​

BeliefReality
"TTL 60 means failover in 60 s."Detection + TTL + client caches and pooled connections; often minutes, sometimes until restart
"GeoDNS locates the user."It locates the resolver, or the ECS subnet when the resolver sends one; 1.1.1.1 sends none
"Round-robin DNS is a load balancer."No load or health awareness; use multivalue/failover policies and real LBs behind each address
"A CNAME at the apex is fine if the provider allows it."The standard forbids it; providers emulate it (ALIAS, flattening) by answering A/AAAA themselves
"Weight 10 of 100 means 10% of users."About 10% of resolver lookups; big resolvers make it lumpy
"TTL 0 disables caching everywhere."Many layers apply floors; it also maximises load and outage exposure
"DNS rollback is instant."Only for new lookups; cached answers and pinned clients stay
"DNSSEC encrypts DNS."It authenticates and protects integrity; no confidentiality
"DoH protects my zone from spoofing."It protects the client-resolver hop; zone authenticity needs DNSSEC
"Split-horizon is security."It is naming; access control happens elsewhere
"Deleting the cloud resource is the decommission."Delete the DNS record first, or someone else may claim the name
"Our service has a fixed IP."Only reserved addresses are fixed (elastic IP, static anycast IP); ALB addresses change
"Anycast balances load."It routes by topology; load can be very uneven
"A new record works immediately."Not where an earlier NXDOMAIN is cached for the negative TTL

Cheat sheet ​

TopicRemember
Authoritative vs recursiveYou control only the authoritative answer; everyone else caches it
ApexNo CNAME; use ALIAS/flattening, plus HTTPS AliasMode
TTL30-60 s steered, 300 s normal, hours-days for NS/MX/TXT/CAA; lower one old-TTL before a change
Negative TTLmin(SOA TTL, SOA MINIMUM); Route 53 default 900 s
Failover timeinterval x threshold + TTL + client caches
Route 53 health checks10/30 s, threshold 3, healthy if > 18% of checkers agree, 2xx/3xx within 2 s, string in first 5,120 bytes
Weighted0-255; 0 only used when all others unhealthy; per lookup, not per user
MultivalueUp to 8 healthy records; unhealthy ones if all fail
GeoDNSResolver location or ECS (/24 IPv4, /56 IPv6); always a default record
AnycastSame prefix via BGP from many sites; failover without DNS; uneven load
GSLBDNS steering for regions, LBs for instances, anycast LB for seconds
DiscoveryKubernetes A/SRV via CoreDNS, TTL 5 s; ClusterIP for most traffic
SecurityNo open resolvers, DNSSEC + CAA, DNS-first decommission, nightly dangling audit
EgressNAT gateway EIPs are contracts; add to allowlists before moving traffic
ClientsNo resolve-once; bounded connection lifetime; libcurl 60 s default cache

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Your Route 53 failover record has TTL 60 and fast health checks with threshold 3. A PHP-FPM app calls it with Laravel's HTTP client using defaults. What is a realistic worst-case time before new requests reach the secondary? Important ​

Answer

Answer: About 30 s detection (10 s x 3) plus 60 s TTL plus up to 60 s of libcurl's DNS cache on a reused handle: roughly two and a half minutes, more if connections are kept alive. Lower CURLOPT_DNS_CACHE_TIMEOUT and bound connection lifetimes to approach the DNS-only figure.

2 — Why can't example.com be a CNAME, and what are your three options? Must-know ​

Answer

Answer: A CNAME owner may hold no other data, and the apex must hold SOA and NS. Options: a provider alias (Route 53 alias, Cloudflare CNAME flattening, ANAME), A/AAAA records you manage yourself (only for stable addresses), or an HTTPS/SVCB AliasMode record for clients that support RFC 9460 (keep A/AAAA for others).

3 — A teammate created beta.example.com at 10:01; a smoke test that ran at 10:00 still fails at 10:10 with "Could not resolve host". Why, and how long until it works? Must-know ​

Answer

Answer: The 10:00 query cached NXDOMAIN for the negative TTL, min(SOA TTL, SOA MINIMUM). With Route 53 defaults that is 900 s, so around 10:15. Create records before anything queries them, or keep the SOA TTL low.

4 — EU users on 1.1.1.1 are routed to the US by your geolocation policy. What is going on? Important ​

Answer

Answer: 1.1.1.1 does not send EDNS Client Subnet, so your authoritative sees the address of the Cloudflare resolver site that forwarded the query. If that site maps to a US location in the provider's database, the US answer is returned. Fix with anycast or latency steering for performance, IP-based rules where you know resolver ranges, and application-level checks for residency.

5 — What does Route 53 return for a multivalue name when all eight records are unhealthy, and why is that sensible? Good to know ​

Answer

Answer: Up to eight unhealthy records. An empty answer guarantees an outage, while "all unhealthy" is more often a health-check or network-path problem than a real total outage. Failing open keeps some traffic flowing.

6 — When is DNS failover the wrong tool, and what replaces it? Must-know ​

Answer

Answer: When the outage budget is seconds or when existing connections must move. Use an anycast global load balancer (Cloudflare proxied LB, Google global external ALB, AWS Global Accelerator) or client-side failover for internal calls; keep DNS for coarse region selection.

7 — Explain how anycast fails over without changing DNS, and its main drawback for TCP. Important ​

Answer

Answer: Every site announces the same prefix via BGP; when a site withdraws its announcement, routers choose the next-best path and new packets reach another site. A route change mid-connection can deliver a TCP flow to a site that has no state for it, resetting the connection; anycast therefore suits short exchanges or edge proxies that terminate connections.

8 — Describe a subdomain takeover and the one operational rule that prevents most of them. Must-know ​

Answer

Answer: A record (usually a CNAME) points at a provider resource you deleted; an attacker creates a resource with the same provider name and serves content on your subdomain, with access to parent-domain cookies and a valid-looking origin. Rule: delete the DNS record before the resource, and audit records against an inventory of owned resources.

9 — Your weighted canary sends green weight 10 against blue 245, yet green's request share swings between 1% and 15%. Why? Important ​

Answer

Answer: Weights apply per resolver lookup, not per request. A few large resolvers that happen to cache green carry many users each for the TTL, so the realised share is lumpy. Use request-level splitting at L7 for precise canaries.

10 — Which of DNSSEC, DoT and DoH would stop (a) a café Wi-Fi rewriting DNS answers for a laptop and (b) a poisoned answer in an ISP resolver's cache? Important ​

Answer

Answer: (a) DoT or DoH to a trusted resolver protects the laptop-resolver hop (a validating stub with DNSSEC also works). (b) DNSSEC validation in the resolver rejects forged answers for signed zones; DoH/DoT do nothing for the resolver-authoritative path.

11 — A bank allowlists 203.0.113.7. You add a second AZ with its own NAT gateway. What breaks and how do you avoid it? Must-know ​

Answer

Answer: Traffic from the new AZ leaves through the new NAT gateway's elastic IP and the bank rejects it. Reserve the new elastic IP first, get it allowlisted, then route traffic; or route all bank traffic through one egress path with known IPs.

Glossary ​

TermMeaning
A recordMaps a name to an IPv4 address
AAAA recordMaps a name to an IPv6 address
CNAMEAlias from one name to a canonical name; no other data at that name
ALIAS / ANAMEProvider feature answering A/AAAA for a target name, usable at the apex
CNAME flatteningCloudflare's resolution of a CNAME chain into addresses at answer time
ApexThe top of a zone (example.com), which holds SOA and NS
NS recordNames the authoritative servers of a zone
SOA recordZone metadata: serial, timers, MINIMUM (negative TTL)
GlueA/AAAA records in the parent for name servers inside the child zone
DelegationParent publishing NS records for a child zone (zone cut)
Root serversThe 13 named authorities (a-m) serving the root zone, via hundreds of instances
TXT recordFree text: SPF, DKIM, DMARC, ACME challenges, verification tokens
SRV recordPriority, weight, port and target for a service (RFC 2782)
CAA recordLists certificate authorities allowed to issue for a name (RFC 8659)
SVCB / HTTPS recordService binding with ALPN, port, IP hints, ECH; AliasMode for apex aliasing (RFC 9460)
PTR recordReverse mapping from address to name
TTLSeconds a cache may keep a record
Negative cachingCaching NXDOMAIN/NODATA for min(SOA TTL, SOA MINIMUM) (RFC 2308)
NXDOMAINRCODE 3: the name does not exist
NODATANOERROR with no records of the requested type
SERVFAILRCODE 2: the resolver could not produce an answer
REFUSEDRCODE 5: the server will not answer this query
Resolver (stub)Client library or OS service that asks a recursive resolver
Recursive resolverServer that walks the hierarchy and caches answers
Authoritative serverServer holding the zone data; its answers carry the AA bit
TTL clampingA resolver applying its own minimum or maximum to TTLs
Serve-staleAnswering with expired data when authorities are unreachable (RFC 8767)
EDNS(0)Extension mechanism for larger messages and options (RFC 6891)
EDNS Client Subnet (ECS)Option carrying a truncated client prefix to authoritative servers (RFC 7871)
Round-robin DNSSeveral records for one name, rotated in answers
Multivalue answerRoute 53 policy: up to 8 health-checked records
Weighted routingAnswers chosen in proportion to weights
Latency-based routingAnswers chosen by measured network latency to provider regions
Geolocation routingAnswers chosen by the query source's country/continent
GeoDNSGeneral term for location-dependent DNS answers
Geoproximity / biasRoute 53 distance-based routing with a bias to grow or shrink regions
Failover routingPrimary answer while healthy, secondary otherwise
Health checkExternal probe deciding endpoint health; failure threshold, interval
GSLBGlobal server load balancing: DNS steering with health and load awareness
AnycastSame address announced from many sites; routing picks the nearest
UnicastOne address, one location
BGPBorder Gateway Protocol; how networks announce reachable prefixes
Split-horizonDifferent answers for internal and external clients (split view)
DNSSECSignatures and keys (RRSIG, DNSKEY, DS) for data integrity
DoTDNS over TLS, port 853 (RFC 7858)
DoHDNS over HTTPS, application/dns-message (RFC 8484)
DNS amplificationReflection attack using small spoofed queries and large answers
Cache poisoningGetting forged data accepted into a resolver cache
Subdomain takeoverAttacker claims the resource behind a dangling record
Dangling CNAMECNAME whose target resource no longer exists in your account
CoreDNSDNS server used by Kubernetes for cluster DNS
Service discoveryFinding instances of a service by name (DNS, registries)
Blue/greenTwo full stacks; switch traffic from one to the other
CanarySend a small share of traffic to a new version first
Elastic IPAWS static public IPv4 address you allocate and remap
NAT gatewayManaged NAT for private subnets' outbound traffic
Egress IPThe source address the outside world sees for your outbound traffic
IPv6128-bit addressing; dual stack publishes A and AAAA
Route 53AWS managed authoritative DNS with routing policies and health checks
CloudflareAnycast DNS, proxy and load-balancing provider

References ​

Built by Morteza Negahi