Load balancer with health checks — distribute traffic and monitor health.
1const httpProxy = require("http-proxy");2const http = require("http");34class LoadBalancer {5 constructor() {6 this.proxy = httpProxy.createProxyServer({});7 this.backends = [];8 this.currentIndex = 0;9 }1011 addBackend(host, port) {12 this.backends.push({13 host,14 port,15 healthy: true,16 failures: 0,17 });18 }1920 getNextBackend() {21 const healthy = this.backends.filter(b => b.healthy);22 if (!healthy.length) return null;2324 const backend = healthy[this.currentIndex % healthy.length];25 this.currentIndex++;26 return backend;27 }2829 async healthCheck(backend, timeout = 5000) {30 return new Promise((resolve) => {31 const req = http.get(32 `http://${backend.host}:${backend.port}/health`,33 { timeout },34 (res) => {35 resolve(res.statusCode === 200);36 }37 );38 req.on("error", () => resolve(false));39 req.on("timeout", () => {40 req.destroy();41 resolve(false);42 });43 });44 }4546 startHealthChecks(interval = 10000) {47 setInterval(async () => {48 for (const backend of this.backends) {49 const healthy = await this.healthCheck(backend);50 if (healthy) {51 backend.failures = 0;52 backend.healthy = true;53 } else {54 backend.failures++;55 if (backend.failures >= 3) {56 backend.healthy = false;57 console.log(`Backend ${backend.host} marked unhealthy`);58 }59 }60 }61 }, interval);62 }63}6465// Usage66const lb = new LoadBalancer();67lb.addBackend("127.0.0.1", 3001);68lb.addBackend("127.0.0.1", 3002);69lb.startHealthChecks();7071http.createServer((req, res) => {72 const backend = lb.getNextBackend();73 if (!backend) {74 res.writeHead(503);75 return res.end("No backends available");76 }77 lb.proxy.web(req, res, {78 target: `http://${backend.host}:${backend.port}`,79 });80}).listen(80);