What is the real difference between Bun and Node.js for an HTTP API?

Both runtimes execute JavaScript and expose a Node-style module system, but their engines and I/O layers differ.

Aspect Node.js Bun
JavaScript engine V8 JavaScriptCore
Native layer C++ with libuv for the event loop and I/O Zig and C++, with its own event loop and socket handling
Native HTTP API node:http Bun.serve, plus a node:http compatibility layer
Tooling Runtime, with npm as a separate tool Runtime, package manager, bundler and test runner in one binary

Bun's published throughput numbers mostly come from Bun.serve. A handler receives a web-standard Request and returns a Response, and the native layer writes the response to the socket with little JavaScript in between. Node's node:http builds IncomingMessage and ServerResponse objects on top of streams. That design is flexible, but each request carries more JavaScript-side work.

Your code gets Bun's fastest path only if it calls Bun.serve directly or uses a framework built on it. Express, Fastify and other code written against node:http run through Bun's compatibility layer, which has to emulate Node's objects and stream semantics. That emulation adds overhead and narrows the gap you would see in a hello-world test.

Node is the default for production APIs because of its long-term support releases, broad native-addon support and mature profiling and observability tooling. Bun gets considered because it offers fast startup, runs TypeScript without a separate build step, installs packages quickly and could, in principle, replace a multi-tool toolchain with a single binary.

           NODE.JS                                  BUN
+---------------------------+   +-------------------+ +-------------------+
| Express / Fastify handler |   | Bun.serve handler | | Express / Fastify |
+-------------+-------------+   | Request ->        | | handler           |
              |                 | Response          | +---------+---------+
              v                 +---------+---------+           |
+---------------------------+             |                     v
| node:http                 |             |           +-------------------+
| IncomingMessage /         |             |           | node:http compat  |
| ServerResponse on streams |             |           | (emulates Node    |
+-------------+-------------+             |           |  objects/streams) |
              |                           |           +---------+---------+
              v                           | fast path           |
+---------------------------+             v                     v
| V8 engine                 |   +-----------------------------------------+
+-------------+-------------+   | JavaScriptCore engine                   |
              |                 +--------------------+--------------------+
              v                                      |
+---------------------------+   +--------------------v--------------------+
| libuv: event loop + I/O   |   | Zig/C++ native layer: event loop,       |
| (C++ native layer)        |   | socket handling, response writes        |
+-------------+-------------+   +--------------------+--------------------+
              |                                      |
              v                                      v
       [ TCP socket ]                         [ TCP socket ]

Request paths in Node.js and Bun: Bun.serve handlers reach Bun's native Zig/C++ layer with little JavaScript in between, while Express, Fastify and other node:http code on Bun goes through a compatibility layer that emulates Node's objects and streams.

Why do hello-world benchmarks mislead on Bun vs Node performance?

A minimal HTTP benchmark returns a fixed string from a single route. That workload exercises very little: accepting the connection, parsing the request line and headers, and writing a short response. Bun's server is heavily optimized for exactly this path, so the gap over Node can look large. A production API spends most of each request somewhere else. It deserializes and validates a JSON body, runs auth middleware, emits structured logs, calls a database driver and waits on downstream services. Most of that time is spent in network round-trips or in library code, and the runtime's HTTP layer has little effect on either.

Illustrative estimate: take a 20 ms request where 18 ms is database and downstream I/O and 2 ms is runtime overhead. If a faster runtime halves that overhead, the request drops to 19 ms, a saving of about 5%. That is real, but a single extra query or a slow index changes the total far more.

Engineers also distort results in several common ways:

  • Running the load generator on the same host. The client competes with the server for CPU, so you partly measure the load tool itself.
  • Skipping warm-up. Both runtimes use JIT compilation, and cold numbers reflect compilation work, not steady-state performance.
  • Comparing different framework paths. Bun's built-in server against Express on Node compares two frameworks as well as two runtimes.
  • Reporting peak RPS alone. Throughput without p99 latency and error rate hides queueing and dropped requests under load.

How do you run a reproducible Bun HTTP server benchmark?

Start by pinning exact runtime versions in your Dockerfile and recording bun --version and node --version with every result set. Both runtimes ship performance changes often, so an unversioned number cannot be reproduced. Build both images from the same base, and apply the same CPU and memory limits to each. A runtime given more cores or a looser memory ceiling will appear faster for reasons that have nothing to do with the runtime.

Run the load generator on a separate machine, or pin it to cores the server cannot use. If both compete for the same CPU, the benchmark measures contention. Warm up each server before recording so that JIT compilation and connection pools have settled. Then hold a fixed request rate and report throughput, p50, p99, p99.9 latency, error rate, and resident memory together.

Tier What runs What it isolates
1. Minimal Bare handler, static response Raw runtime and HTTP stack overhead
2. Framework Same handler behind your real router and middleware Cost of your framework, validation, logging
3. Representative Real endpoint, real database, realistic payload serialization What users actually experience

Expect the gap between runtimes to shrink from tier 1 to tier 3. As database round-trips and JSON work take up more of each request, runtime overhead becomes a smaller share of total latency. If the tier 1 gap mostly disappears by tier 3, switching runtimes will not change your production latency much.

Finish with soak tests that run for hours, not minutes. JavaScriptCore and V8 use different garbage collectors and heap strategies. Memory growth, GC pauses that show up in p99.9, and slow leaks only appear under sustained load.

#!/usr/bin/env bash
# Run the same fixed-rate benchmark against Bun and Node with identical limits.
# Assumes images built FROM the same base, with pinned runtime versions.
# Load generator is wrk2 (its binary is named wrk and adds -R for fixed rate).
set -euo pipefail

RATE=2000          # fixed requests/sec: compare latency at equal load
URL_PATH=/health   # tier 1; switch to framework and DB endpoints for tiers 2 and 3
OUT=results/$(date +%Y%m%d-%H%M%S)
mkdir -p "$OUT"

for RT in bun node; do
  IMAGE=bench-$RT:pinned
  # Record the exact runtime version next to every result set.
  docker run --rm "$IMAGE" "$RT" --version > "$OUT/$RT.version"

  # Same CPU and memory limits for both runtimes. Server gets cores 0-1 only.
  docker run -d --name "srv-$RT" --cpuset-cpus=0-1 --cpus=2 --memory=512m \
    -p 3000:3000 "$IMAGE"
  sleep 5

  # Load generator is pinned to cores the server cannot use.
  # Warm-up pass: let JIT and connection pools settle. Output is discarded.
  taskset -c 4-7 wrk -t4 -c64 -d60s -R"$RATE" "" > /dev/null

  # Measured pass: --latency prints the percentile distribution (p50/p99/p99.9).
  taskset -c 4-7 wrk -t4 -c64 -d300s -R"$RATE" --latency \
    "" > "$OUT/$RT.wrk.txt"

  # Resident memory at the end of sustained load.
  docker stats --no-stream --format '{{.Name}} {{.MemUsage}}' "srv-$RT" > "$OUT/$RT.mem"

  docker rm -f "srv-$RT" > /dev/null
done

echo "Results in $OUT"
# For soak tests, raise -d to several hours and sample docker stats on an interval.

A shell harness that pins runtime versions, gives Bun and Node identical container limits, isolates the wrk2 load generator on separate cores, warms up, then records fixed-rate latency percentiles and memory for each runtime.

How do you audit Node compatibility before switching to Bun?

Treat the audit as a gate. If it fails, the benchmark doesn't matter.

  1. Inventory node: built-ins. Search the codebase and the resolved dependency tree, not only your own imports. Look closely at less common modules: vm, worker_threads, async_hooks (especially AsyncLocalStorage, which tracing and request-scoped logging libraries rely on), cluster, and inspector. These are the modules most likely to be missing, partial, or subtly different, and the differences often appear as wrong behavior rather than a thrown error. For example, a broken context propagation produces log lines without trace IDs.

  2. Find native addons. Bun runs on JavaScriptCore, not V8. Addons built on N-API have a reasonable chance of working. Addons that bind directly to V8 APIs, or use older wrappers around them, generally will not. Check each .node binary's origin and how it was built.

  3. Check install-time and runtime detection. Look for postinstall scripts that compile or download platform binaries. Bun's package manager doesn't run every dependency's lifecycle scripts by default, so a missing artifact can go unnoticed until first use. Also search for packages that branch on the runtime, since they may take a less-tested code path under Bun.

  4. Run the full test suite under Bun before benchmarking. Incompatibilities surface at runtime on specific paths: an error handler, a rarely used serializer, a retry branch. A passing smoke test proves little.

  5. Plan for drift. Most packages run CI only against Node. A routine dependency update can break on Bun without anyone upstream noticing, so keep running your suite under Bun on every update. Expect to be the first to find these breaks.

#!/usr/bin/env bash
# Pre-migration audit: scans your code AND node_modules. Prints findings for review; does not decide pass/fail.
set -uo pipefail
DIRS="src node_modules"

echo '== 1. Less common built-ins (behavior may differ silently) =='
grep -rlE "(require\(|from )['\"](node:)?(vm|worker_threads|async_hooks|cluster|inspector)['\"]" \
  --include='*.js' --include='*.cjs' --include='*.mjs' --include='*.ts' $DIRS | sort -u

echo '== 2. Native addons (compiled .node binaries and build files) =='
find node_modules -name '*.node' -type f
find node_modules -name binding.gyp -not -path '*/node_modules/*/node_modules/*'
# nan wraps V8 APIs directly (high risk); node-addon-api uses N-API (better odds)
grep -rlE '"(nan|node-addon-api)"' --include=package.json node_modules | sort -u

echo '== 3a. Install-time scripts that may not run under bun install =='
find node_modules -name package.json -not -path '*/test/*' -print0 |
  while IFS= read -r -d '' f; do
    jq -r --arg f "$f" \
      'select(.scripts.install or .scripts.postinstall) | "\($f): \(.scripts.install // .scripts.postinstall)"' \
      "$f" 2>/dev/null
  done

echo '== 3b. Packages that branch on the runtime =='
grep -rlE 'process\.versions\.bun|typeof Bun' --include='*.js' --include='*.cjs' --include='*.mjs' $DIRS | sort -u

echo '== 4. Full existing suite under Bun (not a smoke test) =='
# --bun makes the script and its node-shebang binaries run on Bun instead of Node
bun install
bun --bun run test

A bash audit script that inventories risky node: built-ins, native addons, install scripts and runtime-detection branches across your code and dependency tree, then runs the existing test suite under Bun; rerun it on every dependency update to catch drift.

What production readiness concerns go beyond the request path?

Most tracing and APM agents were built around Node internals. They patch modules at load time, hook the CommonJS loader, and rely on async_hooks or AsyncLocalStorage to carry trace context across await boundaries. If any of those behave even slightly differently, the agent can still start, emit spans, and report no errors while the spans are wrong. Deploy the agent in staging and check three things: spans nest correctly under concurrent load, trace IDs propagate across outbound HTTP calls and queue consumers, and database spans actually appear. A trace that looks complete for a single request can fall apart at 50 concurrent requests.

Debugging needs the same check. Bun runs on JavaScriptCore, not V8, so V8-specific flags, heap snapshot workflows, and the profiling scripts your team already uses may not apply. Before an incident forces the question, confirm that you can capture a heap snapshot from a running production-like process and that you know which tool opens it.

Test graceful shutdown directly. Send SIGTERM while requests are in flight. The server should stop accepting connections, drain the in-flight work, close database pools, and exit before the orchestrator's kill deadline.

Run soak tests that last days, not minutes, inside containers that use your real CPU and memory limits. Garbage collection heuristics differ between engines, and V8 tuning flags such as --max-old-space-size do nothing on Bun. Track RSS against the cgroup limit, not just heap size.

Node has a long production history and a predictable LTS cadence. With Bun, expect some failure modes to have no existing write-up, so budget time to build that incident-response knowledge yourself.

// shutdown.ts: graceful SIGTERM handling for a Bun HTTP server.
// Test it by sending SIGTERM (e.g. `kill -TERM <pid>`) while a load test is running.

// Placeholder for your real DB pool. Swap in your driver's close/end call.
const pool = { async end() { /* close connections */ } };

const server = Bun.serve({
  port: 3000,
  async fetch(req) {
    // Simulate slow in-flight work so draining is observable.
    await Bun.sleep(2000);
    return new Response("ok");
  },
});

// Stay under the orchestrator's kill deadline (e.g. 30s terminationGracePeriod).
const SHUTDOWN_DEADLINE_MS = 25_000;
let shuttingDown = false;

async function shutdown(signal: string) {
  if (shuttingDown) return; // ignore repeated signals
  shuttingDown = true;
  console.log(`${signal} received, draining`);

  // Hard stop if draining hangs, so we exit before SIGKILL arrives.
  const timer = setTimeout(() => {
    console.error("drain deadline exceeded, forcing exit");
    process.exit(1);
  }, SHUTDOWN_DEADLINE_MS);

  // stop(false): refuse new connections, let in-flight requests finish.
  await server.stop(false);
  await pool.end();
  clearTimeout(timer);
  process.exit(0);
}

process.on("SIGTERM", () => void shutdown("SIGTERM"));
process.on("SIGINT", () => void shutdown("SIGINT"));

A minimal Bun server that handles SIGTERM by refusing new connections, letting in-flight requests finish, closing the database pool, and forcing an exit before the orchestrator's kill deadline.

What are the lower-risk alternatives to a full Bun migration?

You don't have to swap runtimes in one step. The cheapest entry point keeps Node in production and uses Bun only in the toolchain: bun install as the package manager, bun test for the suite, or bun run for build and maintenance scripts. These can make local and CI loops faster, and a problem there costs you a slow pipeline, not an outage. Confirm that the dependency tree Bun resolves matches what Node loads in production, so tests don't pass against a different graph.

When you do move a runtime, pick one stateless, low-risk service, such as an internal read API or a webhook receiver. Avoid anything that owns a session, a queue consumer, or a payment path. Put it behind a canary with automatic rollback tied to error rate and tail latency. If the rollback depends on someone noticing a dashboard, it won't happen in time.

How cheap that rollback stays depends on your code. If you build on web-standard APIs such as fetch, Request/Response, and Web Streams, the same handlers run on both runtimes, so reverting is a deploy, not a rewrite. If you adopt Bun-only APIs like Bun.serve, you may get more throughput, but every such call is code you must port back. Runtime-agnostic code keeps the exit open but can leave some performance unused. Decide that trade-off deliberately for each service.

Before any of this, check whether the runtime is even your bottleneck. Many APIs spend most of their request time waiting on the database. In that case, query optimization, caching, and connection pooling usually reduce latency more than a runtime change, and they carry no compatibility risk.

When should you choose Bun, and when should you stay on Node?

The decision rests on one question: does the gain you measured on your own workload pay for the one-time migration and for the cost of maintaining a second runtime?

Factor Favors Bun Favors Node
Hot path CPU-bound JavaScript such as serialization, validation, templating I/O-bound, mostly waiting on the database or upstream services
Startup time Matters: cold starts, short-lived jobs, aggressive autoscaling Amortized over long-running processes
Native dependencies None, or pure-JS replacements available Native addons compiled against Node
Observability Logging and basic metrics APM agents, async context tracing, diagnostics tied to Node internals
Dependency coverage Passes your compatibility audit Key libraries tested only on Node
Benchmark result Margin clearly exceeds run-to-run variance Tier-3 gain falls within noise

Migration cost includes the audit, new container images, CI changes and fixes for incompatibilities. Maintenance cost continues after that. Any dependency upgrade can reintroduce a compatibility gap. On-call engineers also have to learn a second set of failure modes. A throughput gain that saves a few instances on a small service rarely covers either cost. The same gain across a large, CPU-heavy fleet can.

Bun's tooling can save engineering time without any production risk. Its package installer and test runner can shorten local and CI feedback loops while the deployed artifact still runs on Node. Keep a test job that runs on Node, because passing tests under Bun does not prove the code behaves the same in production.

For I/O-bound APIs, the database work from the previous section usually returns more than any runtime switch.

How OneEnv can help

Disclosure: OneEnv is the product behind this blog.

OneEnv (oneenv.io) is a workspace-based governance platform for the things services share — environment variables, database structure, API routes and validation rules. A change to a shared value is staged on a branch, reviewed once, and then every affected service explicitly approves or rejects it before it goes live, so you can see who a change touches before it ships instead of finding out in production.

Applied to bun vs node performance, this is where it helps:

Saves time

  • Every service that inherits a shared value is listed in one place, so nobody searches repos and chats to find out who is affected.
  • One review per branch replaces coordinating each team separately; each service still keeps its own approve/reject.
  • Changing a route's URL or method automatically notifies the services that consume it — no hunting through repos for callers.

Saves cost

  • Fewer production incidents and rollbacks caused by a shared value, route or column changing under a consumer unannounced.
  • Less duplicated configuration to maintain: one shared definition inherited by many services.
  • Consumers learn about a breaking change at review time rather than from production errors.
  • OneEnv has a free plan (1 workspace, unlimited services and members, full governance), so trying it costs nothing.

These are qualitative benefits, not measured results — how much you save depends on how many services share the value.

Want to try it? Start at oneenv.io.