Sub topic 12
Global load balancing with DNS and anycast
This chapter assumes you know how a single-site load balancer works: backend pools, health checks, and the difference between Layer 4 and Layer 7. It also assumes you can read basic DNS records (A, AAAA, CNAME) and know what a TCP connection is. Everything here is about balancing across sites, such as regions or data centers, instead of across servers inside one site.
Why a single site is not enough
A highly available load balancer pair removes the load balancer as a single point of failure within one site. It does not protect you if the whole site is lost. A power failure, a network cut, a bad deployment, or a cloud region outage takes down every server and every load balancer in that location at once.
Running several sites solves two problems:
- Availability. If one site fails, others keep serving traffic.
- Latency. A user in Singapore is served faster by a nearby site than by one in Virginia. Light in fiber takes roughly 5 ms per 1,000 km one way, so distance alone adds tens to hundreds of milliseconds per round trip.
Global load balancing is the set of techniques that decide which site receives each client's traffic. The two main mechanisms are DNS-based steering and anycast routing. Many large services use both.
Where the decision is made
A local load balancer sees every connection and picks a backend. A global load balancer usually works earlier, before the client has connected to anything. It influences where the client sends its first packet.
| Aspect | Local load balancer | Global load balancer |
|---|---|---|
| Unit being balanced | Servers | Sites or regions |
| Decision point | When a connection or request arrives | Before the connection, in DNS or routing |
| Typical granularity | Per request or connection | Per DNS lookup or per network route |
| Failover speed | Seconds | Seconds to minutes, depending on caching and routing |
DNS-based global load balancing
With DNS-based balancing, the authoritative DNS server for your domain returns different answers depending on who asks and which sites are healthy. The client then connects directly to the returned IP address, which is normally the address of a local load balancer at one site.
Steering policies
DNS services typically offer several policies. You can combine them, for example geolocation first, then weighted within a region.
- Round robin or weighted. The server returns several addresses or rotates the order, with weights such as 70/30 to send most traffic to a larger site. This is useful for gradual migrations.
- Geolocation. The answer depends on the client's apparent country or region. This helps with data residency rules and with serving regional content.
- Latency-based. The service uses measurements of network latency between resolver locations and each site, and returns the site with the lowest value.
- Failover. A primary site gets all traffic while it is healthy. A secondary site is returned only when health checks on the primary fail.
Health checks in global DNS
The DNS service runs its own health checks against each site, usually from several probe locations. A typical check requests https://site.example.com/healthz every 10 to 30 seconds and marks the site unhealthy after a few consecutive failures. Probing from several locations avoids removing a healthy site because of one broken network path.
Check something that reflects the site's ability to serve users, such as the load balancer's public address with a path that touches the backends. Checking only that the load balancer answers a TCP connection can report a site as healthy when every backend behind it is down.
The caching problem
DNS answers are cached by recursive resolvers, operating systems, and sometimes applications, for the length of the record's TTL (time to live). If a site fails, clients that already hold its address keep trying it until their cached answer expires.
Failover time is therefore roughly:
detection time + TTL + client-side caching beyond TTLFor example, with three failed checks at 10 second intervals and a TTL of 60 seconds, the best case is about 90 seconds, and some clients will take longer.
Points to watch:
- Low TTLs reduce failover time but increase DNS query volume and lookup latency. A TTL of 30 to 60 seconds is common for load-balanced records. Do not set it to 0.
- Some resolvers and clients ignore low TTLs. Certain resolvers enforce a minimum, and some long-running applications resolve a name once at startup. You cannot fully control this.
- Browsers and JVMs may cache separately. Check the runtime's DNS cache settings for your own clients, such as service-to-service callers.
- The resolver's location is not the client's location. Geolocation and latency decisions are based on the recursive resolver's address, unless the resolver passes EDNS Client Subnet (ECS) data. A user of a public resolver located in another country can be steered to a distant site. ECS reduces this error but is not universally supported, and it has privacy costs.
Simple weighted DNS example
The following Python script simulates weighted selection with health state. It shows the logic a DNS steering service applies when it builds an answer.
import random
sites = [
{"name": "eu", "ip": "203.0.113.10", "weight": 70, "healthy": True},
{"name": "us", "ip": "198.51.100.20", "weight": 30, "healthy": True},
]
def answer(sites):
candidates = [s for s in sites if s["healthy"]]
if not candidates:
candidates = sites # fail open: better to try than to return nothing
chosen = random.choices(candidates, weights=[s["weight"] for s in candidates])[0]
return chosen["ip"]
counts = {}
for _ in range(10000):
ip = answer(sites)
counts[ip] = counts.get(ip, 0) + 1
print(counts)
sites[0]["healthy"] = False
print(answer(sites))With both sites healthy, roughly 7,000 answers go to the EU address and 3,000 to the US address. After the EU site is marked unhealthy, every answer is the US address. The "fail open" branch is a deliberate design choice: if every site looks unhealthy, the health checks themselves may be wrong, so returning all sites is safer than returning none.
Anycast routing
Anycast announces the same IP address from several locations. Each site tells the internet's routing system, through BGP (Border Gateway Protocol), that it can reach that prefix. Routers choose the path they consider best, which is usually the one with the shortest AS path, so each client's packets generally reach a topologically close site.
The client does nothing special. It resolves one address and connects to it. The network delivers the packets to a nearby site.
Failover with anycast
Each site withdraws its BGP announcement when it becomes unhealthy. A local agent usually monitors the site's load balancers and removes the route if they fail. Routers then converge on the remaining sites. Convergence typically takes from a few seconds to a minute or so. Because the client's address does not change, there is no DNS cache to wait out.
TCP and anycast
Routing is decided per packet by each router, but routes are stable for a given source in normal operation, so a TCP connection almost always keeps reaching the same site. The problem arises when routes change mid-connection, for example after a link failure or a BGP update. Packets from an existing connection can then arrive at a different site that has no state for it, and that site resets the connection.
This makes anycast a natural fit for:
- DNS. Most root and public DNS services use anycast. Queries are short, often single UDP packets, so a route change does not matter.
- CDN edges and DDoS scrubbing. Short requests, plus the ability to absorb attack traffic across many sites.
- TLS and HTTP front ends, when connections are short or clients can retry. Long-lived connections such as large uploads or WebSockets need more care.
Limits of anycast
- BGP does not measure load or latency. It prefers the shortest path, not the fastest or least loaded one. A client can be routed to a site that is geographically far but close in AS hops.
- You cannot steer precisely. You influence routing by prepending AS paths, announcing from selected locations, or using communities. Results depend on other networks' policies.
- You need your own IP space and an AS number, or a provider that offers anycast as a service. This is why most teams buy anycast from a CDN or cloud provider instead of running BGP themselves.
Comparing the two approaches
| Property | DNS-based | Anycast |
|---|---|---|
| Client sees | Different IPs for the same name | One IP |
| Failover delay | Detection plus TTL plus client caching | BGP convergence |
| Steering control | Fine: weights, geography, latency, failover | Coarse: BGP path selection |
| Accuracy of location | Based on the resolver, unless ECS is present | Based on the network path of the client |
| Mid-connection risk | None, since the client sticks to one IP | Possible resets if routes shift |
| Setup needs | A DNS provider with health checks | IP space, an AS number, BGP, or a provider |
The two combine well. A common design uses anycast for the DNS service itself, so DNS answers come from a nearby site, and DNS steering to return the address of the best site for the user. Another design places anycast addresses at CDN or edge sites, which terminate TLS and forward traffic to regional load balancers over the provider's backbone.
Design issues that cross sites
Global balancing is easy to draw and hard to operate. Check these points before you rely on it.
- Capacity for failover. If one of three sites fails, the other two must absorb its load. Sites running at 70 percent utilization cannot do this. Plan for N+1 capacity, or have a way to shed load.
- State and data. Sending a user to another site is only useful if that site has the user's data. Sessions, databases, and caches need replication or a design that tolerates a cold site. Sticky sessions do not carry across sites.
- Failback. When a site recovers, returning all traffic at once can overload its cold caches. Use weights to bring it back gradually.
- Health check flapping. A site that alternates between healthy and unhealthy causes traffic to bounce. Require several consecutive successes before restoring a site.
- Split decisions. The DNS service and the site's own load balancer may disagree about health. Make the DNS check exercise the same path users take.
- Testing. Drain a site on purpose during normal hours. A failover path that has never been used often does not work.
Observing global load balancing
Check these signals to confirm it works:
- Traffic share per site compared with the intended weights. A site getting far more than its weight points to resolver concentration, such as one large ISP resolver.
- Latency per client region and per site. High latency for a region suggests misrouted users.
- DNS health check results from each probe location.
- BGP announcements per site, to confirm that withdrawals happen when expected.
- Spot checks with
dig. Query from different networks or use a public resolver to see which answer is returned, and note the remaining TTL:
dig +noall +answer www.example.com A
dig +noall +answer www.example.com A @8.8.8.8The second column of each answer line is the remaining TTL. Running the command twice a few seconds apart shows it counting down when a resolver is serving a cached answer.
Exercise
A service runs in three regions with DNS failover. Health checks run every 10 seconds and mark a site unhealthy after 3 failures. The record TTL is 60 seconds. (a) What is the minimum time before a well-behaved client stops using a failed site, once it has failed? (b) Name two reasons some clients will take longer. (c) Why might a team add anycast in front of this setup?
Show answer
(a) About 90 seconds: up to 30 seconds to detect the failure with three failed checks, plus up to 60 seconds for cached answers to expire. In the best case, with a client whose cache expires immediately, it could be shorter, but 90 seconds is the planning figure. (b) Some resolvers enforce a minimum TTL or ignore the TTL, and some applications resolve a name once at startup and keep using the address. Browsers, JVMs, or operating systems may also cache separately. (c) With anycast, the client's IP address does not change, so failover depends on BGP route withdrawal and convergence (seconds to about a minute) and does not wait for DNS caches to expire. It also steers clients by network path instead of by the resolver's location.
Exercise
You announce one anycast address from Frankfurt and Ashburn. A user in Paris has a 20 minute file upload over TCP, and a BGP change moves the user's route to Ashburn halfway through. What happens, and what design choices reduce the impact?
Show answer
Ashburn has no TCP state for the connection, so it resets it and the upload fails. Ways to reduce the impact: use anycast only for short requests, have clients resume or retry uploads (chunked or resumable uploads), or have the anycast edge terminate the connection and carry the upload to the origin over a separate connection. For long-lived flows, you can also return a unicast address for the session after an anycast first contact.