Sub topic 6
Detecting failure with health checks and heartbeats
Failover starts with detection. A system cannot switch away from a failed component until something decides that the component has failed. This chapter assumes you know what a load balancer is, how timeouts work, and the basic ideas of redundancy and single points of failure from earlier chapters. It covers the kinds of checks, how detection settings trade speed against false positives, and the common mistakes in health check design.
Why detection is hard
A failure detector is a guess. From the outside, a component that has stopped, one that is slow, and one that is cut off by the network all look the same: no answer arrives. The detector must pick a point at which silence counts as failure.
Two errors are possible:
- A false negative means the detector reports a healthy component when it is actually broken. Traffic keeps going to a dead server.
- A false positive means the detector reports a failure when the component is fine. The system fails over without need, and may cause an outage that the original fault would not have caused.
Every detection setting moves the balance between these errors. Faster detection shortens the time users see errors, and it also raises the chance of false positives.
Two detection models
Detection works in one of two directions.
- Active probing (health checks). A monitor, such as a load balancer, sends a request to the target at a fixed interval and judges the response.
- Heartbeats. The target sends a periodic "I am alive" message to the monitor or to its peers. The monitor declares failure when messages stop arriving.
| Property | Health check (pull) | Heartbeat (push) |
|---|---|---|
| Who initiates | The monitor | The monitored component |
| Typical use | Load balancers, orchestrators | Clustered databases, leader election, peer groups |
| Can test real work | Yes, with a request to a real endpoint | Only what the sender chooses to report |
| Failure signal | Probe fails or times out | Expected message does not arrive |
| Main weakness | Probe load on the target, shallow checks | A stuck process may keep sending heartbeats from a separate thread |
Many systems use both. A load balancer probes web servers, while database replicas exchange heartbeats with each other.
Levels of health checks
A check can look at the component from different depths.
- Network level. Can a TCP connection be opened to the port? This catches a crashed process or a dead host. It does not show that the application works.
- Process level. Is the process running? An init system or container runtime checks this. A process can run while being deadlocked.
- Application level. Send an HTTP request to a health endpoint and expect a status such as 200. This catches many hung or misconfigured applications.
- Dependency level (deep check). The endpoint also tests the database connection, a cache, or a downstream service.
- Synthetic transaction. A monitor performs a real user action, such as logging in or adding an item to a cart, and checks the result.
Deeper checks find more kinds of failure, and they have more ways to cause trouble themselves. The next sections explain why.
Shallow versus deep checks
A shallow check only shows that the process answers. A deep check also exercises what the process needs to do real work.
Deep checks have a serious risk. Suppose every web server's health check queries the shared database. The database slows down for a minute. Every web server's check then fails, the load balancer marks all of them unhealthy, and the whole service goes offline. The web servers were fine, and they could not have fixed the database anyway. The health check turned a partial degradation into a total outage.
Guidelines that reduce this risk:
- Keep the liveness check shallow. It answers "is this process able to respond at all?"
- Use a separate readiness check for "can this instance serve traffic right now?" Include only dependencies that this instance needs and that other instances might not share.
- Do not fail a check because of a dependency that every instance shares. Alert on that dependency separately.
- If all instances look unhealthy at once, prefer a "fail open" behavior, where the load balancer keeps sending traffic anyway. Many load balancers support this, often called panic mode or a minimum healthy threshold.
A health endpoint example
The following Python program serves two endpoints using only the standard library. /live is shallow. /ready checks a local condition, here whether a flag file allows traffic, and returns 503 when the instance should not receive requests.
from http.server import BaseHTTPRequestHandler, HTTPServer
import os
DRAIN_FLAG = "/tmp/drain"
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
if self.path == "/live":
self.respond(200, b"alive\n")
elif self.path == "/ready":
if os.path.exists(DRAIN_FLAG):
self.respond(503, b"draining\n")
else:
self.respond(200, b"ready\n")
else:
self.respond(404, b"not found\n")
def respond(self, status, body):
self.send_response(status)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
if __name__ == "__main__":
HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()Creating the file /tmp/drain makes /ready return 503. A load balancer that probes /ready then stops sending new requests to this instance, while /live still returns 200 so the instance is not killed. This pattern lets you drain an instance for maintenance without an outage.
Tuning detection: interval, timeout, and thresholds
Most health check systems expose the same four settings.
| Setting | Meaning | Effect of making it smaller |
|---|---|---|
| Interval | Time between probes | Faster detection, more probe traffic |
| Timeout | How long to wait for one answer | Faster detection, more false positives on slow responses |
| Unhealthy threshold | Consecutive failures before marking down | Faster detection, more false positives from single blips |
| Healthy threshold | Consecutive successes before marking up | Faster recovery, risk of flapping |
Worst-case detection time is roughly:
detection time ≈ interval × unhealthy_threshold + timeoutWith an interval of 5 seconds, a threshold of 3, and a timeout of 2 seconds, a server that dies right after a successful probe is noticed after about 17 seconds. That window counts toward your recovery time objective, which a later chapter covers. During those seconds, some requests go to a dead server unless the load balancer retries them elsewhere.
The following script computes the worst-case detection time and compares settings.
def detection_time(interval, timeout, unhealthy_threshold):
return interval * unhealthy_threshold + timeout
settings = {
"conservative": (10, 5, 3),
"balanced": (5, 2, 3),
"aggressive": (1, 1, 2),
}
for name, (interval, timeout, threshold) in settings.items():
seconds = detection_time(interval, timeout, threshold)
print(f"{name}: {seconds} seconds")It prints 35 seconds for conservative, 17 for balanced, and 3 for aggressive. The aggressive profile reacts quickly, but a garbage collection pause of two seconds or a brief network drop can remove a healthy server. Removing servers shifts their load onto the rest, which can slow those down and cause more removals.
Flapping and cascading removal
Flapping is when a component alternates quickly between healthy and unhealthy. Each change can trigger a failover, a DNS update, or a leader election, and each of those has its own cost.
Ways to reduce flapping:
- Require more consecutive successes to mark a server up than failures to mark it down. A common choice is a healthy threshold equal to or higher than the unhealthy threshold.
- Add a hold-down timer, which keeps a component out of service for a minimum time after it fails.
- Use a slow-start period, where a returning server receives a growing share of traffic instead of its full share at once.
- Set a limit on how much capacity the system may remove automatically. If a check wants to remove more than half of the fleet, stop and alert a person.
Heartbeats and timeouts
Heartbeats work with the same trade-off. A peer sends a message every T seconds, and the monitor declares failure after k missed messages. Detection time is about T × k.
The simplest rule is a fixed timeout. It breaks down when network delay varies. Some systems use an adaptive detector, such as the phi accrual failure detector used by Cassandra and Akka. Instead of a yes or no answer, it computes a suspicion level from the recent history of arrival times. A threshold on that level decides failure, so a link that is normally slow gets more patience than a link that is normally fast.
A heartbeat has one more trap. If the heartbeat comes from a background thread, the thread can keep sending while the main application is deadlocked. Tie the heartbeat to real progress, for example by having the main work loop update a timestamp that the heartbeat sender reads and checks for staleness.
import threading
import time
last_progress = time.monotonic()
lock = threading.Lock()
def record_progress():
global last_progress
with lock:
last_progress = time.monotonic()
def heartbeat_allowed(max_stale=5.0):
with lock:
return time.monotonic() - last_progress < max_stale
def heartbeat_loop(send):
while True:
if heartbeat_allowed():
send("alive")
time.sleep(1.0)The work loop calls record_progress() after each unit of work. If it hangs, heartbeat_allowed() turns false within five seconds and the heartbeats stop, so the monitor sees the failure.
Where the monitor sits
The monitor is also a component that can fail, and its position in the network affects what it sees.
- A monitor in the same rack as its target may see a healthy server that users in other places cannot reach. A monitor far away may report failure for a problem on the path to the monitor.
- Using several independent monitors, and requiring a majority to agree before declaring failure, reduces false positives from one broken path.
- Run the monitor with redundancy as well. A single health checker is a single point of failure.
A partition, where a monitor loses contact with a healthy target, is the root of the split brain problem covered in a later chapter. Detection says "I cannot hear it," and that is weaker than "it is down."
Common errors
- Checking only that the port is open. A deadlocked application still accepts TCP connections.
- Checking shared dependencies in every instance. This causes the total outage described earlier.
- Probe timeout longer than the interval. Probes overlap, and results arrive out of order.
- Health endpoint that needs authentication or hits a slow path. The check fails for reasons unrelated to health.
- No alert on mass removal. The fleet shrinks silently until capacity runs out.
- Identical settings everywhere. A cache, a database, and a web server have different tolerance for delay, so they need different thresholds.
Exercise
A load balancer probes every 4 seconds with a 2 second timeout and marks a server unhealthy after 3 consecutive failures. What is the worst-case detection time? Then name one risk of lowering the threshold to 1.
Show answer
The worst case is 4 × 3 + 2 = 14 seconds. With a threshold of 1, a single slow response or dropped packet removes a healthy server, which causes false positives, flapping, and extra load on the remaining servers.
Exercise
Each web server's /health endpoint runs a query against a shared database. The database becomes slow and every check times out. What happens, and how would you change the design?
Show answer
The load balancer marks every web server unhealthy and the service goes fully offline, even though the web servers work. Make /health a shallow liveness check, keep dependency checks out of the removal decision (or use a readiness check limited to instance-local needs), alert on the database separately, and enable a fail-open or minimum healthy threshold setting.