How do Bun and Node.js differ under the hood for API workloads?
Node.js pairs Google's V8 engine with libuv, a C library that provides the event loop and a thread pool for filesystem, DNS and some crypto work. Bun pairs Apple's JavaScriptCore (JSC), the engine behind Safari, with a runtime written mostly in Zig. Bun implements its HTTP server, bundler and many Node APIs natively and does not use libuv.
JIT tiers and startup
Both engines start code in an interpreter and promote hot functions to more aggressive compilers. V8 moves through Ignition, Sparkplug, Maglev and TurboFan. JSC moves through LLInt, Baseline, DFG and FTL. The tiers differ in when they promote functions and what they speculate on, so the same handler can warm up differently on each engine. JSC is generally tuned for fast startup, and Bun avoids some of Node's bootstrap work, so cold starts are usually shorter. That matters for CLIs, serverless functions and frequent restarts. It matters little for a long-lived API process.
Garbage collection
V8 uses a generational collector. A copying scavenger handles the young generation, and a mostly concurrent mark-compact collector handles the old heap. JSC's collector is concurrent and non-moving and scans the stack conservatively. These designs produce different pause patterns, fragmentation and resident memory, which is why RSS (resident set size, the memory the process actually holds) can differ noticeably between the runtimes for the same code.
Why the engine rarely decides request latency
A typical API request spends most of its time waiting on the database or downstream services. It then spends more time on JSON serialization, validation and middleware. Swapping the engine changes the CPU and memory cost of your JavaScript. It does not change the network round trip. The engine difference only shows up in end-to-end latency when CPU work in the runtime dominates the request.
Node.js Bun
+-----------------------------+ +-----------------------------+
| Your API handler (JS) | | Your API handler (JS) |
+-----------------------------+ +-----------------------------+
| V8 engine | | JavaScriptCore (JSC) |
| JIT: Ignition > Sparkplug | | JIT: LLInt > Baseline |
| > Maglev > TurboFan | | > DFG > FTL |
| GC: generational, copying | | GC: concurrent, non-moving |
| young + mark-compact old| | conservative stack scan |
+-----------------------------+ +-----------------------------+
| Node core + libuv: | | Zig runtime: native HTTP, |
| event loop + thread pool | | server, Node APIs, bundler |
| (fs, DNS, some crypto) | | no libuv |
+-----------------------------+ +-----------------------------+
| |
+----------------+-----------------+
|
v
+---------------------------------------------------------------+
| One API request in a long-lived process: where time goes |
| [====== DB / downstream I/O wait ======][ JSON ][valid][ mw ] |
| <---- network/DB time: same on both ---><- runtime differs -> |
+---------------------------------------------------------------+
Cold start: JSC tuning + lighter bootstrap -> Bun usually faster
(matters for CLIs/serverless, little for long-lived API servers)
Node.js (V8 + libuv) and Bun (JavaScriptCore + Zig runtime) differ in JIT tiers, garbage collection and startup. In a typical API request, those differences only affect the JavaScript CPU and GC share of the time, not the I/O wait that usually dominates.
How compatible is Bun with your existing Node.js service?
Compatibility is not a single yes-or-no property. Bun reimplements Node's built-in modules and npm resolution itself, and coverage varies by module and sometimes by individual function. A module can import cleanly and still behave differently on an edge case that only your traffic triggers.
Auditing a real service
Start by running your existing test suite under Bun, unchanged. Then write targeted tests for the areas where reimplementations most often diverge:
- Native addons. N-API addons target a stable ABI and are the most likely to load. Older addons written directly against V8's C++ API depend on engine internals that Bun does not share, so expect failures there.
node:worker_threadsandnode:vm. Test message passing, transfer lists, and context isolation, not just module loading.AsyncLocalStorage. Confirm that context survives timers, promise chains, and stream callbacks. Request-scoped logging and tracing depend on it.- Stream backpressure and error paths. Push data through slow consumers, abort requests mid-body, and check that
errorandcloseevents fire in the order your code expects. node:httpdetails. Frameworks rely on specifics such as header casing, keep-alive handling, and socket lifecycle events.
Lockfile checklist
Search the lockfile for:
- packages that build native addons (look for
node-gypor prebuilt binary fetchers) - packages with
postinstallscripts - APM and tracing agents, which often hook module loading or runtime internals
- libraries known to patch or reach into undocumented Node internals
Treat a passing smoke test as weak evidence. These gaps usually appear at runtime, under concurrency, or on error paths that a happy-path request never reaches.
// als-check.mjs: run with both runtimes and compare results:
// node als-check.mjs && bun als-check.mjs
import { AsyncLocalStorage } from 'node:async_hooks';
import { Readable, Writable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import assert from 'node:assert/strict';
const als = new AsyncLocalStorage();
const current = () => als.getStore()?.requestId;
async function simulateRequest(id) {
await als.run({ requestId: id }, async () => {
// Context must survive a timer hop
await new Promise((resolve) => setTimeout(resolve, 5));
assert.equal(current(), id, 'context lost after setTimeout');
// ...and a promise chain
await Promise.resolve().then(() => assert.equal(current(), id, 'context lost in .then'));
// ...and stream callbacks under backpressure (slow consumer, tiny buffer)
const slowSink = new Writable({
highWaterMark: 1,
write(_chunk, _enc, cb) {
assert.equal(current(), id, 'context lost in stream write');
setTimeout(cb, 1);
},
});
await pipeline(Readable.from(['a', 'b', 'c', 'd']), slowSink);
});
}
// Interleave requests so leaked or crossed contexts show up
await Promise.all(['req-1', 'req-2', 'req-3'].map(simulateRequest));
const runtime = globalThis.Bun ? 'bun' : 'node';
console.log(`AsyncLocalStorage checks passed on ${runtime}`);
A standalone script you run under both Node and Bun that checks whether AsyncLocalStorage context survives timers, promise chains, and backpressured stream callbacks across concurrent requests, so any behavioral difference between the runtimes shows up as a failed assertion.
How do you run a fair Bun vs Node.js benchmark?
Start with the same application code on both runtimes. Use one framework that runs on both, the same database driver, and the same logger, so the only variable is the runtime. Run each in a container with identical CPU and memory limits, pinned to the same host class. A runtime that looks faster with spare cores can behave differently once it is throttled to two vCPUs.
Use handlers that resemble production. A useful endpoint parses a JSON body of realistic size, runs auth middleware that verifies a signed token, and makes one or two database round trips. Hello-world and vendor benchmarks transfer poorly because they measure only the HTTP fast path. In a real request, TLS termination, driver serialization, connection pooling, and synchronous logging can account for most of the latency, and those costs do not shrink just because routing got faster.
Warm up before you measure. JIT compilation, connection pools, and caches all need time to settle, so discard the first few minutes of each run.
Generate load open-loop: send requests at a fixed arrival rate whether or not earlier ones have returned. Closed-loop tools wait for a response before sending the next request. When the server stalls, they stop sending, so the slow period never gets recorded. This is called coordinated omission.
Report p50, p99, and p99.9 latency together with sustained throughput at a stated request rate. As an illustrative estimate, a runtime might win p50 by 30% yet lose p99.9 under garbage collection pressure.
Flawed setups can mislead you in either direction. A hello-world test can push you toward a migration that brings no gain, while an unwarmed or closed-loop test can rule out a runtime that would actually help.
#!/usr/bin/env bash
# Same app code, framework, driver and logger in both images; only the runtime differs.
set -euo pipefail
RATE=2000 # fixed arrival rate (req/s), the same for both runtimes
DURATION=300s # measured window
WARMUP=120s # discarded: JIT, connection pools and caches settle here
for IMAGE in api-node:bench api-bun:bench; do
# Identical limits; pin to dedicated cores so the load generator cannot steal CPU.
docker run -d --rm --name sut \
--cpus=2 --cpuset-cpus=2,3 --memory=1g \
-p 8443:8443 \
-e DATABASE_URL=postgres://bench:placeholder@db.internal:5432/bench \
"$IMAGE"
sleep 10
# wrk2 (its binary is named wrk) is open-loop: -R fixes the arrival rate, and
# latency is measured from the intended send time, which corrects for
# coordinated omission. post.lua sends a realistic JSON body and a signed bearer token.
# Warm-up pass: output deliberately thrown away.
taskset -c 4-7 wrk -t4 -c128 -d"$WARMUP" -R"$RATE" \
-s post.lua > /dev/null
# Measured pass over TLS, through auth middleware and real database calls.
# --latency prints the full percentile distribution (p50, p99, p99.9).
taskset -c 4-7 wrk -t4 -c128 -d"$DURATION" -R"$RATE" --latency \
-s post.lua \
| tee "results-${IMAGE%%:*}-${RATE}rps.txt"
docker stop sut
done
# Compare p50, p99 and p99.9 at the same RATE. Check that achieved throughput
# matched RATE before comparing latency, then repeat at higher rates to find
# where each runtime's tail latency starts to climb.
Runs both runtimes under identical container CPU and memory limits, discards a warm-up pass, then drives a realistic TLS and JSON endpoint with wrk2's fixed-rate open-loop load and records p50, p99 and p99.9 latency at the same stated request rate.
How should you measure memory use in Bun and Node.js?
Idle footprint is the number most comparisons quote, and it tells you the least. A freshly started process has not yet filled its heap, warmed its JIT, or grown connection pools and caches. What matters is memory under the load you benchmarked, held long enough for the garbage collector to settle into its steady-state pattern.
Compare RSS, not heap figures
Node.js runs on V8 and Bun on JavaScriptCore. Their garbage collectors are different, and so are their heap layouts and the way they account for memory. A "heap used" value from one runtime does not measure the same thing as the similarly named value from the other. Process RSS, or the container's cgroup memory usage, counts everything the kernel attributes to the workload. That includes native allocations, buffers and JIT code. It is the most comparable number, and it is also the number your orchestrator acts on. Use runtime heap metrics to diagnose problems inside one runtime, not to compare the two.
Run soak tests for hours
Record RSS at fixed intervals over several hours at constant load. You are looking for a plateau. Slow, steady growth points to a leak, fragmentation, or caches that never stop growing. These problems are invisible in a five-minute run.
Correlate memory with tail latency
Plot p99 latency on the same timeline as memory. Periodic latency spikes that line up with heap growth and drops are GC pauses. Mean latency hides them.
Test near the limit
Set container memory limits close to what you would use in production. Watch how each runtime behaves as usage approaches the ceiling. One runtime may collect more aggressively and keep running. Another may keep growing until the kernel's OOM killer terminates it. A lower idle number does not tell you which of these you will get.
#!/usr/bin/env bash
# Soak-test memory sampler: run the Node and Bun builds of the same API under
# identical container memory limits, then record container memory over hours.
# Drive constant load at both containers with your load tool in parallel.
set -euo pipefail
LIMIT=512m # set close to your production limit
INTERVAL=30 # seconds between samples
DURATION=$((6*3600)) # 6 hours; short runs hide slow growth
OUT=soak-memory.csv
# Placeholder image names; both serve the same API on different host ports.
docker run -d --name api-node --memory="$LIMIT" -p 3000:3000 example/api:node
docker run -d --name api-bun --memory="$LIMIT" -p 3001:3000 example/api:bun
echo "timestamp,container,mem_usage,mem_percent" > "$OUT"
end=$(( $(date +%s) + DURATION ))
while [ "$(date +%s)" -lt "$end" ]; do
ts=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# Container (cgroup) memory as seen by the engine: comparable across runtimes,
# unlike each runtime's own heap metrics.
docker stats --no-stream \
--format '{{.Name}},{{.MemUsage}},{{.MemPerc}}' api-node api-bun \
| sed "s/^/${ts},/" >> "$OUT"
sleep "$INTERVAL"
done
# Did either runtime hit the limit and get OOM-killed instead of collecting harder?
for c in api-node api-bun; do
echo "$c OOMKilled=$(docker inspect --format '{{.State.OOMKilled}}' "$c")" \
"restarts=$(docker inspect --format '{{.RestartCount}}' "$c")"
done
# Next step: plot mem_usage against p99 latency from your load tool on one timeline
# and look for a plateau (healthy) versus steady growth (leak, fragmentation, caches).
A shell script that runs the Node and Bun builds under the same container memory limit, samples container memory usage at fixed intervals over a multi-hour soak, and checks whether either container was OOM-killed.
When does Bun deliver real gains, and when should you avoid it?
Memory behaviour is one input, but the shape of your workload decides whether a switch pays off at all.
Bun's gains concentrate where the runtime itself is the bottleneck. Startup time matters most in three cases: serverless functions, CLI-style batch jobs, and pods launched during autoscaling bursts. In each, a cold start adds directly to request latency or job wall-clock time. Tooling is the other clear win. Bun's package installer, bundler and test runner can shorten CI and local feedback loops even if production stays on Node.js. CPU-bound paths that use Bun's native implementations, such as HTTP parsing or hashing, may also run faster.
Most APIs, however, spend their time waiting on a database or another service. Illustrative estimate: if a request takes 40 ms and 35 ms of that is a query, halving runtime overhead saves about 2.5 ms, which is likely lost in network jitter.
| Workload | Likely outcome | Why |
|---|---|---|
| Serverless, short-lived jobs | Meaningful gain | Startup is a large share of total time |
| CI install/test | Meaningful gain | Tooling speed, low production risk |
| CPU-bound handlers | Possible gain | Native implementations of hot paths |
| I/O-bound CRUD API | Marginal | Database and network dominate |
Avoid Bun if your service depends heavily on native addons, because not every addon built for Node loads cleanly. Avoid it if you rely deeply on APM agents, which often hook Node internals. Avoid it if you have strict LTS or compliance requirements that Node's published release schedule satisfies. Above all, profile before migrating. Many teams pay the full migration cost and then find the latency they hoped to cut was never in the runtime.
What does running Bun in production cost in operations and engineering time?
Runtime choice also determines which tools on-call engineers can use during an incident.
| Concern | Node.js | Bun |
|---|---|---|
| Release process | Published LTS schedule with long maintenance windows | Frequent releases, no equivalent LTS track |
| Profiling and heap analysis | V8 CPU profiles and heap snapshots; mature DevTools and third-party analyzers | WebKit-protocol inspector; JavaScriptCore heap format, so V8-oriented tools don't apply |
| OpenTelemetry auto-instrumentation | Broad coverage via module patching hooks | Partial; some instrumentations may not attach |
| Incident knowledge | Large body of postmortems and answered questions | Smaller and less tested against edge cases |
The observability gap can go unnoticed. When an auto-instrumentation fails to hook a module, nothing errors. Traces just lose spans, and you find out mid-incident. After any migration, compare span counts per route between runtimes in staging.
Running both runtimes doubles base images, CI matrix entries, CVE triage and runbooks. Code that calls Bun-only APIs such as Bun.serve or bun:sqlite cannot fall back to Node without a rewrite. Keep those calls behind thin adapters.
Bun can save time on fast installs and quick test runs, even if production stays on Node.
Illustrative estimate (assumed numbers, not a benchmark). Annual net hours = (CI runs/day × minutes saved/run × workdays ÷ 60) − (patch cycles/year × hours/cycle). Assume 40 runs/day, 2 minutes saved, 230 workdays, 24 cycles and 3 hours per cycle: (40 × 2 × 230 ÷ 60) − (24 × 3) ≈ 307 − 72 = 235 hours.
How can you adopt Bun incrementally, and who should stay on Node.js?
That comes to roughly 235 engineering hours a year (illustrative estimate). This is why tooling, not the production runtime, is the cheapest place to start.
Use Bun for tooling first. Run bun install, bun test and package scripts through Bun in CI and on laptops while production stays on Node.js. You get faster feedback loops and users are never exposed to runtime differences. Keep a CI job that runs the suite under Node.js too, because a test passing on Bun does not prove the same code behaves correctly on Node.js.
Canary one stateless service. Put Bun instances behind the same load balancer as the Node.js pool and send them a small weighted share of traffic. Compare p99 latency, error rate and RSS on identical requests. Choose a stateless service so shifting traffic back is instant, with no sessions or data to migrate.
Keep code runtime-agnostic. Write business logic against fetch, Request/Response, Web Streams and node: modules that both runtimes implement. Isolate any Bun-specific server or file APIs behind a thin adapter. That way you can switch runtimes by changing configuration instead of rewriting code.
Maintain a tested rollback. Build the Node.js image on every commit and rehearse moving traffic back to it. A rollback path you have never exercised is a hope, not a plan.
| Condition | Stay on Node.js | Pilot Bun |
|---|---|---|
Native addons, APM agents, or niche node: APIs |
✓ | |
| Greenfield service on Web-standard APIs | ✓ | |
| Cold-start-sensitive workloads (CLIs, scale-to-zero) | ✓ | |
| No capacity to own compatibility testing | ✓ | |
| Team willing to triage runtime bugs upstream | ✓ |
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 production, 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.
- Reviewers see the exact diff and the list of affected services up front, so approval is a decision rather than an investigation.
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.
- Per-service approve/reject means a bad shared value can be refused where it would break something, before it is live.
- 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.