Sub topic 8
Failing over traffic with load balancers and DNS
This chapter assumes you know what a load balancer and a DNS record are, and that you understand health checks and timeouts at a basic level. It builds on the failover sequence (detect, decide, switch, verify). Here we look at the "switch" step for network traffic. There are two main ways to do it: change which backend a load balancer picks, or change which address a name resolves to.
Two places to redirect traffic
Clients reach a service through a name and an address. You can redirect traffic at two points:
- The load balancer sits in front of the backends. Clients keep talking to the same address. The balancer stops sending requests to a failed backend. The switch takes effect as soon as the balancer decides, usually within seconds.
- DNS maps a name to one or more addresses. To fail over, you change the answer that clients get. The switch takes effect only when clients stop using their cached answer.
Use a load balancer to fail over between backends in one site. Use DNS to fail over between sites or regions, where one balancer cannot reach both.
Each approach has its own single point of failure. A single load balancer is a single point of failure for everything behind it, so production setups run balancers in pairs or as a managed, multi-zone service.
Load balancer failover
A load balancer keeps a list of backends. For each request or connection it picks one from the healthy subset. It builds that subset from two kinds of health information.
- Active checks. The balancer sends its own probe, such as
GET /healthz, at a fixed interval. It marks a backend down after a number of consecutive failures and up again after a number of successes. - Passive checks. The balancer watches real traffic. If proxied requests fail with connection errors or timeouts, it counts them against the backend.
The NGINX configuration below uses passive checks, since open-source NGINX does not probe on its own. It also shows a backup server.
upstream app {
server 10.0.0.11:8080 max_fails=3 fail_timeout=10s;
server 10.0.0.12:8080 max_fails=3 fail_timeout=10s;
server 10.0.0.13:8080 backup;
}
server {
listen 80;
location / {
proxy_pass http://app;
proxy_next_upstream error timeout http_502 http_503;
}
}Here is what each part does:
- The two active servers share load. By default NGINX uses round robin.
max_fails=3 fail_timeout=10smeans that after 3 failed attempts within 10 seconds, NGINX treats the server as unavailable for 10 seconds. It then tries it again.- The
backupserver receives traffic only when both active servers are unavailable. This is an active-passive arrangement inside an active-active pool. proxy_next_upstreamretries the same request on another server after a connection error, a timeout, or a 502 or 503 response. The client sees a slower response instead of an error.
Common load balancer mistakes
- Shallow health checks. A check that only tests whether the port is open reports a backend healthy when its database connection is broken. A check that tests the database too can fail every backend at once when the database is down. Then the balancer has no healthy target and the outage grows. Keep the health endpoint focused on whether this instance can serve requests. Handle dependency failures with degraded responses where you can.
- Retrying non-idempotent requests. An idempotent request has the same effect when repeated. NGINX does not retry non-idempotent requests (such as POST) by default after the request was sent. Turning that on can create duplicate orders or payments.
- Retry storms. When one backend dies, retried traffic lands on the others. If they were already near capacity, they fail too. Keep spare capacity (the N+1 idea from earlier chapters) so the survivors can take the extra load.
- Slow start. A recovered backend with a cold cache may fail under a full share of traffic. Many balancers can ramp traffic up gradually.
- Connection draining. When you remove a backend on purpose, let in-flight requests finish before you stop it.
DNS failover
With DNS failover, a monitor checks your endpoints. When one fails, the DNS service stops returning its address and returns another one. Managed DNS services such as Amazon Route 53 offer this as health-checked routing policies. Typical policies are:
| Policy | Behavior | Typical use |
|---|---|---|
| Failover (primary/secondary) | Returns the primary while it is healthy, otherwise the secondary | Active-passive across sites |
| Multivalue or weighted | Returns several healthy addresses, or splits by weight | Active-active across sites |
| Latency or geographic | Returns the closest or assigned site, skipping unhealthy ones | Multi-region services |
The TTL problem
Every DNS answer carries a TTL (time to live), the number of seconds resolvers may cache it. After you change an answer, clients can keep using the old address until their cached copy expires. So the worst-case switch time is roughly:
detection time + TTL + client behavior
Detection time is the monitor's check interval multiplied by its failure threshold. For example, a check every 10 seconds with 3 failures needed adds about 30 seconds. A TTL of 60 seconds then adds up to 60 more.
The following Python function turns those settings into a worst-case estimate.
def worst_case_dns_failover(check_interval_s, failure_threshold, ttl_s):
detection = check_interval_s * failure_threshold
return detection + ttl_s
print(worst_case_dns_failover(10, 3, 60)) # 90 seconds
print(worst_case_dns_failover(30, 3, 300)) # 390 secondsLowering the TTL speeds up failover, but it has costs:
- More queries reach your DNS provider, which can raise cost and load.
- Each lookup adds latency for clients whose cache has expired.
- Your DNS provider becomes a more critical dependency. If it is down and nothing is cached, clients cannot resolve your name at all.
Why DNS failover is never exact
- Resolvers and clients may ignore the TTL. Some caches hold records longer than the TTL. Some applications resolve a name once at startup and keep the address, for example long-lived connection pools in some runtimes.
- Existing connections keep going to the old address. DNS affects only new lookups. Established connections must fail and reconnect on their own.
- The monitor is a failure domain too. If the health checker sits in one region and loses connectivity to your endpoint, it may fail over a healthy site. Good services check from several vantage points and require agreement.
- Flapping. If a site alternates between healthy and unhealthy, DNS answers change back and forth and clients are scattered across sites. Use thresholds and hold-down times so that a site must stay healthy for a while before it returns to rotation.
Choosing between them
| Question | Load balancer | DNS |
|---|---|---|
| Switch speed | Seconds | Detection time plus TTL, often a minute or more |
| Scope | Backends behind one balancer | Sites, regions, or balancers |
| Client visibility | Clients see one stable address | Clients see changing addresses |
| Main weakness | The balancer itself | Caching you do not control |
Most designs use both layers. DNS or an anycast address picks a site. A balancer in that site picks a healthy backend. Fast, local failures are handled by the balancer. Whole-site failures are handled by DNS. Clients add a final layer with their own timeouts and endpoint lists, covered in the next chapter.
Exercises
Exercise
A DNS failover record has a health check every 20 seconds, 3 consecutive failures to mark the endpoint down, and a TTL of 120 seconds. What is the worst-case time before clients using a well-behaved resolver reach the secondary? Name one reason real clients might take longer.
Show answer
Detection takes 20 × 3 = 60 seconds, and the TTL adds up to 120 seconds, so the worst case is about 180 seconds. Real clients may take longer because some resolvers cache past the TTL, because some applications resolve the name only once at startup, or because established connections continue to use the old address until they fail.
Exercise
In the NGINX example, both active servers fail and the backup server also fails. What do clients receive, and which two settings determine how quickly NGINX tries the active servers again?
Show answer
NGINX has no available upstream, so clients receive an error such as 502 or 503. The settings maxfails=3 and failtimeout=10s decide this. After 3 failed attempts within 10 seconds a server is skipped for 10 seconds, and then NGINX tries it again.