Planning Load Balancer in Node.js
The user wants a load balancer implementation in Node.js to distribute requests evenly across multiple servers. I should provide code that demonstrates this, likely using the http module. I'd implement a round-robin approach to manage multiple backend servers. The balancer will listen on port 8000 and route requests to servers on ports 3001 and 3002. I might keep it simple by using core modules only and suggest features like a round-robin counter and health checks, focusing on even distribution without extra complexity.Structuring Load Balancer Implementation
I need to consider headers and methods while handling requests. It’s important to mention limitations like no HTTPS termination and timeouts, but I can be concise since the user isn't asking for production-grade code.
I’ll provide examples including how to run backend servers and the main load balancer code. I’ll focus on a round-robin approach for distributing requests evenly across backend servers. For sample backends, I can use server IDs like 3001, 3002, and 3003 with simple hello messages.Implementing Load Balancer Code
I’m creating a load balancer in index.js using the http module. I’ll set up an array of target servers, allowing requests to rotate through them with a round-robin approach. The balancer listens on port 8000 and proxies client requests to the designated backend servers.
I'll handle errors, ensuring proper responses are sent back to clients when a proxy error occurs. While I thought about adding keepAlive settings or cluster scaling, I'll focus on just the basics since the user didn't ask for those extra features.Crafting Load Balancer Response
I'll start directly with the answer since the user didn't specify a need for extensive explanations. The word "Implement" implies they want code, so I’ll provide that along with some brief instructions. I aim for a moderate level of detail to meet their expectations without overwhelming them. Keeping it concise, I’ll present the important elements clearly and directly, ensuring that the code is straightforward and easy to understand. Let's move forward with that! Below is a minimal round‑robin load balancer in Node.js that forwards incoming HTTP requests evenly across multiple backend servers.
1. Example backend servers
Create three simple HTTP servers (you can put this in backend.js and run three instances with different ports, or just duplicate and change the port).
// backend.js
const http = require('http');
const PORT = process.env.PORT || 3001;
http.createServer((req, res) => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Response from server on port ${PORT}\n`);
}).listen(PORT, () => {
console.log(`Backend server running on port ${PORT}`);
});
Run three instances in different terminals:
PORT=3001 node backend.js
PORT=3002 node backend.js
PORT=3003 node backend.js
2. Round-robin load balancer
Create load-balancer.js:
// load-balancer.js
const http = require('http');
const targets = [
{ host: 'localhost', port: 3001 },
{ host: 'localhost', port: 3002 },
{ host: 'localhost', port: 3003 },
];
let currentTarget = 0;
const server = http.createServer((clientReq, clientRes) => {
// Pick target using round-robin
const target = targets[currentTarget];
currentTarget = (currentTarget + 1) % targets.length;
const options = {
hostname: target.host,
port: target.port,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers,
};
// Forward request to target server
const proxyReq = http.request(options, (proxyRes) => {
// Pass status and headers through
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
// Stream response body
proxyRes.pipe(clientRes, { end: true });
});
proxyReq.on('error', (err) => {
console.error('Proxy error:', err.message);
if (!clientRes.headersSent) {
clientRes.writeHead(502, { 'Content-Type': 'text/plain' });
}
clientRes.end('Bad Gateway');
});
// Stream request body to target
clientReq.pipe(proxyReq, { end: true });
});
const LB_PORT = 8000;
server.listen(LB_PORT, () => {
console.log(`Load balancer listening on port ${LB_PORT}`);
});
Run the load balancer:
node load-balancer.js
Now send requests to the load balancer (port 8000):
curl http://localhost:8000
curl http://localhost:8000
curl http://localhost:8000
curl http://localhost:8000
You should see responses alternating between ports 3001, 3002, and 3003, confirming even (round‑robin) distribution.
If you want, I can extend this with health checks, HTTPS support, or sticky sessions.