How we migrated our production NestJS fleet to Bun
Two webhooks benchmarks showed throughput gains of between 72 and 86 percent on Bun 1.3.14. Getting our backend services ready for production also meant working around socket failures and allowing for higher memory use.
We run six backend services for Anvil, our observability tool for Control4 driver developers. When we moved the first service, our GraphQL API, to Bun, it lasted about ten hours before Kubernetes killed it for exceeding its memory limit. The replacement pod grew until it hit the same limit. Health checks stayed green throughout, and the logs gave us no explanation.
By 1 August all six NestJS services were running Bun 1.3.14 in production, directly from TypeScript source. Getting there meant working around socket lifecycle failures that surfaced under traffic, including the connection retention behind those repeated restarts. This post covers that initial migration and the version-specific compromises we made.
The migration improved throughput on the services we benchmarked and removed the backend build step:
- Throughput rose by between 72 and 86 percent on the two webhooks endpoints we benchmarked, with better median and tail latency.
- Production cold-boot measurements overlapped those of the previous Node deployment, despite running from source.
- CI dependency installs dropped from minutes to seconds, and backend images no longer needed a build stage.
- Development and production used the same pinned runtime version for each backend service.
Our Next.js frontends stayed on Node 24. The Next application we benchmarked showed slower builds and worse server-rendering tail latency under Bun.
Control4 drivers are Lua programs running inside a controller's Director process. The Driverforge SDK captures telemetry from a driver on a developer's test controller, and an agent sends it over MQTT to our backend. The six services handle the GraphQL and internal APIs, MQTT ingestion, queued work, Stripe webhooks, and an MCP server for AI assistants. They run on Kubernetes, alongside Postgres, Redis, Mosquitto and the Ory stack.
How we ended up here
We started looking at Bun because changes were taking too long to get from a pull request into production. Dependency installation consumed minutes of every CI run, and our development servers ran compiled output, so each restart had to wait for compilation. A large shared library also pulled services into builds and deploys whenever any part of it changed, even when those services didn't use the changed code.
Bun addressed the installation and compilation delays. Using its package manager with a shared BuildKit cache brought CI installs down to seconds, while running TypeScript directly brought our development restart loop to about sixteen seconds. We dealt with the dependency graph separately by splitting the shared library into six libraries with narrower responsibilities.
That left development on Bun and production on Node. We wanted tests and local development to exercise the runtime we actually deployed, so the migration became a way to restore that match. Speed mattered, but we also needed to establish which services could run reliably on the same pinned version of Bun in both environments.
The rig
Unit tests couldn't tell us how the services would behave under sustained load or recover from an infrastructure outage on a different runtime. We built a set of container-based checks using real services and infrastructure:
- Soak. Apply sustained, realistic load for hours and sample resident memory (RSS) every minute. The worker ran for 11.3 hours without significant memory growth before we accepted it.
- Connection churn. Repeat the load with keep-alive disabled, opening a fresh connection for each request. Reusing connections can hide retention associated with opening and closing them; this check exposed growth that the keep-alive runs hadn't shown.
- Outage recovery. Kill the MQTT broker or Redis during traffic, hold the outage for thirty seconds, then restore it and check that the service resumes processing requests.
- Repeated reproductions. Run scripted failure scenarios that print
RECOVEREDorHUNG, making it possible to compare successive attempts without interpreting a graph.
The scripts came to about two hundred lines of shell. They exercised connection lifecycles and outage recovery against the same dependencies the applications use in production.
What it found
Connections stayed in Apollo's drain map
The GraphQL API's memory growth involved Apollo Server's connection-drain plugin. Its Stopper helper tracks requests in a map keyed by socket and is meant to remove each entry when the socket emits close. In our dependency-free reproduction on Bun 1.3.14, server sockets didn't emit that event after their connections closed. The operating system released the connections, but JavaScript cleanup tied to the event couldn't run.
Later testing identified a second obstacle in the same cleanup path. On the Bun versions we checked, http.Server and https.Server were the same constructor. Apollo used instanceof https.Server to choose where to attach its cleanup handler, so our plain HTTP server took the HTTPS branch and waited for secureConnection. That event never arrived. Requests still populated the map, but no close handler was attached to remove the entries. Both faults were present on 1.3.14; observing the missing event alone hadn't established the full cause of the retained map.
Removing the plugin from Apollo's plugin list didn't stop the leak. The NestJS Apollo driver constructs the drain helper unconditionally inside a factory, so we patched the package to remove that call. This bypassed both faults and stopped the observed growth, at the cost of disabling Apollo's HTTP drain helper. A regression spec checked that a dependency update didn't restore it. Connection churn exposed the growing map; the keep-alive test had repeatedly reused connections and missed it.
Redis reads never resumed after an outage
The outage test found a separate connection problem. After a thirty-second Redis outage, ingestion hung permanently, with every message handler blocked on a cache read. Only a process restart restored it. Left overnight, the pod accumulated sixty thousand waiting handler closures and 418 MB of retained heap while its health checks continued to pass.
The health indicator used a separate probe connection, which reconnected after the outage. Actual requests used a different connection that stayed dead, so the passing probe concealed the failure in the request path.
Swapping to a different Redis client didn't help: after one successful recovery, later cycles hung in exactly the same way, and neither library emitted an error event. The cause sat underneath both of them, in the socket lifecycle: in the failing runs on Bun 1.3.14, the connection became unusable without the client recognising that it needed to reconnect. Both libraries depended on socket events to start recovery.
We added a watchdog that pings the connection every ten seconds with a three-second timeout. A timeout forces the client to tear down the connection and reconnect. Liveness probes also make a timed round trip through the client used by requests. The scripted test went from HUNG in two of two trials to RECOVERED in three of three.
A silent hang, bisected to one line
We also tested running next build under Bun. In our monorepo it hung without an error on both Bun 1.3.14 and the 1.4 canary. With no diagnostic output, we started from a bare Next 16.1.7 application and added pieces of our configuration until we could reproduce it.
The six incremental reproductions included standalone output, middleware, Tailwind and the Sentry build wrapper. All six passed. Only the application inside our workspace failed. Stripping down that application's configuration eventually turned the hang into an error message.
In workspaces, Turbopack processes CSS in an external Node worker. Next constructs the worker's environment by folding process.execArgv into NODE_OPTIONS. Under Bun, execArgv contains ["--bun"]. Node rejects that flag with node: --bun is not allowed in NODE_OPTIONS and exit status 9, so the worker dies before connecting and Turbopack waits for it indefinitely.
Next already removes debugger flags at that point in getParsedNodeOptions(). Adding one more delete to remove the Bun flag let the application build in 166 seconds. We opened a PR with the reproduction and fix.
The numbers
We measured our own services on identical hardware or during production cluster reschedules.
For the webhooks service, we used autocannon with 50 concurrent connections:
| Endpoint | Bun 1.3.14 | Node 24 | Delta |
|---|---|---|---|
| GET health | 2,982 rps, p99 256ms | 1,736 rps, p99 342ms | +72% |
| POST with body parse and signature verification | 4,056 rps, p99 107ms | 2,178 rps, p99 192ms | +86% |
On production reschedules, cold boot from container start to application readiness took between 7.5 and 13.5 seconds for Bun running TypeScript source. Node running compiled output took between 5.2 and 14.8 seconds. Those ranges overlapped.
Our laptop measurements had suggested Bun booted three times slower. That difference came from transpiler caching behaviour on developer hardware and didn't appear in the cluster measurements.
Next.js performed worse under Bun in several of the measurements that mattered to us. Builds took 166 seconds against 81 seconds on Node. Server-side rendering had a modest improvement in mean latency, but p99 rose to 1,707 ms from 897 ms. API route handlers were twice as fast on Node, with little difference in memory use.
For the backend services, Bun's steady-state RSS was higher than Node's in every soak test. We found no memory savings in the workloads we measured and accounted for the increase in our capacity review.
What we decided
We pinned the backends to Bun 1.3.14 for the initial migration. The 1.4 canary emitted server-socket close events in our reproduction, but a smaller Nest and Apollo harness still showed memory growth of between 37 and 50 MB an hour under load and eventually ran out of memory. That was enough to hold back the upgrade. It didn't establish a separate runtime heap regression: the harness still included the drain helper, whose event selection was also a source of retention. Testing on 1.4.2 later isolated that second fault. The original canary result remains an observation of the combined stack, rather than proof of a defect in Bun's memory management.
The frontends stayed on Node in both environments. The Next patch let the workspace build finish under Bun. Our development setup still required Node for next dev, which encountered the same flag-forwarding problem. Moving production alone would have introduced a runtime mismatch within each frontend. Keeping them on Node gave every application the same runtime in development and production, even though the fleet used two runtimes.
We kept the simpler backend execution path. Running TypeScript source removed compilation from development restarts and from the backend image build. The package manager also reduced installation time. The other execution paths we tried didn't justify a switch; some failed to boot, and the successful trials didn't show a sufficient advantage.
The initial migration left us maintaining package patches, including the Apollo drain-helper removal, with specs checking them during dependency updates. The higher memory use fitted within the pod limits we deployed, but had to be included in the capacity budget. We also lost our application console: the REPL that boots a service's real module graph so we can call its providers from a prompt, much like rails console. It depends on node:repl, which failed in our Bun 1.3.14 setup. We accepted that loss until a move to 1.4 rather than running the console on a different version. The container checks took about a day to run for this migration.
At the end of the initial migration, all six backend services ran from source on Bun 1.3.14. The measured throughput gains came with higher memory use and workarounds to maintain; for the Next.js applications, the measurements supported staying on Node.
Bun 1.4 later changed that picture: we've since moved the whole stack, Next.js included, to Bun 1.4.