SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
  • What are Load Balancers?
  • Load Balancing Algorithms
  • DNS Load Balancing
  • Anycast Routing
  • Layer 4 vs Layer 7 Load Balancers
  • Health Checks
  • Sticky Sessions
  • Global Load Balancing
  • Nginx and HAProxy
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Foundations/Load Balancing

Health Checks

How a load balancer finds out that a server is sick, and stops sending it traffic.

⏱ 11 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A health check is a small, regular test that asks a server "are you OK?". A load balancer uses the answers to stop sending traffic to a sick server and to start again when it recovers.

  • Active checks send a probe on a timer (for example GET /health every 5 seconds).
  • Passive checks watch real traffic and notice errors and timeouts.
  • A server is marked unhealthy only after several failed checks in a row, and healthy again after several good ones. This avoids flapping.

02Concept: What is it?

A load balancer shares requests between many servers. But servers fail: a process crashes, a disk fills up, a deployment goes wrong. If the balancer keeps sending requests to a dead server, a share of your users sees errors. The balancer needs a way to find out which servers are alive. That is a health check.

With active health checks the balancer itself calls each server on a timer. It can try to open a TCP connection (is anything listening?) or send an HTTP request to a path such as /health and check the status code (200 means OK). With passive health checks the balancer simply watches the real requests. If a server returns several errors or times out, it is taken out for a while.

To avoid reacting to a single blip, balancers use thresholds: for example "unhealthy after 3 failed checks" and "healthy again after 2 good checks". The interval, the timeout and the thresholds decide how fast you notice a failure, and how likely you are to flap.

The health check loop
⏱️Timerevery 5 s
→↓GET /health
🖥️Server200 OK or failure
→↓result
⚖️Load balancerhealthy list
→↓user traffic
👥Users
The balancer only sends user traffic to servers that are currently healthy.
🧠Detection time
The worst-case time to notice a failure is about interval × number of failed checks (plus timeouts). During that time some requests still go to the dead server.

03Real-Life Example

🍵The Waiter Checking the Kitchen Stations
A restaurant manager sends orders to five cooking stations. Every few minutes a waiter pokes his head in and asks each cook, "Ready?". If one station does not answer three times in a row (the cook has gone home), the manager stops sending it orders. When it answers twice in a row again, orders flow back. If the waiter marked a cook as gone after a single missed answer, orders would jump around every time someone was busy for a moment.
Restaurant
Health checks
The waiter asking 'Ready?'
An active health probe
How often the waiter asks
The check interval
How long the waiter waits for an answer
The probe timeout
Three missed answers in a row
The unhealthy threshold
Two good answers before orders return
The healthy threshold
The manager noticing late orders himself
A passive health check
A cook who is busy, not gone
A false alarm (a flapping server)
One server fails and recovers
✅Healthygets traffic
→↓3 failed checks
🚫Unhealthyremoved
→↓2 good checks
✅Healthyback in rotation

04Why Do We Need It?

🧯Hide failures from users
Once a sick server is out of rotation, users no longer hit it.
🔁Self-healing
A recovered server rejoins on its own, with no human step.
🚀Safe deployments
A new version only receives traffic after it reports ready.
📈Auto-scaling
New servers join the pool only when they pass their checks.
🛡️Higher availability
Together with redundancy, health checks are what make a spare server useful.
🔍Early warning
Check results and failure counts show a problem before the users complain.
Redundancy is useless if the balancer cannot tell which copy is broken. Health checks are how it finds out.

05Where Do We Use It?

⚖️Load balancers
Cloud balancers, Nginx, HAProxy and Envoy all run checks against their backends.
☸️Kubernetes
Liveness, readiness and startup probes decide whether to restart a container or send it traffic.
🌍DNS and global routing
DNS failover and global balancers check each region, and stop answering with a dead one.
🗄️Databases and caches
Clients and proxies check which node is primary and which replicas are alive.
🕸️Service discovery
A registry removes instances that stop sending heartbeats or fail checks.
🧰Orchestrators
Auto-scaling groups replace instances that fail their checks.

06Types / Parts / How It Works

Active and passive

Two ways to find a sick server
Active (probe)
⚖️Balancer
↓GET /health every few seconds
🖥️Server
Passive (watch traffic)
👥Real requests
↓errors and timeouts counted
⚖️Balancermarks it down
Many balancers use both: active checks find idle failures, passive checks react to real errors immediately.
TypeHow it worksGood and bad
ActiveThe balancer sends a probe on a timerFinds failures even with no traffic. Adds a little load and can be wrong if the probe differs from real use.
PassiveThe balancer counts real errors and timeoutsNo extra load and very realistic. The first real users hit the failure, and a server with no traffic is never tested.

What the probe does

CheckWhat it provesGood and bad
TCP connectSomething is listening on the portCheap and works for any protocol. A hung app can still accept connections.
HTTP statusThe app answers a request with 200Proves the web layer works. Needs a /health route.
HTTP with content checkThe answer contains the expected textCatches wrong answers. Easy to make too strict.
Shallow (local)The process is up and can serveFast and safe. Does not notice a broken database.
Deep (dependencies)The database, cache and others also workMore complete. A shared dependency problem can mark every server unhealthy at once.

Liveness, readiness and startup (Kubernetes names)

ProbeQuestionWhen it fails
LivenessIs the process stuck or dead?Restart the container
ReadinessCan it take traffic right now?Remove it from the balancer, but do not restart
StartupHas it finished starting?Wait before running the other probes, or restart if it never finishes
VisualizerCheck settings: how fast do we notice, and how often does the state flip?Use the clean crash first and make the interval longer. Then pick the flaky server and try 1 failed check against 3. Compare failed requests, time to notice and changes of mind.
What happens to the server?
What the server is really doing (green = working, red = down), second by second
What the load balancer does with it
0 s30 s60 s
in rotation, working in rotation, DOWN (requests fail) removed, down (safe) removed, working again (wasted)
Time to notice
10 s
after the failure at 20 s
Failed requests
100
10 req/s to this server
Changes of mind
2
removed or added back
Checks per minute
12
load on the server
The balancer noticed after 10 s (first failed check, then 2 more, 5 s apart). About 100 requests went to the dead server before that. After it recovered, the balancer waited for 2 good checks, so 5 s of a working server stayed unused.

Simplified: one health check at every multiple of the interval, and a failed check counts at that second (a real check that times out adds a little delay). The 10 requests per second is an illustrative share of the traffic. Fast checks find failures sooner but add load and make flapping more likely.

07How to Use It / Steps / Implementation

Setting up good health checks

  1. 1
    Add a dedicated endpoint
    Create a cheap route such as /health that returns 200 without heavy work, and does not need a login.
  2. 2
    Choose shallow or deep on purpose
    Make the main check shallow (is this process able to serve?). Check shared dependencies in a separate readiness check, with care, so one database problem does not remove every server.
  3. 3
    Pick interval and timeout
    A common start is an interval of a few seconds and a timeout shorter than the interval. Faster means quicker detection but more load and more flapping.
  4. 4
    Set thresholds
    Require several failures before removing a server (for example 2 to 3) and a few successes before adding it back. This calms short blips.
  5. 5
    Warm up new servers
    Use a start-up grace period or slow start, so a cold server is not hit with full traffic immediately.
  6. 6
    Drain before stopping
    On shutdown, fail the readiness check first, let in-flight requests finish, then stop. This is graceful draining.
  7. 7
    Watch the results
    Alert when many servers are unhealthy, when a server flaps, or when the healthy count drops below a safe minimum.
Example check settings (Nginx-style idea, example only)
interval         5s     # how often to probe
timeout          2s     # how long to wait for an answer
unhealthy after  3      # failed probes in a row
healthy after    2      # good probes in a row
path             /health  expect status 200
⚠️Do not let one dependency empty the pool
If every server's health check calls the same database, a database slowdown can turn all of them unhealthy at once. The balancer then has no healthy server and your whole site is down, even though the web servers are fine. Keep the load balancer check shallow, and handle dependency failures inside the app.

08Key Terms to Know

TermMeaning in easy words
Health checkA test that tells whether a server can handle traffic
Active checkA probe sent by the balancer on a timer
Passive checkJudging health from real request errors and timeouts
ProbeOne single health check request
IntervalThe time between two probes
TimeoutHow long to wait for a probe answer before counting a failure
Unhealthy thresholdNumber of failures in a row before a server is removed
Healthy thresholdNumber of successes in a row before a server is added back
FlappingA server that keeps switching between healthy and unhealthy
Liveness / readiness probeKubernetes checks: is it alive, and is it ready for traffic
Connection drainingLetting in-flight requests finish before a server is removed

09Pros, Cons and Trade-offs

✅ Pros
  • Users stop hitting dead servers
  • Recovered servers rejoin automatically
  • Safe rollouts and auto-scaling
  • Cheap to run
  • Gives early signals about problems
⚠️ Cons
  • Detection is never instant
  • A bad check causes false alarms or misses real failures
  • Too many probes add load
  • A deep check can take the whole pool down at once
  • More settings to tune and monitor

Trade-offs

ChoiceWe gainWe lose
Short intervalFaster detectionMore probe load and more chance of flapping
Long intervalCalm and cheapMore failed requests before a failure is noticed
Low unhealthy threshold (1)Removes bad servers quicklyA single blip removes a healthy server
High unhealthy threshold (5)Stable stateSlow to react to real failures
Shallow checkSafe and fastMisses broken dependencies
Deep checkCatches more problemsA shared dependency can remove every server
Illustrative detection time (interval 5 s)
Unhealthy after 1 failed checkabout 5 s
Unhealthy after 3 failed checksabout 15 s
Unhealthy after 5 failed checksabout 25 s
Fast but jumpy Balanced Calm but slow

10Common Problems and Mistakes

Common mistakes

  1. A check that always says OK. /health returns 200 even when the app cannot do its job.
  2. A check that is too deep. It calls the database, so a database blip removes every server.
  3. No thresholds. One missed probe removes a healthy server, and servers flap.
  4. A timeout longer than the interval. Probes overlap and the results become confusing.
  5. Sending full traffic to a cold server. It passes the check but is too slow, and fails under load.
  6. Restarting on a readiness failure. A busy but healthy app is killed for no reason and the problem gets worse.
  7. Everyone unhealthy, no plan. Decide the balancer's behaviour when no server is healthy: fail open (send to all) or return an error.

Things to watch

🌀Flapping
A server switching state again and again. Raise the thresholds and look for the real cause.
🐢Slow but alive
A server that answers the probe slowly may still hurt users. Consider latency and error rate in passive checks.
🐘Thundering herd
When a server returns, all pending traffic can flood it. Use slow start.
🔐Exposed health endpoint
Do not leak internal details in the health response, and limit who can call it.

11Real-World Examples

☁️Cloud balancers
Target groups and backend pools carry settings for path, interval, timeout and thresholds.
☸️Kubernetes pods
Readiness probes keep a starting pod out of the Service until it is ready.
🪽HAProxy and Nginx
Both support active checks, and passive failure counting for backends.
🌍Multi-region failover
Global balancers check each region and send users away from a failed one.
🛍️Rolling deployments
New versions get traffic only after they report ready, and old ones are drained first.
🧪Chaos testing
Teams kill servers on purpose to check that the balancer notices and recovers.
📝Note
Defaults for intervals and thresholds depend on the product and version. Read the documentation before relying on any number.
Mini case: a deploy without downtime
🆕New serverstarting, not ready
→↓ready check passes
⚖️Balanceradds it
→↓drain, then remove
🗑️Old serverfinishes in-flight requests
Not ready In rotation Draining
The balancer never sends traffic to a server that is starting or stopping.

12Related Topics to Read Next

What are Load Balancers?→

Health checks are what keep a balancer from sending users to a dead server.

Layer 4 vs Layer 7 Load Balancers→

Layer 7 can run real HTTP checks, Layer 4 usually checks the port.

Failover→

Health checks trigger the switch to a backup.

Heartbeats→

The same idea between machines in a cluster.

Single Point of Failure (SPOF)→

Checks are what make redundant servers useful.

Rolling Deployments→

Readiness checks make rollouts safe.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: regular tests that tell a balancer which servers can take traffic.
  • ✔Active: timed probes (GET /health). Passive: watch real errors.
  • ✔Detection time: about interval × failed checks, plus timeouts.
  • ✔Thresholds: several failures to remove, several successes to add back. Stops flapping.
  • ✔Shallow vs deep: keep the balancer check shallow, so one shared dependency cannot empty the pool.
  • ✔Kubernetes: liveness restarts, readiness controls traffic, startup waits.
  • ✔Deploys: warm up new servers (slow start), drain old ones.
  • ✔One line: “Ask often, act only on repeated evidence, and never let one shared dependency take every server out.”
← Previous
Layer 4 vs Layer 7 Load Balancers
Next →
Sticky Sessions