const http = require('http');
const url = require('url');
// Configuration: List of backend servers
const backends = [
{ host: 'localhost', port: 3001 },
{ host: 'localhost', port: 3002 },
{ host: 'localhost', port: 3003 }
// Add more servers as needed
];
let currentIndex = 0; // Round-robin index
// Create the load balancer server
const loadBalancer = http.createServer((clientReq, clientRes) => {
// Select the next backend server (round-robin for even distribution)
const backend = backends[currentIndex % backends.length];
currentIndex++;
console.log(`Forwarding request to ${backend.host}:${backend.port}${clientReq.url}`);
// Prepare proxy request options
const proxyOptions = {
hostname: backend.host,
port: backend.port,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
// Create proxy request to backend
const proxyReq = http.request(proxyOptions, (proxyRes) => {
// Forward the response status and headers
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
// Stream the response body back to client
proxyRes.pipe(clientRes);
});
// Handle proxy request errors (e.g., backend down)
proxyReq.on('error', (err) => {
console.error(`Proxy error to ${backend.host}:${backend.port}:`, err.message);
clientRes.statusCode = 502; // Bad Gateway
clientRes.setHeader('Content-Type', 'text/plain');
clientRes.end('Backend server error');
});
// Pipe the client request body to proxy request (handles POST/PUT etc.)
clientReq.pipe(proxyReq);
});
// Handle client connection errors
loadBalancer.on('error', (err) => {
console.error('Load balancer error:', err.message);
});
// Start the load balancer on port 3000
const PORT = 3000;
loadBalancer.listen(PORT, () => {
console.log(`Load balancer running on http://localhost:${PORT}`);
console.log(`Backend servers:`, backends.map(b => `${b.host}:${b.port}`).join(', '));
});
console.log('To test:');
console.log('1. Start backend servers (e.g., simple HTTP servers on ports 3001, 3002, 3003)');
console.log('2. Send requests to http://localhost:3000');
console.log('Example backend server (save as server.js and run with node server.js 3001):');
console.log(`
const http = require('http');
const PORT = process.argv[2] || 3001;
http.createServer((req, res) => {
console.log(\`Request to \${PORT}: \${req.url}\`);
res.end(\`Hello from server on port \${PORT}! Time: \${new Date().toISOString()}\\n\`);
}).listen(PORT, () => console.log(\`Server on \${PORT}\`));
`);
How it works:
- Round-robin distribution: Cycles through backends sequentially for even load (e.g., req1→3001, req2→3002, req3→3003, req4→3001, etc.).
- Full HTTP proxy: Forwards method, headers, URL, and body (via piping for streaming efficiency).
- Error handling: Returns 502 if a backend fails.
- No external dependencies: Pure Node.js (http, url modules).
- Configurable: Edit the
backends array. Supports different hosts/ports.
Testing:
- Start 3 backend servers:
node server.js 3001 # (use the example code above)
node server.js 3002
node server.js 3003
- Run the load balancer:
node loadbalancer.js
- Test with
curl http://localhost:3000/test -v (repeat to see rotation in logs).
This is production-ready for basic use. For advanced features (HTTPS, health checks, sticky sessions), consider libraries like http-proxy.