The user wants to implement a load balancer in Node.js.
This is a classic networking/system design problem.
I need to provide a working, understandable, and reasonably robust example.
Core Components of a Load Balancer:
Server: Needs to listen for incoming client requests.
Upstream Servers (Targets): A list of servers to forward requests to.
Algorithm: A strategy for picking the next server. The prompt specifies "distributes requests evenly," which strongly suggests Round Robin.
Proxying: The mechanism to forward the request to the target and send the response back to the client.
Technology Stack:
Node.js (required).
Built-in modules: http, https.
Third-party modules: http-proxy is the industry standard for this in Node.js because handling raw socket piping, headers, and errors manually is error-prone. However, for an educational example, I should probably mention it but also show how to do it simply or use a popular library.
Actually, showing a manual implementation using http.request is good for understanding, but using http-proxy is more practical for a "real-world" feel. Let's stick to http-proxy for the main implementation because it handles the complexities of proxying (websockets, headers, chunked encoding) correctly.
Alternatively, I can write a simple proxy from scratch to show how it works under the hood. Let's do a from-scratch version for educational value, but maybe mention libraries like http-proxy or express-http-proxy.
Decision: I will implement a Round Robin load balancer using the native http module to keep dependencies low and logic clear, but I'll add comments about production-grade libraries.
Step-by-Step Implementation Plan:
Define the Upstream Servers: An array of objects/strings representing the backend servers (e.g., { host: 'localhost', port: 3001 }).
The Round Robin Logic: Maintain a currentServerIndex. Every time a request comes in, pick servers[currentServerIndex], then increment the index (modulo length).
The Proxy Logic:
Receive request req and response res from the client.
Identify target.
Create a new request to the target.
Pipe the client request body to the target request.
Pipe the target response body back to the client response.
Handle errors (e.g., if a backend server is down).
Code Structure:
javascript
const http = require('http');
// Configuration
const servers = [
{ target: 'http://localhost:3001' },
{ target: 'http://localhost:3002' },
{ target: 'http://localhost:3003' }
];
let current = 0;
// The Handler
const server = http.createServer((clientReq, clientRes) => {
// 1. Select target (Round Robin)
const target = servers[current];
current = (current + 1) % servers.length;
// 2. Log it
console.log(`Proxying request to ${target.target}`);
// 3. Create proxy request
// Need to parse target URL to construct options for http.request
const parsedTarget = new URL(target.target);
const options = {
hostname: parsedTarget.hostname,
port: parsedTarget.port,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers // Forward headers
};
const proxyReq = http.request(options, (proxyRes) => {
// 4. Forward response headers and status
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
// 5. Pipe response body
proxyRes.pipe(clientRes);
});
// Error handling
proxyReq.on('error', (e) => {
console.error(`Problem with request: ${e.message}`);
clientRes.writeHead(502); // Bad Gateway
clientRes.end();
});
// 6. Pipe request body
clientReq.pipe(proxyReq);
});
server.listen(8080);
Refining the Code:
The manual implementation above works for basic HTTP.
I should also provide a setup to test it. I can't just give the load balancer code; the user needs servers to balance.
I will write a small script that spawns 3 dummy backend servers and 1 load balancer.
Addressing "Evenly":
Round Robin is the standard interpretation of "evenly" for stateless requests.
Least Connections is another way, but harder to implement without keeping state. Round Robin is sufficient for this prompt.
Bonus/Production considerations:
Health checks (removing dead servers).
Retries.
Sticky sessions.
Mentioning http-proxy.
Final Output Structure:
Concept: Briefly explain Round Robin.
Prerequisites: Node.js installed.
The Implementation: Provide a complete, single-file script (or two files) that runs the LB and the backends.
Explanation: Walk through the code (Proxying, Round Robin logic).
Running it: Instructions on how to test.
Production Note: Mention http-proxy or Nginx.
Let's write the code clearly.
I'll create two blocks of code:
load-balancer.js: The main logic.
backend-servers.js: A helper to simulate backends (for testing purposes).
Actually, putting them in one file is easier for a "Copy-Paste-Run" experience, but separating them is more realistic. I will provide the Load Balancer code as the primary answer, and a small helper script to generate traffic/backends for testing.
Wait, better approach: Write the Load Balancer, then write a simple script to start 3 servers, then the Load Balancer connects to them.
The Load Balancer Code:
Dependencies: http (native).
Logic:
servers array.
currentIndex variable.
http.createServer.
http.request to target.
pipe streams.
Handling Headers:
When proxying, we need to copy headers from clientReq to proxyReq.
We also need to handle the host header specifically sometimes, though usually passing it through is fine for simple apps.
We need to pipe clientReq into proxyReq.
Handling Errors:
If the backend is down, the proxyReq emits an error. We should catch this and return 502 Bad Gateway or 503 Service Unavailable.
Structure of the response:
Introduction: Mentioning the Round Robin algorithm.
The Code: A robust load-balancer.js using native Node.js modules.
Testing Setup: A helper script to spawn dummy servers so the user can see it working.
Explanation: How the piping and index logic works.
Let's refine the code to be very clean.
javascript
// 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((req, res) => {
// Round Robin Selection
const target = targets[currentTarget];
currentTarget = (currentTarget + 1) % targets.length;
console.log(`Request received. Forwarding to ${target.host}:${target.port}`);
// Prepare options for the proxy request
const options = {
hostname: target.host,
port: target.port,
path: req.url,
method: req.method,
headers: req.headers
};
// Create request to the backend server
const proxyReq = http.request(options, (proxyRes) => {
// Send the backend response status and headers back to the client
res.writeHead(proxyRes.statusCode, proxyRes.headers);
// Pipe the data stream from backend response to client response
proxyRes.pipe(res);
});
// Handle errors (e.g., backend server is down)
proxyReq.on('error', (err) => {
console.error(`Error connecting to ${target.host}:${target.port}: ${err.message}`);
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain' });
res.end('Bad Gateway');
}
});
// Pipe the client request body to the backend request
req.pipe(proxyReq);
});
server.listen(8080, () => {
console.log('Load Balancer listening on port 8080');
});
This looks solid. It uses native modules, handles streams correctly (which is the "Node way"), handles basic errors, and implements the requested algorithm.
I will also add a section on "Testing" by providing a small script that spins up the 3 dummy servers. This ensures the user can verify the solution immediately.
Summary of content to generate:
Approach: Round Robin.
Main Code: The Load Balancer.
Helper Code: The Backend Servers.
How it works: Explanation of streams and round robin.
One edge case: req.headers. Sometimes the host header needs to be updated to match the target, otherwise some strict backends might reject it. However, for a generic implementation, passing headers as-is is usually fine. I will add a comment about it.
Let's double check the req.pipe(proxyReq) inside http.createServer.
Yes, req is a readable stream (incoming request). proxyReq is a writable stream (outgoing request to backend). This pipes the body (POST/PUT data). Correct.
proxyRes is a readable stream (incoming from backend). res is a writable stream (outgoing to client). Correct.
The logic is sound. I will proceed with generating the response.
Here is a complete, runnable implementation of a Load Balancer in Node.js.
This example uses the Round Robin algorithm, which is the most common method for distributing requests evenly. It cycles through a list of servers one by one.
Prerequisites
Ensure you have Node.js installed.
1. The Implementation
Save the following code as load-balancer.js.
This script uses Node's built-in http module to act as a reverse proxy. It intercepts incoming requests, forwards them to one of the target servers, and sends the response back to the client.
javascript
const http = require('http');
const httpProxy = require('http-proxy');
// 1. Define the backend servers
const servers = [
{ host: 'localhost', port: 3001 },
{ host: 'localhost', port: 3002 },
{ host: 'localhost', port: 3003 }
];
// 2. Create a proxy server instance
const proxy = httpProxy.createProxyServer({});
// 3. Round Robin State
let currentServerIndex = 0;
// 4. Create the Load Balancer Server
const server = http.createServer((req, res) => {
// Select the target server using Round Robin
const target = servers[currentServerIndex];
// Log the routing
console.log(`Forwarding request ${req.url} to ${target.host}:${target.port}`);
// Update index for the next request (modulo operator loops it back to 0)
currentServerIndex = (currentServerIndex + 1) % servers.length;
// Forward the request
proxy.web(req, res, { target: target }, (error) => {
// Handle errors (e.g., if a backend server is down)
console.error(`Error forwarding to ${target.port}:`, error.message);
if (!res.headersSent) {
res.writeHead(502, { 'Content-Type': 'text/plain' });
res.end('Bad Gateway: Backend server unavailable');
}
});
});
// 5. Start listening
const PORT = 8080;
server.listen(PORT, () => {
console.log(`Load Balancer running on http://localhost:${PORT}`);
console.log(`Distributing to:`, servers.map(s => `http://${s.host}:${s.port}`).join(', '));
});
2. The Dependency (Optional but Recommended)
While you can write a raw HTTP proxy from scratch using http.request, it is complex to handle edge cases (like chunked encoding, headers, and websockets) perfectly.
The code above uses the industry-standard http-proxy library.
Install it first:
bash
npm init -y
npm install http-proxy
3. Testing the Load Balancer
To see the load balancer in action, you need to start the backend servers that it will distribute traffic to.
Step A: Create Dummy Servers
Create a file named backend.js:
javascript
const http = require('http');
const port = process.argv[2]; // Get port from command line argument
const server = http.createServer((req, res) => {
// Simulate a bit of work
setTimeout(() => {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(`Response from Server running on Port ${port}`);
}, 100);
});
server.listen(port, () => {
console.log(`Backend server listening on port ${port}`);
});
Step B: Run everything
Open 4 separate terminal windows.
Terminal 1 (Backend 1):node backend.js 3001
Terminal 2 (Backend 2):node backend.js 3002
Terminal 3 (Backend 3):node backend.js 3003
Terminal 4 (Load Balancer):node load-balancer.js
Step C: Generate Traffic
Use your browser or a tool like curl to hit the Load Balancer multiple times: