skills/bun-guides-http-cluster/SKILL.md
Run multiple HTTP servers concurrently via the "reusePort" option to share the same port across multiple processes
npx skillsauth add jarle/bun-skills Bun Start a cluster of HTTP serversInstall this skill globally with one command. Works with Claude Code, Cursor, and Windsurf.
3 of 9 scanners reported clean
Some scanners were skipped, did not run, or reported a non-clean status. Review each row below.
Run multiple HTTP servers concurrently via the "reusePort" option to share the same port across multiple processes
To run multiple HTTP servers concurrently, use the reusePort option in Bun.serve() which shares the same port across multiple processes.
This automatically load balances incoming requests across multiple instances of Bun.
import { serve } from "bun";
const id = Math.random().toString(36).slice(2);
serve({
port: process.env.PORT || 8080,
development: false,
// Share the same port across multiple processes
// This is the important part!
reusePort: true,
async fetch(request) {
return new Response("Hello from Bun #" + id + "!\n");
},
});
After saving the file, start your servers on the same port.
Under the hood, this uses the Linux SO_REUSEPORT and SO_REUSEADDR socket options to ensure fair load balancing across multiple processes. Learn more about SO_REUSEPORT and SO_REUSEADDR
import { spawn } from "bun";
const cpus = navigator.hardwareConcurrency; // Number of CPU cores
const buns = new Array(cpus);
for (let i = 0; i < cpus; i++) {
buns[i] = spawn({
cmd: ["bun", "./server.ts"],
stdout: "inherit",
stderr: "inherit",
stdin: "inherit",
});
}
function kill() {
for (const bun of buns) {
bun.kill();
}
}
process.on("SIGINT", kill);
process.on("exit", kill);
Bun has also implemented the node:cluster module, but this is a faster, simple, and limited alternative.
development
Using TypeScript with Bun, including type definitions and compiler options
development
Learn how to write tests using Bun's Jest-compatible API with support for async tests, timeouts, and various test modifiers
testing
Learn how to use snapshot testing in Bun to save and compare output between test runs
testing
Learn about Bun test's runtime integration, environment variables, timeouts, and error handling