Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 5 of 6 · Concept · 20 min · revision 1

Global load balancing with DNS and anycast

Route users across regions with DNS-based global load balancing or anycast, estimate failover time from health checks, TTLs and routing convergence, and know which parts are outside your control.

Contentsand lesson path

What you will learn

  • Route users across regions with DNS-based or anycast global load balancing and estimate failover time.

Prerequisites: Scalability Fundamentals

01. Why it matters

Inside one region, a load balancer sees every instance and can switch traffic in seconds. Across regions there is no single box in front of everything: users start from networks all over the world, and the first decision about where they go is made by systems you only partly control, the Domain Name System (DNS) and Internet routing.

Global server load balancing (GSLB) steers users to a region that is close and healthy, and away from one that fails. Every design review then asks "how long until users stop hitting the broken region?", and the answer should be a range with its assumptions, not a single hopeful number.

It builds on the DNS lookup in the name-to-response lesson.

02. DNS-based global load balancing

With DNS-based GSLB, your authoritative DNS servers give different answers to different askers. A query for shop.example.com might return the address of the Singapore region for one asker and the Frankfurt region for another. The policy can use geography (often called GeoDNS), measured latency, weights for a gradual migration, and health: when a region fails its checks, the DNS service stops returning its address.

There is a catch in "for one asker". Users rarely ask your DNS servers directly. Their recursive resolver, run by their ISP, their company or a public DNS service, asks on their behalf, so your servers see the resolver's address, not the user's. A company that sends all staff queries through resolvers in Frankfurt will see its Tokyo office steered to Frankfurt. The EDNS Client Subnet option (RFC 7871) lets a resolver include part of the client's address in the query, but it is an informational RFC, it raises privacy concerns, and the RFC itself recommends that the feature be off by default in nameserver software. Do not assume it is present.

03. TTLs, caches and what you do not control

Every DNS record carries a time to live (TTL), which RFC 1035 defines as how long the record may be cached before the source is consulted again; RFC 2181 (section 8) adds that it is a maximum, not a mandatory time. After a failover, users keep the old answer until their cache expires, and several caches sit in the way:

  • the recursive resolver, which usually respects the TTL: the Google SRE book notes that not all resolvers do, and resolver software such as Unbound has a cache-min-ttl setting that keeps records longer than the owner intended;
  • the operating system, and some runtimes or HTTP clients with their own cache;
  • open connections, which ignore DNS: a keep-alive or HTTP/2 connection to the old region stays in use until it breaks.

Under RFC 8767 serve-stale, a resolver that cannot reach your authoritative servers may keep answering with expired records: good during a DNS outage, but stale answers then outlive the TTL. And negative answers are cached too (RFC 2308): if a name briefly returns "does not exist" after a mistaken change, that answer stays cached for a time set by the zone's SOA record.

Short TTLs speed up failover but increase query volume, add lookups to more first requests and make you more dependent on your DNS provider. A common compromise is a moderate TTL in normal operation, lowered at least one old TTL before a planned move, because caches filled before the change keep the old TTL.

04. Estimating failover time

Break DNS failover into three parts and give each a range:

  1. Detection: the global health checker needs several failed checks in a row. With checks every 30 s and three failures required, the region is marked down 60 to 90 s after it fails, depending on when the failure falls between checks.
  2. Propagation: resolvers that already cached the old answer keep it for up to one TTL after detection, longer if they hold records past the TTL.
  3. Reconnection: clients keep using open connections until they break, then retry with backoff.

With a 120 s TTL, a resolver that honours it moves its users by detection plus TTL: at worst about 90 + 120 = 210 s. A resolver that raises short TTLs to 600 s can take up to 90 + 600 = 690 s. The simulation below models 2,000 resolvers whose users normally go to region A, assumes 10% of them keep short records for 600 s, and lets region A fail at time 0. The 10% is an assumption to show the effect, not a measured share of real resolvers.

Python 3.12 · dns_failover.py (standard library only)
"""How long do users keep reaching a failed region after DNS failover?"""
import random

SEED = 11
RESOLVERS = 2_000  # recursive resolvers, each serving a similar share of users
TTL = 120  # seconds, the TTL you publish on the record
CHECK_EVERY, FAILS_TO_MARK_DOWN = 30, 3  # your global health checker
CLAMPED_SHARE, CLAMP_TO = 0.10, 600  # resolvers that raise short TTLs to 600 s

rng = random.Random(SEED)
# Region A fails at t=0. Checks run every 30 s at an unknown phase, so the
# third failed check lands between 60 s and 90 s after the failure.
detected = (FAILS_TO_MARK_DOWN - 1) * CHECK_EVERY + rng.uniform(0, CHECK_EVERY)

switch_times = []  # when each resolver first fetches an answer without A
for _ in range(RESOLVERS):
    ttl = CLAMP_TO if rng.random() < CLAMPED_SHARE else TTL
    expiry = rng.uniform(-ttl, 0) + ttl  # cached at a random time before t=0
    while expiry < detected:  # refetches before detection still return A
        expiry += ttl
    switch_times.append(expiry)

print(f"failure detected after {detected:.0f} s")
print("seconds after failure | users still sent to region A")
for t in (0, 60, 120, 180, 240, 300, 450, 600, 750):
    still = sum(1 for s in switch_times if s > t) / RESOLVERS
    print(f"{t:>21} | {100 * still:5.1f}%")
Expected output (seeded, identical on every run)
failure detected after 74 s
seconds after failure | users still sent to region A
                    0 | 100.0%
                   60 | 100.0%
                  120 |  64.6%
                  180 |  18.2%
                  240 |   7.1%
                  300 |   6.3%
                  450 |   3.6%
                  600 |   1.2%
                  750 |   0.0%

Nothing moves for the first 74 s, because the checker has not yet decided that region A is down. Then traffic drains over roughly one TTL as caches expire: nearly two thirds of users still go to A at 120 s, under a fifth at 180 s. After about 194 s every resolver that honours the TTL has moved; what remains is a long, thin tail from resolvers that kept the record longer, which ends only after about 674 s here.

So the honest answer to "how long does failover take?" here is about 1 to 3.5 minutes for most users, up to about 11 minutes for a small share in this run (690 s at worst by the formula), plus reconnection time. To shorten it, shorten detection and the TTL, and make clients retry on a fresh connection. Check from several locations so that one lost path cannot trigger a false failover; Amazon Route 53, for example, checks every 10 or 30 s from many locations and counts an endpoint as healthy while more than 18% of its checkers say so.

05. Anycast, and how the two combine

With anycast, the same IP prefix is announced through BGP, the Internet's routing protocol, from many sites at once. Each network's routers pick a path by their own policy, so each user reaches one of your sites, usually a nearby one. "Nearby" means close in routing terms; RFC 4786 points out that topological nearness does not in general match round-trip performance, so some users land on a site that is not their fastest. DNS itself relies on anycast: by late 2007, RFC 7094 notes, at least 10 of the 13 root name servers used it.

Failover works by withdrawing the route. When a site's health checks fail, it withdraws its announcement (RFC 4786 ties announcements to service health), and traffic shifts to the next-best site as routers elsewhere learn the change. No DNS cache is involved, so this is often faster than waiting for caches to expire, but the timing and the new path depend on routers in networks you do not operate. You control when you withdraw; you do not control how quickly every other network converges or which site it chooses next.

Anycast has its own limits. A routing change can move the packets of a running connection to a different site (RFC 7094, section 4.2), which breaks stateful protocols such as TCP and TLS unless that site can recognise the flow, so anycast usually fronts edge layers built for it rather than application servers. Running it yourself needs your own address space and BGP sessions with providers, so most teams buy it: Google Cloud's global external load balancers, for example, put one anycast IP address in front of backends in many regions.

DNS-based steering and anycast side by side
                     DNS-based GSLB                  Anycast
Steering decision    your DNS answer per resolver    routers in each network
Sees                 resolver address (ECS optional) network path, not the user
Failover delay       detection + TTL + caches        detection + BGP convergence
Outside your control resolver caching, TTL floors    other networks' routing
Per-user control     weights, geo, latency maps      little: routing decides
Typical owner        you, via a DNS provider         usually a CDN or cloud edge

A common combination puts an anycast edge from a CDN or cloud provider in front; its proxies terminate connections near users and choose a healthy region with their own health checks, taking the regional decision out of DNS caches. The order of these layers is a design choice, not a fixed recipe: some systems put a CDN first, others send API traffic straight to a regional balancer.

Neither tool moves your data. Steering users to region B helps only if B can serve them correctly: its replica may lag, so recent writes can be missing, and some data may not be allowed to leave a country. Decide routing together with data placement; the Availability design skill covers active-active and active-passive trade-offs. Measure failover from the client side in planned tests; paper estimates miss caches and connections you cannot see.

06. Check your understanding

Practice check · 3 questions

Global routing and failover

Three scenarios about negative caching, anycast convergence and resolver location.

Q1. During a migration, a script deletes the record for `api.shop.example` by mistake, and an engineer restores it two minutes later. The zone's SOA record has a TTL and a minimum of 900 s. For some users the name keeps failing with "does not exist" for up to 15 minutes after the fix. Why?
Q2. An anycast site detects that its own proxies are down and withdraws its BGP route within 2 s. Users on one ISP still reach a broken path for about a minute before landing on another site. Which part of that delay was outside the operator's control?
Q3. A company sends all staff DNS queries through its own resolvers in Frankfurt, which do not send EDNS Client Subnet. Staff in Tokyo use a SaaS product whose GeoDNS steers users to a Frankfurt or a Tokyo region. Which region do the Tokyo staff reach?
Practice only: not graded, not saved, not evidence.

07. Apply it

Write a failover estimate for a two-region service you know, or for a shop with regions in Europe and Asia:

  1. List the global health-check interval, threshold and number of checking locations, and compute the detection range.
  2. Choose a TTL and justify it against query cost and DNS provider dependency.
  3. Run the simulation with your numbers, and once more with CLAMPED_SHARE = 0.25, and report best, expected and worst times.
  4. State what is outside your control and how you would measure the real value in a test.
  5. Note which data the surviving region needs, and how stale it may be after failover.

08. Review prompt

From memory, describe how DNS-based steering and anycast each decide where a user goes, and what each one sees about the user. Then write the three parts of a DNS failover estimate, say which part a short TTL improves, and name two reasons some users can reach a failed region long after the TTL has passed.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check