Overview
TheHealthChecker class runs periodic health checks against all backend servers in the pool. It sends HTTP requests to each backend and updates their health status based on responses, ensuring the load balancer only routes traffic to healthy servers.
Constructor
Creates a new HealthChecker instance with the specified backend pool and check interval.The backend pool to monitor. The health checker will verify all backends in this pool and update their health status.
The interval between health check cycles in milliseconds. Default is 5000ms (5 seconds).
Methods
start()
Starts the periodic health check loop.- Performs an immediate health check on all backends
- Starts the periodic health check loop at the configured interval
- No-op if health checker is already running
- Runs asynchronously without blocking
stop()
Stops the periodic health check loop.- Sets the running flag to false
- The health check loop will terminate after the current cycle completes
- Does not interrupt in-flight health check requests
checkAll()
Performs a health check on all backends in the pool.Promise<void> - Resolves when all health checks complete.
Behavior:
- Retrieves all backends from the pool (both healthy and unhealthy)
- Sends HTTP requests to each backend concurrently
- Uses AbortController with 3-second timeout per request
- Marks backends healthy if response status is OK (2xx)
- Marks backends unhealthy if response fails or times out
- Logs health status for each backend
AbortController timeout mechanism
The health checker usesAbortController to implement request timeouts, ensuring health checks don’t hang indefinitely:
- Creates an
AbortControllerfor each health check request - Sets a 3-second timeout that calls
controller.abort() - Passes the abort signal to the fetch request
- If timeout triggers, the fetch is aborted and throws an error
- If fetch completes first, the timeout is cleared
- Aborted or failed requests result in the backend being marked unhealthy
Health check criteria
Backend marked healthy when:- HTTP request completes within 3 seconds
- Response status is in the 2xx range (
res.ok === true)
- HTTP request times out (>3 seconds)
- Response status is outside 2xx range
- Network error or connection refused
- Any other fetch error occurs
Usage examples
Basic setup
Custom check interval
Manual health check
Starting and stopping
Complete load balancer setup
Related
- BackendPool - Backend collection managed by health checker
- LoadBalancer - Uses health status for routing decisions
- ProxyHandler - Also marks backends unhealthy on proxy errors