Considering Equitable Distribution
I've been focusing on the core requirement of this load balancer: even distribution of requests. My current thinking revolves around practical implementations within Node.js. I'm exploring various algorithms and data structures that can ensure fair allocation. Also, I'm considering potential edge cases like server availability changes.
Refining the Architecture
I'm now zeroing in on the essential building blocks. The core components are taking shape: an entry point, backend servers, round robin logic for distributing requests, and the proxying mechanism. I'm leaning toward using the Node.js built-in http module for performance, though I'll also explore the http-proxy library to see if it simplifies things.
Clarifying Implementation Path
I've decided to prioritize a comprehensive and readily understandable solution. While I'll use http-proxy for the primary approach, mirroring industry practices, I'll also implement the core proxy logic using the standard http.request module to demonstrate a deeper understanding. This dual approach gives a great educational basis for understanding how these proxies function. The focus is now on the step-by-step implementation.
Defining Round-Robin Mechanism
I've formulated the logic for the round-robin selection. Now, I have a clear plan for the server selection process. I'll maintain an index, incrementing it with each request and using the modulo operator to ensure it cycles through the available servers. The underlying structure looks clean and functional. I also drafted a sample round-robin balancing logic within my scratchpad.
Finalizing Code Structure
I'm now putting together the final code structure. I'm focusing on creating two key files: backends.js to simulate servers and loadbalancer.js for the primary logic. I'm prioritizing error handling and header forwarding. I've also incorporated the http module for a zero-dependency implementation, focusing on a copy-paste-ready example.
Building Proxy Logic
I'm now focusing on the proxy logic implementation using the http module. I've defined the configuration details, including ports for backend and load balancer servers. The core of this lies within http.request where I'm setting the hostname, port, path, method, and headers. Within the callback, I'm now implementing header writing and request body piping. Error handling will also be essential.
Resolving Error Conditions
I'm tackling error handling and edge cases more directly now. I've realized I need to account for potential unhandled exceptions, and will provide two files, one for backends and another for the load balancer. For round-robin, I've simplified the index increment to (i + 1) % length for clarity. I'm also refining the stream logic, using req.pipe(connector, { end: true }); for more robust request handling.
Here is a complete implementation of a Load Balancer in Node.js using the Round Robin algorithm.
I have split this into two parts:
- The Backend Servers: A script to spin up multiple "worker" servers.
- The Load Balancer: The server that accepts traffic and distributes it.
We will use the native http module (zero external dependencies) so you can understand exactly how the request piping works.
Part 1: The Backend Servers (server.js)
First, let's create a file to simulate multiple web servers running on ports 3001, 3002, and 3003.
// server.js
const http = require('http');
const ports = [3001, 3002, 3003];
ports.forEach((port) => {
http.createServer((req, res) => {
// Simulate some work
const message = `Hello from Backend Server on port: ${port}\n`;
// Logging to console to see which server handled the request
console.log(`Server ${port} handled request: ${req.method} ${req.url}`);
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end(message);
}).listen(port, () => {
console.log(`Backend server started on port ${port}`);
});
});
Part 2: The Load Balancer (lb.js)
Now, the load balancer. This runs on port 8080. It accepts requests and forwards them to the backend servers one by one.
// lb.js
const http = require('http');
// Configuration
const SERVERS = [
{ host: 'localhost', port: 3001 },
{ host: 'localhost', port: 3002 },
{ host: 'localhost', port: 3003 }
];
let currentServerIndex = 0;
const server = http.createServer((clientReq, clientRes) => {
// 1. Implement Round Robin Strategy
const target = SERVERS[currentServerIndex];
currentServerIndex = (currentServerIndex + 1) % SERVERS.length;
console.log(`Proxying request to: ${target.host}:${target.port}`);
// 2. Prepare options for the target request
const options = {
hostname: target.host,
port: target.port,
path: clientReq.url,
method: clientReq.method,
headers: clientReq.headers
};
// 3. Make the request to the target backend server
const proxyReq = http.request(options, (proxyRes) => {
// 4. Forward the response headers and status code back to the client
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers);
// 5. Pipe the response body from backend -> client
proxyRes.pipe(clientRes, { end: true });
});
// Handle errors (e.g., if a backend server is down)
proxyReq.on('error', (e) => {
console.error(`Error connecting to ${target.host}:${target.port}`);
clientRes.writeHead(502, { 'Content-Type': 'text/plain' });
clientRes.end('Bad Gateway: Backend server is down');
});
// 6. Pipe the request body from client -> backend
// (This ensures POST data/uploads are forwarded correctly)
clientReq.pipe(proxyReq, { end: true });
});
const LB_PORT = 8080;
server.listen(LB_PORT, () => {
console.log(`Load Balancer running on port ${LB_PORT}`);
});
How to Run It
-
Open Terminal 1 (Backends):
node server.js
You should see "Backend server started on port..." for all 3 ports.
-
Open Terminal 2 (Load Balancer):
node lb.js
You should see "Load Balancer running on port 8080".
-
Test it:
Open a third terminal or use your browser. Send multiple requests to the load balancer (port 8080).
Using curl:
curl http://localhost:8080
curl http://localhost:8080
curl http://localhost:8080
curl http://localhost:8080
Expected Output
Terminal Client:
Hello from Backend Server on port: 3001
Hello from Backend Server on port: 3002
Hello from Backend Server on port: 3003
Hello from Backend Server on port: 3001
Load Balancer Console:
Proxying request to: localhost:3001
Proxying request to: localhost:3002
Proxying request to: localhost:3003
Proxying request to: localhost:3001
Key Concepts Used
-
Round Robin Algorithm:
The line currentServerIndex = (currentServerIndex + 1) % SERVERS.length; ensures that we cycle through the array indefinitely (0, 1, 2, 0, 1, 2...).
-
Streams & Piping (.pipe()):
Node.js is event-driven. Instead of downloading the entire request body and then sending it, we connect the incoming data stream directly to the outgoing stream.
clientReq.pipe(proxyReq): Forwards data sent by the user (e.g., JSON in a POST request) to the backend.
proxyRes.pipe(clientRes): Forwards the HTML/JSON sent by the backend back to the user.
-
Reverse Proxy:
This implementation effectively acts as a Reverse Proxy. The client doesn't know which server (3001, 3002, etc.) actually handled the request; it only knows about port 8080.