Back to results for “Advanced Node.js”
Node.js › HTTP & Web Servers

How would you implement a simple TCP-level proxy or load balancer in Node.js using the net module, distinct from an HTTP-level reverse proxy?

Advanced

Answer

The node:net module operates at the raw TCP level, below HTTP, letting you build a proxy that forwards raw byte streams between a client and a backend server without parsing or understanding HTTP semantics at all -- useful for protocols other than HTTP, or for a lightweight load-balancing layer that simply distributes TCP connections across backend servers without needing to inspect or modify the application-level protocol being carried over those connections.
const net = require('node:net');

const servers = [{ host: 'backend1', port: 4000 }, { host: 'backend2', port: 4000 }];
let current = 0;

net.createServer((clientSocket) => {
  const backend = servers[current++ % servers.length]; // simple round-robin
  const backendSocket = net.connect(backend, () => {
    clientSocket.pipe(backendSocket);
    backendSocket.pipe(clientSocket);
  });
}).listen(3000);
Real-world example A team building a lightweight load balancer for a non-HTTP TCP-based protocol (like a custom binary protocol between internal services) implements it using the raw net module, since an HTTP-aware reverse proxy like Nginx wouldn't understand or correctly route the underlying protocol being used.

Common follow-ups: Why would you choose this raw TCP approach over an HTTP-level reverse proxy for an application that does happen to use HTTP?;What features (like HTTP header inspection or path-based routing) does this simple TCP proxy approach necessarily give up compared to an HTTP-aware proxy?