What is a backend pool?
The backend pool is a collection of servers that can handle incoming requests. TheBackendPool class maintains the list of backends and their current health status.
Each backend consists of a URL and a health flag indicating whether it’s available to receive traffic.
Backend structure
Backends are represented as simple objects with two properties:src/types/types.ts
url- The backend server endpoint (e.g.,http://localhost:3001)health- Boolean flag indicating if the server is operational
BackendPool implementation
TheBackendPool class manages the collection of backends:
src/balancer/pool.ts
Key methods
getAllBackends()
Returns all backends regardless of health status. This is used by the health checker to monitor all servers, including those currently marked as unhealthy.The health checker needs to poll all backends, not just healthy ones, so it can detect when failed servers recover.
getHealthyBackends()
Returns only backends withhealth: true. This is the critical method used by the load balancer when selecting a server to handle a request.
markHealthy(url)
Marks a specific backend as healthy. Called by the health checker when a server passes its health check:markUnhealthy(url)
Marks a specific backend as unhealthy. Called by the health checker when a server fails its health check:Initialization
When the backend pool is created, all servers start as healthy:Health state tracking
The backend pool maintains mutable state for each server. When health checks run:Health status updated
Based on the check results,
markHealthy() or markUnhealthy() is called for each backend.Load balancer queries healthy servers
getHealthyBackends() filters the list to only include available servers.The backend pool acts as the single source of truth for server health status. Both the health checker and load balancer reference the same pool instance.
Thread safety considerations
The current implementation assumes single-threaded JavaScript execution. In the Node.js event loop:- Health checks update backend health asynchronously
- Load balancing queries happen synchronously
- No race conditions occur due to JavaScript’s single-threaded nature
If you port this to a multi-threaded environment, you’ll need to add synchronization around health state updates.