Load balancer — distributes incoming requests across multiple servers.
1const http = require("http");2const httpProxy = require("http-proxy");34const proxy = httpProxy.createProxyServer({});56const servers = [7 "http://localhost:3001",8 "http://localhost:3002",9 "http://localhost:3003",10];1112let currentIndex = 0;1314// Round-robin15function getNextServer() {16 const server = servers[currentIndex];17 currentIndex = (currentIndex + 1) % servers.length;18 return server;19}2021const lb = http.createServer((req, res) => {22 const target = getNextServer();23 proxy.web(req, res, { target }, (err) => {24 console.error("Proxy error:", err.message);25 res.writeHead(502);26 res.end("Bad Gateway");27 });28});2930lb.listen(80, () => console.log("Load balancer on port 80"));
Strategies:
For production, use: Nginx, HAProxy, or cloud LB.