Sub topic 7
The failover sequence: detect, decide, switch, verify
Failover moves work from a failed component to a healthy one. This chapter breaks it into four phases and shows where time is spent and where each phase tends to go wrong. It assumes you know what health checks, load balancers, and DNS TTLs are, and that you have seen the difference between active-active and active-passive designs.
Why treat failover as a sequence
"The standby takes over" hides four separate jobs. Each has its own delay and its own failure modes:
- Detect. Notice that the component is no longer serving.
- Decide. Choose whether to fail over, and which target to use.
- Switch. Promote the target and redirect traffic to it.
- Verify. Confirm that the new arrangement works.
Outage time is the sum of the four phases. Treating them separately shows which one to shorten, and which ones need extra caution.
Phase 1: Detect
Detection is a statistical judgment. A probe that fails once may mean a dropped packet, not a dead server. Most systems require several consecutive failures before they act. The detection delay then depends on three settings:
interval: seconds between probes.threshold: consecutive failures required.timeout: how long one probe waits before it counts as failed.
If the component dies just after a passing probe, the worst case is about interval * threshold + timeout. If it dies just before a probe, the best case is about (threshold - 1) * interval + timeout.
Lowering these values speeds up detection but raises the false-positive rate. A garbage-collection pause or a brief network blip can then trigger a failover that nothing needed. Failover has its own cost (lost connections, cold caches, a risk of data loss), so a false positive is not free.
Where the probe runs also matters. A probe from one monitor only proves that this monitor can reach the target. If the monitor's own network link is broken, it will "detect" a failure that doesn't exist. Use several observers, or require agreement among them, before treating a failure as real. The quorum chapter covers this in more depth.
Probe depth matters too. A TCP connect only shows that a port is open. An HTTP check that runs a trivial query shows that the application and its database path work. Deeper checks catch more failures, but they can also fail because of a shared dependency and take every instance out of rotation at once.
Phase 2: Decide
Once the detector says "down", something must decide what to do. Questions to answer:
- Is automatic failover allowed here, or should a human approve it?
- Is a healthy target available, and does it have enough capacity?
- Is the data on the target recent enough? An async replica that is 40 seconds behind means a promotion loses 40 seconds of writes.
- Has the system already failed over recently?
Automatic failover suits stateless tiers, where the cost of a wrong choice is a few dropped requests. For stateful systems, many teams automate the decision only when the loss is bounded and acceptable. Otherwise they page a human, accepting slower recovery in exchange for fewer irreversible mistakes.
A cooldown guards against flapping, where the system fails over, fails back, and fails over again. If the new primary fails verification and the controller keeps switching, it can make the outage worse. A cooldown makes the controller stop and escalate instead.
The sketch below shows the detect and decide logic with an injected clock, so it runs deterministically:
class FailoverController:
def __init__(self, probe, promote, verify, threshold=3, cooldown=300.0):
self.probe = probe
self.promote = promote
self.verify = verify
self.threshold = threshold
self.cooldown = cooldown
self.failures = 0
self.last_failover = None
def tick(self, now):
if self.probe():
self.failures = 0
return "healthy"
self.failures += 1
if self.failures < self.threshold:
return "suspect"
recent = (
self.last_failover is not None
and now - self.last_failover < self.cooldown
)
if recent:
return "blocked by cooldown: page a human"
self.last_failover = now
self.failures = 0
self.promote()
if not self.verify():
return "failover failed verification: page a human"
return "failed over"
primary_up = True
events = []
ctl = FailoverController(
probe=lambda: primary_up,
promote=lambda: events.append("promoted standby"),
verify=lambda: True,
)
for t in range(7):
if t == 1:
primary_up = False # the primary dies at t=1
print(t, ctl.tick(now=t * 5))
print(events)The run prints healthy at t=0, suspect at t=1 and t=2, and failed over at t=3. The probe keeps checking the old primary, so it fails again at t=4 and t=5. At t=6 the threshold is reached a second time, and the cooldown blocks a second failover. A real controller would probe the new primary after the switch, but this simplification is enough to show the cooldown.
Phase 3: Switch
Switching has three parts. The order matters.
- Fence the old component. Make sure it can no longer accept work. Otherwise you risk two active primaries, which the split-brain chapter covers.
- Promote the target. For a database replica, this means replaying any remaining log, accepting writes, and starting a new replication timeline. For a stateless server, it may mean nothing, because it is already running.
- Redirect traffic. Update the load balancer pool, move a virtual IP, or change a DNS record.
How fast traffic redirects depends on the mechanism. A load balancer removes a server from its pool within seconds of its own check failing. A DNS change takes effect only after cached answers expire, and some resolvers and clients keep records longer than the TTL says. The traffic chapter covers these mechanisms in detail. For now, remember that the switch time is often dominated by promotion (tens of seconds for a database) or by DNS caching (the TTL plus unpredictable extra time).
Phase 4: Verify
Failover is not done when the switch command returns. It is done when real traffic succeeds on the new target. Verification should cover:
- Health: the target answers health checks and real requests.
- Role: it reports itself as primary, and the old primary is confirmed fenced.
- Data: the data is readable, and the replication position matches what you expected to be promoted.
- Capacity: the target handles the full load without saturating.
- Redundancy: you know the system is now running with no spare, and an alert says so.
The last point is easy to miss. After a failover, the system usually has one fewer copy than before, so another failure causes an outage. Restoring redundancy is part of recovery, and the failback chapter covers it.
Where the time goes
A timing budget makes the phases concrete. This code computes best and worst cases:
def detection_window(interval, threshold, timeout):
best = (threshold - 1) * interval + timeout
worst = interval * threshold + timeout
return best, worst
best, worst = detection_window(interval=5, threshold=3, timeout=2)
decide = 0 # automatic decision
promote = 10 # replica promotion, seconds
dns_ttl = 60 # record cache time, seconds
verify = 15 # smoke tests
fixed = decide + promote + dns_ttl + verify
print("best case:", best + fixed, "seconds") # 97
print("worst case:", worst + fixed, "seconds") # 102With these numbers, the DNS TTL is the largest single cost, and detection is small. Cutting the TTL to 10 seconds saves 50 seconds, while halving the probe interval saves only about 8. Measure your own system before tuning, because the largest phase differs between architectures.
| Phase | Question it answers | Typical delay sources | Common failure |
|---|---|---|---|
| Detect | Is it really down? | Probe interval, threshold, timeout | False positives, or a monitor that can't see the target |
| Decide | Should we act, and with what? | Human approval, replica lag checks | Failover loops, promoting a stale replica |
| Switch | Who serves now? | Promotion time, DNS TTL, connection draining | Old primary still accepting writes |
| Verify | Does it work? | Smoke tests, warm-up | Declaring success before traffic is healthy |
Edge cases
- Failover causes overload. If two servers each ran at 70% load, the survivor receives 140% after one fails. It slows down, fails its health checks, and the failure cascades. Size spare capacity for the full load (see the N+1 design in an earlier chapter).
- Thundering herd. Every client reconnects at once, and the new primary faces a connection storm and a cold cache. Use jittered retries and connection limits.
- Partial failure. A server that responds to health checks but returns errors for real requests never triggers failover. Make probes exercise a real code path.
- Failure of the failover system. The controller is itself a component. Run it redundantly, and do not put it in the same fault domain as the thing it watches.
- In-flight work. Requests being processed when the primary dies are lost or ambiguous. Clients need idempotent operations so they can retry safely.
Summary
Failover is four phases: detect, decide, switch, verify. Detection settings trade speed against false positives. The decision step needs guards such as a cooldown, a data freshness check, and an escalation path. The switch must fence the old component before promoting a new one. Verification confirms that real traffic works and that the system knows it has lost a spare.
Exercise
A service has a probe interval of 10 seconds, a failure threshold of 3, and a probe timeout of 3 seconds. Failover takes 20 seconds to promote and the DNS TTL is 30 seconds. Verification takes 10 seconds, and the decision is automatic. What is the worst-case total time from failure to a verified switch? Which single change would reduce it most?
Show answer
Worst-case detection is 10 * 3 + 3 = 33 seconds. Adding promotion (20), DNS TTL (30), and verification (10) gives 93 seconds. The largest controllable contributor is detection at 33 seconds, closely followed by the DNS TTL at 30. Lowering the TTL to 5 seconds saves 25 seconds without raising the false-positive rate, while shortening detection by cutting the threshold to 2 saves 10 seconds but makes false failovers more likely. The TTL change is the safer one.
Exercise
A controller fails over from primary A to standby B, but B fails verification. The controller immediately fails back to A, which then fails its probes, and the cycle repeats. Which mechanism from this chapter stops the loop, and what should the controller do when it triggers?
Show answer
A cooldown (rate limit on failovers). When it triggers, the controller stops switching and escalates to a human, because repeated automatic switching suggests a cause that failover cannot fix, such as a shared dependency or bad data.