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 for | Go to |
|---|---|
| The whole page in three tables | Everything in one minute |
| Why DNS is a routing layer at all | Why it exists |
| RFC 1034 to RFC 9460 in one timeline | Where it comes from |
| Public vs private IPs, elastic IPs, NAT gateways, egress allowlists, IPv6 | IP addressing at design level |
| Delegation, NS, SOA, glue, root and TLD servers | Authoritative DNS and delegation |
| Which record type for which job | Record types, The apex problem |
| TTL, negative caching, resolver behaviour | TTL, Negative caching, Caches you do not control |
| Round-robin, weighted, latency, geo, failover | Round-robin, Weighted, Latency, GeoDNS and ECS, Failover and health checks |
| DNS failover vs LB failover vs GSLB | GSLB |
| Anycast, BGP, unicast | Anycast |
| Internal vs external answers | Split-horizon |
| SRV, Kubernetes DNS, CoreDNS | Service discovery |
| Blue/green and canary by DNS | Blue/green and canary |
| DNSSEC, DoH, DoT | DNSSEC, DoH and DoT |
| Amplification, cache poisoning, subdomain takeover | DNS as attack surface |
| Flags, RCODEs, knobs, failover arithmetic, error messages | Mechanics |
| Code | Go, Laravel |
| Classic incidents and their fixes | Solving the classic problems |
| Which policy, which TTL, which product | Choosing |
| Monolith to multi-region | In architecture |
| A GeoDNS server you can query with dig | Lab |
| Wrong beliefs, summary, quiz, terms | Misconceptions, Cheat sheet, Self-check, Glossary |
Everything in one minute
The records an architect actually decides about.
| Record | In plain words | Tiny example | Design decision it carries |
|---|---|---|---|
| A / AAAA | Name to IPv4 / IPv6 address | api.example.com. 60 IN A 192.0.2.10 | Which endpoint, how long caches keep it |
| CNAME | This name is an alias of that name | www 300 IN CNAME d111111abcdef8.cloudfront.net. | Delegating an endpoint to a provider; not allowed at the apex |
| ALIAS / ANAME / CNAME flattening | Provider-side alias that answers with A/AAAA, so it works at the apex | Route 53 alias example.com -> my-alb-123.eu-west-1.elb.amazonaws.com | Apex pointing at a load balancer or CDN |
| NS | Which servers are authoritative for a zone | example.com. 172800 IN NS ns-2048.awsdns-64.net. | Which DNS provider(s), delegation |
| SOA | Zone metadata: serial, timers, negative TTL | ... 1 7200 900 1209600 86400 | How long "does not exist" is cached |
| TXT | Free text | SPF, DKIM, _acme-challenge, domain verification | Ownership proofs; keep an inventory |
| SRV | Service 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) |
| CAA | Which certificate authorities may issue | example.com. CAA 0 issue "letsencrypt.org" | Limits certificate mis-issuance |
| HTTPS / SVCB | Connection hints: ALPN (h2, h3), ports, IP hints, ECH; apex aliasing | example.com. 300 IN HTTPS 1 . alpn="h3,h2" | HTTP/3 discovery, apex alias without CNAME |
The routing policies, across products.
| Policy | Decides by | Amazon Route 53 | Cloudflare | Google Cloud DNS | What it cannot do |
|---|---|---|---|---|---|
| Simple / round-robin | Nothing; returns all records | Simple, Multivalue answer (up to 8 healthy) | Multiple records, DNS-only | Standard record set | Know load or health (unless multivalue) |
| Weighted | Your percentages | Weighted (0-255) | Load Balancing: pool/endpoint weights, Random steering | Weighted round robin | Guarantee per-user stickiness |
| Latency | Measured network latency to provider regions | Latency (per AWS Region) | Dynamic steering (RTT from health monitors) | (geolocation as proxy) | See your servers' load |
| Geolocation / GeoDNS | Country/continent of the resolver or ECS subnet | Geolocation, Geoproximity (bias), IP-based (CIDR) | Geo steering, Proximity steering | Geolocation | Know where a user behind a far-away resolver really is |
| Failover | Health check result | Failover (primary/secondary) | Pool fallback, monitors | Failover (with health checks) | Move existing connections |
Time and blast radius: the three numbers to know.
| Knob | Typical value | Lower means | Higher means |
|---|---|---|---|
| Record TTL for steered names | 30-300 s | Faster failover and canary shifts; more queries, more cost, more exposure to a DNS outage | Fewer 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 s | New names appear sooner after an NXDOMAIN was cached | A typo'd lookup or early probe pins NXDOMAIN for hours |
| Health check interval x failure threshold | Route 53: 30 s or 10 s x 3 | Faster detection; more flapping risk | Slower failover |
| Failover time (rough) | detection + TTL + client caches | Use anycast or an L7 global LB when you need seconds | DNS failover is a minutes-scale tool |
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 DNS | Steering with a load balancer or anycast proxy |
|---|---|
| Works before any packet reaches you; spans providers, clouds and regions | Works after the packet arrives at your edge |
| Decision per resolver (or per ECS subnet), not per user or per request | Decision 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 them | Can 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 expire | Fails closed: a down LB stops all traffic behind it |
| Health checks from the outside, every 10-30 s | Health 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
- "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.
- "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.
- "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.
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 standardThe 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.
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 allowlistedReal 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:
| Need | AWS | Google Cloud | Cloudflare / others | Note |
|---|---|---|---|---|
| Fixed inbound IPv4 | Elastic IP on an instance or NLB; Global Accelerator static anycast IPs | Reserved static external IP | Cloudflare proxied records answer with Cloudflare anycast IPs | ALB has no fixed IPs: point DNS at its name |
| Fixed outbound IPv4 | NAT gateway with elastic IP(s) | Cloud NAT with reserved IPs | Cloudflare egress IPs (Zero Trust) | One EIP per NAT gateway per AZ; publish the list |
| Private addressing | VPC CIDR from RFC 1918; private NAT gateway for overlapping ranges | VPC subnets | - | Plan non-overlapping CIDRs before peering |
| IPv6 | Dual-stack VPCs, egress-only internet gateway | Dual-stack subnets | IPv6 on by default for proxied records | AWS 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.
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 3Real 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:
| Product | Authoritative model | Multi-provider | Notes |
|---|---|---|---|
| Amazon Route 53 | Hosted zone, 4 name servers across TLDs | Possible, but traffic policies and alias records are Route 53-only | SOA default TTL 900 s, MINIMUM 86400 |
| Cloudflare DNS | Zone on Cloudflare's anycast network | Primary or secondary DNS (zone transfer) | Proxied records return Cloudflare IPs |
| Google Cloud DNS | Managed zones, public and private | Via zone transfer tooling | Routing policies on record sets |
| NS1 (IBM NS1 Connect) | Managed DNS with a filter-chain traffic engine | Commonly used as the second provider | Steering logic is provider-specific |
| BIND, Knot, PowerDNS, CoreDNS | Self-hosted authoritative | AXFR/IXFR to secondaries | You 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:
| Type | RFC | Holds | Design use | Gotcha |
|---|---|---|---|---|
| A | 1035 | IPv4 address | Endpoint; several records = round-robin | Never point at addresses you might release |
| AAAA | 3596 | IPv6 address | Dual stack; Happy Eyeballs prefers it | Broken IPv6 path causes slow connects, not errors |
| CNAME | 1034 | Canonical name | Hand a name to a provider (CDN, SaaS, LB) | No other data at that name; not at the apex; each hop adds a lookup |
| ALIAS / ANAME | Provider feature | Target name, answered as A/AAAA | Apex to LB/CDN | Non-standard; TTL controlled by provider |
| NS | 1035 | Name servers | Delegation, sub-delegation | Long TTL; mismatched parent/child NS confuse resolvers |
| SOA | 1035, 2308 | Serial, timers, MINIMUM | Negative TTL, zone transfers | MINIMUM is not a minimum TTL any more |
| MX | 1035 | Mail exchangers with preference | E-mail routing | CNAME at the target is not allowed |
| TXT | 1035 | Text | SPF, DKIM, DMARC, ACME, verification | Inventory and expire them |
| SRV | 2782 | Priority, weight, port, target | Service discovery with ports | Browsers do not use SRV for HTTP |
| CAA | 8659 | Allowed CAs | Stops other CAs issuing for you | Checked at issuance, not by browsers |
| PTR | 1035 | Reverse name for an address | Mail deliverability, logs | Lives in the address owner's zone (ask AWS/your ISP) |
| HTTPS / SVCB | 9460 | Priority, target, ALPN, port, ipv4hint/ipv6hint, ECH | HTTP/3 discovery, apex alias, encrypted ClientHello | Client support varies; keep A/AAAA too |
| DS, DNSKEY, RRSIG | 4034 | DNSSEC keys and signatures | Chain of trust | Expired signatures = SERVFAIL for validating resolvers |
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 beforeReal 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.
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 nameReal 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:
| Product | Mechanism | TTL | Health-aware |
|---|---|---|---|
| Amazon Route 53 | Alias record to ELB, CloudFront, S3 website, API Gateway, Global Accelerator, other records in the zone | Target's default (not settable) for AWS targets; target record's TTL inside the zone | "Evaluate target health" |
| Cloudflare | CNAME flattening (default at apex; all CNAMEs optionally; proxied CNAMEs always) | 300 s "Auto" for proxied records | Via Load Balancing |
| Azure DNS | Alias record sets to Azure resources | Resource-driven | Traffic Manager profiles |
| Generic | ANAME (DNSimple, NS1 and others) | Provider-defined | Provider-defined |
| Standard | HTTPS / SVCB AliasMode (RFC 9460) | Your TTL | No (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.
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:
| Layer | Behaviour | Knob |
|---|---|---|
| Google Public DNS | Caps 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 less | Flush Cache tool for non-ECS names |
| Cloudflare proxied records | TTL fixed at 300 s ("Auto"), not editable | Use DNS-only records for custom TTLs |
| Amazon Route 53 alias | TTL of the AWS target (not settable) | - |
CoreDNS kubernetes plugin | Default 5 s, max 3600 s | ttl option |
| libcurl (PHP, Laravel HTTP client) | Caches names 60 s by default on a handle | CURLOPT_DNS_CACHE_TIMEOUT |
Go net package | No answer cache; every Dial resolves (through the OS or the Go resolver) | Add your own (the Go section) |
| Long-lived connection pools | Keep the old address for the life of the connection | Max 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".
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 worksReal 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.
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 fineWhat each product does:
| Cache | Product | Behaviour |
|---|---|---|
| Public resolver | Google Public DNS | Anycast, ECS to supporting servers, TTL capped near 6 h, Flush Cache tool |
| Public resolver | Cloudflare 1.1.1.1 | Anycast, no ECS ("does not include client IP information"), DoH/DoT/ODoH |
| Cloud VPC resolver | Route 53 Resolver (AmazonProvidedDNS) | Resolves private hosted zones for the VPC (split view) |
| Kubernetes | CoreDNS with cache plugin | Pod queries go to CoreDNS; ndots:5 multiplies queries for external names |
| Self-hosted | Unbound, BIND | serve-expired, stale-answer-enable, prefetch |
| Language runtime | Go net | No cache; GODEBUG=netdns=go or cgo picks the resolver |
| HTTP client | libcurl / Guzzle / Laravel Http | 60 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".
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 timeoutReal 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).
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 / 255Real 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.
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.
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 locationReal 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:
| Product | Location source | Granularity | Default behaviour |
|---|---|---|---|
| Amazon Route 53 geolocation | Resolver IP or ECS | Continent, country, US state | "no answer" without a default record |
| Amazon Route 53 IP-based | Your CIDR blocks | Any prefix | Default (*) location |
| Cloudflare Load Balancing Geo / Proximity | Resolver location, ECS (prefer_ecs), Cloudflare PoP | Region, country (ECS: country-level) | Fallback pool |
| Google Cloud DNS geolocation | Source region | GCP regions | Nearest configured |
| NS1 | Filter chain (geotarget filters) | Country, region, ASN | Configurable |
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.
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 reconnectReal 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:
| Product | Probe | Interval | Threshold | Notes |
|---|---|---|---|---|
| Amazon Route 53 | HTTP, HTTPS, TCP, string match, calculated, CloudWatch alarm, private endpoint checks | 10 s (fast) or 30 s | Failure threshold (default 3) | 18% rule across locations |
| Cloudflare Load Balancing | HTTP(S), TCP, ICMP, SMTP, UDP-ICMP monitors | Configurable | Retries + timeout | Probes from every data center unless limited |
| Google Cloud DNS | Health checks on internal/external LBs | LB health check config | - | Failover and WRR policies |
| NS1 | Monitoring jobs feeding the filter chain | Configurable | Configurable | "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.
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| Option | Steers | Reaction time | Moves existing connections | Cost / complexity |
|---|---|---|---|---|
| DNS failover (Route 53, Cloud DNS) | New lookups | detection + TTL + client caches: minutes | No | Low |
| DNS GSLB with steering (Cloudflare DNS-only LB, NS1, Azure Traffic Manager) | New lookups, by geo, latency, load | Minutes | No | Medium |
| Anycast L7 global LB (Cloudflare proxied LB, Google global external ALB) | Each request | Seconds | New requests yes; open streams no | Medium-high, traffic through provider |
| Anycast L4 (AWS Global Accelerator) | Each new connection | Seconds | No | Medium |
| Regional LB (ALB, NLB, HAProxy, NGINX, Envoy) | Each request inside a region | Seconds | Can drain | Per region |
| Client-side failover (SDK, the Laravel router) | Each call | Milliseconds to seconds | Next call | Code 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".
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.
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 zoneReal 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.
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 cacheReal 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.
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:
| Need | DNS | L7 (Envoy, NGINX, ALB weighted target groups, Istio) |
|---|---|---|
| Whole-stack swap including LB, CDN, region | Good | Cannot, it lives inside one stack |
| Exact percentages, per-user stickiness, header-based routing | No | Yes |
| Rollback in seconds for everyone | No | Yes |
| Works for non-HTTP protocols | Yes | Protocol-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.
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 userFix / 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.
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.
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 exposedWhat provides protection:
| Threat | Your side | Provider side |
|---|---|---|
| Amplification from your servers | No open recursion; authoritative servers answer only their zones (REFUSED otherwise); response rate limiting (BIND RRL) | Route 53, Cloudflare absorb at anycast edge |
| Amplification against you | Anycast edge or DDoS service in front (DDoS) | Cloudflare, AWS Shield |
| Cache poisoning of your users' resolvers | Sign the zone (DNSSEC) | Resolvers: port + ID randomization, 0x20, DNS cookies, validation (Google Public DNS) |
| Subdomain takeover | Delete DNS before the resource; inventory; CI audit (Laravel command); avoid wildcard CNAMEs to third parties | Some providers verify domain ownership (TXT) before binding |
| Unauthorized certificates | CAA records | CAs must check CAA |
| Registrar hijack | Registrar lock, MFA, registry lock for key domains | Registrar |
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:
| Field | Meaning | Where it bites |
|---|---|---|
QR, AA | Response; Authoritative Answer | aa absent in dig output means you are reading a cache |
RD, RA | Recursion Desired / Available | An authoritative server answering RA to the internet is an open resolver |
TC | Truncated: retry over TCP | Large answers (many A records, DNSSEC, TXT) need TCP 53 open |
AD, CD, DO | Authenticated Data, Checking Disabled, DNSSEC OK | AD set by a validating resolver |
ID (16 bits) | Matches a response to a query | Cache-poisoning target; must be random |
| EDNS(0) OPT, UDP size | RFC 6891; payload size beyond 512 bytes | 1232 bytes is the common safe value to avoid IP fragmentation |
| ECS option | RFC 7871 SOURCE / SCOPE PREFIX-LENGTH | GeoDNS answers cached per subnet |
| RCODE | Name | What it means for you |
|---|---|---|
| 0 | NOERROR | Success; with an empty answer section it is NODATA |
| 1 | FORMERR | Malformed query (or ECS with a bad prefix, RFC 7871) |
| 2 | SERVFAIL | Resolver could not get a usable answer: authoritative down, DNSSEC validation failed, lame delegation |
| 3 | NXDOMAIN | Name does not exist; cached for the negative TTL |
| 5 | REFUSED | Server will not answer (not its zone, recursion not allowed) |
Failover arithmetic
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 + unboundedQuery 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
| Product | Knob | Value / range | Effect |
|---|---|---|---|
| Amazon Route 53 | Health check request interval | 30 s (standard) or 10 s (fast) | Detection speed |
| Amazon Route 53 | Failure threshold | 1-10, default 3 | Consecutive failures before unhealthy |
| Amazon Route 53 | Healthy rule | more than 18% of checkers report healthy | Avoids one region's network issue failing you over |
| Amazon Route 53 | HTTP timing | TCP connect 4 s, status within 2 s, body string in first 5,120 bytes within the next 2 s | Health endpoint must be fast and small |
| Amazon Route 53 | Weighted weight | 0-255 | 0 = only when all non-zero weights are unhealthy |
| Amazon Route 53 | Multivalue | up to 8 healthy records per answer | Health-aware round-robin |
| Amazon Route 53 | Geoproximity bias | -99 to 99 | Shrinks or grows a region's catchment |
| Amazon Route 53 | SOA default | TTL 900, MINIMUM 86400 (negative TTL = 900) | NXDOMAIN caching |
| Cloudflare | Proxied record TTL | 300 s "Auto", not editable | Change propagation for proxied names |
| Cloudflare Load Balancing | Steering | Off/standard, Geo, Dynamic, Proximity, Random, Least Outstanding Requests | Pool choice |
| Cloudflare Load Balancing | prefer_ecs | proximity / geo / always / never | Whether ECS decides location |
| Google Public DNS | Max cached TTL | about 6 h | Long TTLs clamped |
CoreDNS kubernetes | ttl | default 5 s, max 3600 s | Discovery freshness |
| libcurl | CURLOPT_DNS_CACHE_TIMEOUT | default 60 s; 0 disables; -1 forever | PHP/Laravel client freshness |
| Guzzle | force_ip_resolve | v4 or v6 | Avoid a broken address family |
| Go | GODEBUG=netdns=go / cgo (+1 for debug) | resolver choice | Pure Go resolver reads resolv.conf itself |
| RFC 8767 | stale TTL / recheck / max stale | 30 s / 30 s / 1-3 days | Serve-stale behaviour |
| RFC 2308 | max negative TTL at resolver | 1-3 hours sensible | Negative cache cap |
Error messages you will actually see
| Where | Message | Meaning |
|---|---|---|
Go net | lookup api.example.com on 10.0.0.2:53: no such host | NXDOMAIN (or NODATA for every family); DNSError.IsNotFound is true |
Go net | lookup api.example.com on 10.0.0.2:53: server misbehaving | SERVFAIL or a broken answer from the resolver |
Go net | dial tcp: lookup api.example.com: i/o timeout | Resolver did not answer in time |
| PHP / Laravel | cURL error 6: Could not resolve host: api.example.com (ConnectionException) | Resolution failed (often a cached NXDOMAIN) |
| PHP / Laravel | cURL error 28: Connection timed out after 2001 milliseconds | Address resolved but endpoint unreachable (old region, released IP) |
dig | status: SERVFAIL with aa missing | Resolver failed: try +cd to see whether DNSSEC validation is the cause |
dig | status: REFUSED | Server 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 console | Health check status "Unhealthy" with "Failure: Resolved IP address ... connection timed out" | Checker cannot reach the endpoint from the internet |
| Browser | DNS_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.
// 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:
// 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
}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:
// 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}
}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:
// 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
}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):
// 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
}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)
}
}// 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 feature | Use for DNS design | Note |
|---|---|---|
net.Resolver (LookupHost, LookupNetIP, LookupSRV, LookupTXT, LookupNS, LookupCNAME) | Everyday lookups | No TTL in results; no cache |
net.Resolver.PreferGo, Dial | Force 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+1 | Choose and debug the resolver | On Unix the pure Go resolver is preferred unless cgo is required |
*net.DNSError (IsNotFound, IsTimeout, IsTemporary) | Classify failures: NXDOMAIN vs timeout | Retry timeouts, not NXDOMAIN |
net.Dialer with multiple addresses | Tries each A/AAAA in turn; Happy Eyeballs via FallbackDelay | Pair with short connect timeouts |
http.Transport IdleConnTimeout, MaxConnsPerHost, closing idle connections | Forces re-resolution after a DNS change | Long-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/dns | Wire-level client and server: TTLs, ECS, SOA, DNSSEC records | Used 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
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
// 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
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
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
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
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
// 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
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
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 feature | Use | Note |
|---|---|---|
Http::connectTimeout() / timeout() | Make a dead region cost seconds, not the 10 s connect default | ConnectionException on timeout |
Http::retry($times, $sleep, $when, throw:) | One in-region retry for connection errors only | Fail over to another region after that |
Http::withOptions(['curl' => [...]]), Http::globalOptions() | CURLOPT_DNS_CACHE_TIMEOUT, CURLOPT_RESOLVE for tests | Guzzle passes the curl array to the handler |
Guzzle force_ip_resolve | v4/v6 when one family is broken upstream | Only with the cURL handler |
Http::pool() | Parallel calls; a DNS failure is a ConnectionException entry in the result array | Inspect each entry |
->withRouting(health: '/up'), DiagnosingHealth event | Liveness for load balancers and Kubernetes | Throw from the listener to return 500 |
Cache::put() / Cache::has() with a TTL | Shared "region down" flags and a drain switch | Redis store so all workers see it |
config/*.php + env() | Region identity and endpoints per deployment | Run config:cache in production |
dns_get_record() | TTL-aware lookups and audits in PHP | Remaining TTL, target, minimum-ttl for SOA |
gethostbyname() | First IPv4 only, no TTL | Avoid for anything long-lived |
Solving the classic problems
A region fails and users keep hitting it
| Solution | How | Advantage | Cost / limitation |
|---|---|---|---|
| Route 53 failover or latency + Evaluate target health | Primary/secondary or per-region records with deep health checks, TTL 60 | Cheap, provider-native | Minutes; open connections stay |
| Anycast global LB | Cloudflare proxied LB, Google global external ALB, AWS Global Accelerator | Seconds; IP does not change | Traffic through a provider; cost |
| Client-side regional failover | The Laravel router and the Go pool | Works for internal calls in milliseconds | Code in each client |
| Bounded connection lifetime | Max connection age in pools; re-resolve on reconnect | Makes the other three effective | Slightly 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):
-- 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
| Situation | Recommendation | Extra technique | Reason |
|---|---|---|---|
| One region, one LB | Simple alias record (apex) + CNAME (www) | TTL 300 | Nothing to steer |
| Active-passive DR | Failover routing with deep health checks | TTL 60, fast checks, drain switch | Coarse, cheap, provider-native |
| Active-active multi-region, latency-sensitive | Latency routing + Evaluate target health, or an anycast global LB | Capacity headroom per region | Users go to the fastest healthy region |
| Data residency / legal | Geolocation (country) with default record | Enforce again in the app and data layer | DNS location is a hint, not a guarantee |
| Big customers behind known resolvers | IP-based routing (Route 53 CIDR collections) | Per-customer rules | Overrides geolocation databases |
| Gradual migration or provider canary | Weighted routing | Health checks; TTL 30-60 | Coarse, works across stacks |
| Request-level canary, per-user stickiness | L7 split (Envoy, NGINX, ALB, Istio) | Header or cookie routing | DNS cannot do per-request |
| Many equal servers, no LB | Multivalue answer | Client retries next address | Health-aware round-robin |
| Seconds-level failover | Anycast (Cloudflare, Global Accelerator, Google global LB) | Regional LBs behind | IP never changes |
| Internal service-to-service | ClusterIP / VPC private zone + client-side failover | Short TTL, re-resolve | Fast and local |
Which TTL
| Name | TTL | Reason |
|---|---|---|
| Failover / weighted / canary names | 30-60 s | Steering must reach resolvers quickly |
| Normal service names (alias to LB/CDN) | 300 s | Balance between agility and load |
| NS, MX, TXT, CAA, DS | 3600-172800 s | Rarely change; resilience to provider outages |
| ECS-steered names on Google Public DNS | 900 s or less | ECS answers cannot be flushed |
| SOA (negative TTL) | 300-900 s | New names appear quickly after an early NXDOMAIN |
| Kubernetes Service names | 5 s (CoreDNS default) | Pods churn; ClusterIP is stable anyway |
Which product
| Need | Amazon Route 53 | Cloudflare | Google Cloud DNS | NS1 |
|---|---|---|---|---|
| AWS-native aliases, free alias queries | Best fit | CNAME flattening | - | ANAME-style |
| Anycast proxy + DNS steering in one | DNS only (add Global Accelerator/CloudFront) | Proxied LB | Global external ALB | DNS only |
| Rich steering logic | Traffic flow policies, geoproximity bias, IP-based | Steering policies, ECS controls | Geolocation, WRR, failover | Filter chain |
| Private zones / split view | Private hosted zones | Internal DNS | Private zones | Private DNS (product-specific) |
| Second provider for resilience | Primary or secondary | Primary or secondary | Primary | Common 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
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 sWhat 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
| Scale | DNS 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.
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 resolver7 (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 replyThings 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
| Belief | Reality |
|---|---|
| "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
| Topic | Remember |
|---|---|
| Authoritative vs recursive | You control only the authoritative answer; everyone else caches it |
| Apex | No CNAME; use ALIAS/flattening, plus HTTPS AliasMode |
| TTL | 30-60 s steered, 300 s normal, hours-days for NS/MX/TXT/CAA; lower one old-TTL before a change |
| Negative TTL | min(SOA TTL, SOA MINIMUM); Route 53 default 900 s |
| Failover time | interval x threshold + TTL + client caches |
| Route 53 health checks | 10/30 s, threshold 3, healthy if > 18% of checkers agree, 2xx/3xx within 2 s, string in first 5,120 bytes |
| Weighted | 0-255; 0 only used when all others unhealthy; per lookup, not per user |
| Multivalue | Up to 8 healthy records; unhealthy ones if all fail |
| GeoDNS | Resolver location or ECS (/24 IPv4, /56 IPv6); always a default record |
| Anycast | Same prefix via BGP from many sites; failover without DNS; uneven load |
| GSLB | DNS steering for regions, LBs for instances, anycast LB for seconds |
| Discovery | Kubernetes A/SRV via CoreDNS, TTL 5 s; ClusterIP for most traffic |
| Security | No open resolvers, DNSSEC + CAA, DNS-first decommission, nightly dangling audit |
| Egress | NAT gateway EIPs are contracts; add to allowlists before moving traffic |
| Clients | No resolve-once; bounded connection lifetime; libcurl 60 s default cache |
Self-check: questions & answers
- 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
| Term | Meaning |
|---|---|
| A record | Maps a name to an IPv4 address |
| AAAA record | Maps a name to an IPv6 address |
| CNAME | Alias from one name to a canonical name; no other data at that name |
| ALIAS / ANAME | Provider feature answering A/AAAA for a target name, usable at the apex |
| CNAME flattening | Cloudflare's resolution of a CNAME chain into addresses at answer time |
| Apex | The top of a zone (example.com), which holds SOA and NS |
| NS record | Names the authoritative servers of a zone |
| SOA record | Zone metadata: serial, timers, MINIMUM (negative TTL) |
| Glue | A/AAAA records in the parent for name servers inside the child zone |
| Delegation | Parent publishing NS records for a child zone (zone cut) |
| Root servers | The 13 named authorities (a-m) serving the root zone, via hundreds of instances |
| TXT record | Free text: SPF, DKIM, DMARC, ACME challenges, verification tokens |
| SRV record | Priority, weight, port and target for a service (RFC 2782) |
| CAA record | Lists certificate authorities allowed to issue for a name (RFC 8659) |
| SVCB / HTTPS record | Service binding with ALPN, port, IP hints, ECH; AliasMode for apex aliasing (RFC 9460) |
| PTR record | Reverse mapping from address to name |
| TTL | Seconds a cache may keep a record |
| Negative caching | Caching NXDOMAIN/NODATA for min(SOA TTL, SOA MINIMUM) (RFC 2308) |
| NXDOMAIN | RCODE 3: the name does not exist |
| NODATA | NOERROR with no records of the requested type |
| SERVFAIL | RCODE 2: the resolver could not produce an answer |
| REFUSED | RCODE 5: the server will not answer this query |
| Resolver (stub) | Client library or OS service that asks a recursive resolver |
| Recursive resolver | Server that walks the hierarchy and caches answers |
| Authoritative server | Server holding the zone data; its answers carry the AA bit |
| TTL clamping | A resolver applying its own minimum or maximum to TTLs |
| Serve-stale | Answering 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 DNS | Several records for one name, rotated in answers |
| Multivalue answer | Route 53 policy: up to 8 health-checked records |
| Weighted routing | Answers chosen in proportion to weights |
| Latency-based routing | Answers chosen by measured network latency to provider regions |
| Geolocation routing | Answers chosen by the query source's country/continent |
| GeoDNS | General term for location-dependent DNS answers |
| Geoproximity / bias | Route 53 distance-based routing with a bias to grow or shrink regions |
| Failover routing | Primary answer while healthy, secondary otherwise |
| Health check | External probe deciding endpoint health; failure threshold, interval |
| GSLB | Global server load balancing: DNS steering with health and load awareness |
| Anycast | Same address announced from many sites; routing picks the nearest |
| Unicast | One address, one location |
| BGP | Border Gateway Protocol; how networks announce reachable prefixes |
| Split-horizon | Different answers for internal and external clients (split view) |
| DNSSEC | Signatures and keys (RRSIG, DNSKEY, DS) for data integrity |
| DoT | DNS over TLS, port 853 (RFC 7858) |
| DoH | DNS over HTTPS, application/dns-message (RFC 8484) |
| DNS amplification | Reflection attack using small spoofed queries and large answers |
| Cache poisoning | Getting forged data accepted into a resolver cache |
| Subdomain takeover | Attacker claims the resource behind a dangling record |
| Dangling CNAME | CNAME whose target resource no longer exists in your account |
| CoreDNS | DNS server used by Kubernetes for cluster DNS |
| Service discovery | Finding instances of a service by name (DNS, registries) |
| Blue/green | Two full stacks; switch traffic from one to the other |
| Canary | Send a small share of traffic to a new version first |
| Elastic IP | AWS static public IPv4 address you allocate and remap |
| NAT gateway | Managed NAT for private subnets' outbound traffic |
| Egress IP | The source address the outside world sees for your outbound traffic |
| IPv6 | 128-bit addressing; dual stack publishes A and AAAA |
| Route 53 | AWS managed authoritative DNS with routing policies and health checks |
| Cloudflare | Anycast DNS, proxy and load-balancing provider |
References
- P. Mockapetris, RFC 1034, Domain Names: Concepts and Facilities (1987): https://www.rfc-editor.org/rfc/rfc1034
- P. Mockapetris, RFC 1035, Domain Names: Implementation and Specification (1987): https://www.rfc-editor.org/rfc/rfc1035
- RFC 1918, Address Allocation for Private Internets: https://www.rfc-editor.org/rfc/rfc1918
- RFC 2181, Clarifications to the DNS Specification: https://www.rfc-editor.org/rfc/rfc2181
- RFC 2308, Negative Caching of DNS Queries: https://www.rfc-editor.org/rfc/rfc2308
- RFC 2782, A DNS RR for specifying the location of services (DNS SRV): https://www.rfc-editor.org/rfc/rfc2782
- RFC 4033, DNS Security Introduction and Requirements: https://www.rfc-editor.org/rfc/rfc4033
- RFC 4786, Operation of Anycast Services: https://www.rfc-editor.org/rfc/rfc4786
- RFC 5358, Preventing Use of Recursive Nameservers in Reflector Attacks: https://www.rfc-editor.org/rfc/rfc5358
- RFC 6891, Extension Mechanisms for DNS (EDNS(0)): https://www.rfc-editor.org/rfc/rfc6891
- RFC 7858, DNS over TLS: https://www.rfc-editor.org/rfc/rfc7858
- RFC 7871, Client Subnet in DNS Queries: https://www.rfc-editor.org/rfc/rfc7871
- RFC 8484, DNS Queries over HTTPS (DoH): https://www.rfc-editor.org/rfc/rfc8484
- RFC 8659, DNS Certification Authority Authorization (CAA): https://www.rfc-editor.org/rfc/rfc8659
- RFC 8767, Serving Stale Data to Improve DNS Resiliency: https://www.rfc-editor.org/rfc/rfc8767
- RFC 9460, Service Binding and Parameter Specification via the DNS (SVCB and HTTPS RRs): https://www.rfc-editor.org/rfc/rfc9460
- RFC 9499, DNS Terminology: https://www.rfc-editor.org/rfc/rfc9499
- IANA, Root Servers: https://www.iana.org/domains/root/servers
- Amazon Route 53, Choosing a routing policy: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy.html
- Amazon Route 53, Weighted routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-weighted.html
- Amazon Route 53, Latency-based routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-latency.html
- Amazon Route 53, Geolocation routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-geo.html
- Amazon Route 53, Geoproximity routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-geoproximity.html
- Amazon Route 53, Multivalue answer routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-multivalue.html
- Amazon Route 53, Failover routing: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/routing-policy-failover.html
- Amazon Route 53, How health checks determine endpoint health: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/dns-failover-determining-health-of-endpoints.html
- Amazon Route 53, Types of health checks: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/health-checks-types.html
- Amazon Route 53, Alias and non-alias records: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/resource-record-sets-choosing-alias-non-alias.html
- Amazon Route 53, NS and SOA records: https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/SOA-NSrecords.html
- Amazon Route 53, Private hosted zone considerations (split-view DNS): https://docs.aws.amazon.com/Route53/latest/DeveloperGuide/hosted-zone-private-considerations.html
- Amazon EC2, Elastic IP addresses: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/elastic-ip-addresses-eip.html
- Amazon VPC, NAT gateways: https://docs.aws.amazon.com/vpc/latest/userguide/vpc-nat-gateway.html
- Cloudflare DNS, CNAME flattening: https://developers.cloudflare.com/dns/cname-flattening/
- Cloudflare DNS, Proxy status: https://developers.cloudflare.com/dns/proxy-status/
- Cloudflare DNS, DNSSEC: https://developers.cloudflare.com/dns/dnssec/
- Cloudflare Load Balancing, Global traffic steering: https://developers.cloudflare.com/load-balancing/understand-basics/traffic-steering/steering-policies/
- Cloudflare Load Balancing, Monitors: https://developers.cloudflare.com/load-balancing/monitors/
- Cloudflare Load Balancing, Proxy modes: https://developers.cloudflare.com/load-balancing/understand-basics/proxy-modes/
- Cloudflare 1.1.1.1, Encryption: https://developers.cloudflare.com/1.1.1.1/encryption/
- Cloudflare 1.1.1.1, FAQ (ECS): https://developers.cloudflare.com/1.1.1.1/faq/
- Cloudflare blog, A Brief Anycast Primer: https://blog.cloudflare.com/a-brief-anycast-primer/
- Cloudflare blog, Deep Inside a DNS Amplification DDoS Attack: https://blog.cloudflare.com/deep-inside-a-dns-amplification-ddos-attack/
- Google Public DNS, Performance: https://developers.google.com/speed/public-dns/docs/performance
- Google Public DNS, Security: https://developers.google.com/speed/public-dns/docs/security
- Google Public DNS, FAQ: https://developers.google.com/speed/public-dns/faq
- Google Cloud DNS, Routing policies and health checks: https://cloud.google.com/dns/docs/routing-policies-overview
- CERT/CC VU#800113, Multiple DNS implementations vulnerable to cache poisoning: https://www.kb.cert.org/vuls/id/800113
- MDN, Subdomain takeover: https://developer.mozilla.org/en-US/docs/Web/Security/Subdomain_takeovers
- OWASP WSTG, Test for Subdomain Takeover: https://owasp.org/www-project-web-security-testing-guide/latest/4-Web_Application_Security_Testing/02-Configuration_and_Deployment_Management_Testing/10-Test_for_Subdomain_Takeover
- Kubernetes, DNS for Services and Pods: https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/
- CoreDNS, kubernetes plugin: https://coredns.io/plugins/kubernetes/
- Go, package net: https://pkg.go.dev/net
- miekg/dns: https://github.com/miekg/dns
- Laravel 13, HTTP Client: https://laravel.com/docs/13.x/http-client
- Laravel 13, Deployment (health route): https://laravel.com/docs/13.x/deployment
- Guzzle, Request options: https://docs.guzzlephp.org/en/stable/request-options.html
- Guzzle, FAQ (custom cURL options): https://docs.guzzlephp.org/en/stable/faq.html
- libcurl, CURLOPT_DNS_CACHE_TIMEOUT: https://curl.se/libcurl/c/CURLOPT_DNS_CACHE_TIMEOUT.html
- PHP manual, dns_get_record: https://www.php.net/manual/en/function.dns-get-record.php
- Google, IPv6 statistics: https://www.google.com/intl/en/ipv6/statistics.html