Bun Rewrote Its Codebase in Rust — 11 Days, 652 Commits, $165K, and a War With Zig's Creator

·5 min readtechnologyyoutube

TL;DR: Bun rewrote 535K lines of Zig to Rust in 11 days using 64 parallel Claude agents at $165K. The rewrite delivered compiler-enforced memory safety, a 20% smaller binary, and 19 semantic regressions from syntactically identical but semantically different code. Zig creator Andrew Kelly argued the rewrite was never technical — it was a relationship breakdown dressed as engineering.

It started with a Hacker News thread that Jared Smith, creator of Bun, called an overreaction. He had posted that Bun might rewrite from Zig to Rust, and the community responded with 302 comments. Jared’s own words: “This whole thread is an overreaction. 302 comments about code that does not work. We have not committed to rewriting. There’s a very high chance all of this code gets thrown out completely.”

Then, on May 3rd, the code started landing. By May 14th: 6,502 commits (merges excluded), +1,009,272 lines added, CI green across all six platforms. Build #54,202 went green. The rewrite was done.

The Problem: Memory Bugs That Style Guides Can’t Catch

Bun was built in Zig — a systems language with no garbage collector, no borrow checker, no constructors or destructors. Memory management is manual: every allocation tracked, cleanup handled through explicit defer statements at each call site. Works fine until your codebase sits on top of JavaScriptCore, a garbage-collected engine. JavaScript values constantly cross the boundary into manually-managed Zig memory.

The bug catalog from v1.3.14 was specific and recurring:

  • heap-use-after-free in node:zlib via async .reset() + .write()
  • use-after-free in node:http2 via re-entrant JS callbacks invalidating stream pointers
  • use-after-free in UDPSocket.send() via valueOf() detaching ArrayBuffer mid-send
  • memory leaks in crypto.scrypt, SSLWrapper.init, tlsSocket.setSession(), fs.watch()
  • double-free in CSS parser with vendor-prefixed background-clip
  • race condition in MessageEvent from GC marker thread

The existing safety net was custom-patched Zig with ASAN support, ReleaseSafe builds on Windows, 24/7 Fuzzilli fuzzing, and end-to-end memory leak tests. It wasn’t enough.

“In Zig, memory safety was enforced by style guides and code review,” Jared wrote. “In Rust, the borrow checker would enforce it at compile time.” Or more directly: “Compiler errors are a better feedback loop than a style guide.”

The Preparation: PORTING.md and LIFETIMES.tsv

Before any agents touched the code, Jared spent ~3 hours with Claude designing two guiding documents.

PORTING.md mapped Zig patterns to Rust equivalents — std.ArrayList → Vec, defer → Drop, error union → Result. It became the public-facing signal (ended up on Hacker News) and the internal reference used by all 64 Claude instances during mechanical translation.

LIFETIMES.tsv specified which struct fields carry which Rust lifetimes. The generation was adversarial: one Claude analyzed every struct field across every file and traced control flow, proposed lifetimes, then two adversarial reviewers checked them, then a fixer applied feedback, then the result serialized to TSV for the other Claudes to reference. Jared manually reviewed both documents before the agents started.

The team made two strategic decisions:

  1. Big bang over incremental — “An incremental rewrite adds temporary code that you hope gets deleted eventually, and would be painful in the short-medium term.”
  2. Faithful over idiomatic — Translate Zig’s architecture into Rust, not redesign the system. Refactor to idiomatic Rust after v1.4 ships.

The Workflow: 4 Shards, 64 Claudes, 1,300 Lines/Minute

The trial run started with 3 files: 1 implementer → 2 adversarial reviewers → 1 fixer. Workflow issues arrived immediately at scale.

The first attempt looped over all 1,448 .zig files in one worktree. After ~2 minutes: Claude instances ran git stash, git stash pop, git reset HEAD --hard — stepping on each other. Separate worktrees per Claude would exhaust disk space (Bun’s repo is too large).

Jared solved it with 4 workflow shards × 4 git worktrees, each shard running 16 Claude instances:

  • Banned commands: git stash, git reset, cargo, anything slow
  • Allowed: commit specific files only
  • Peak throughput: ~1,300 lines/minute, 58 commits/minute, 695/hour

Jared also forgot to increase the default IOPS on the EC2 instance — one slow grep froze disk reads and writes for minutes.

The adversarial review architecture was the quality gate:

"Adversarial Review Workflow"writes diffwrites difffeedbackfeedback"1 Implementer Claude""Writes the .rs file from Zig""Reviewer Claude #1""Adversarial review — sees ONLY the diff""Reviewer Claude #2""Separate context — independent review""1 Fixer Claude""Applies reviewer suggestions"
"Adversarial Review Workflow"writes diffwrites difffeedbackfeedback"1 Implementer Claude""Writes the .rs file from Zig""Reviewer Claude #1""Adversarial review — sees ONLY the diff""Reviewer Claude #2""Separate context — independent review""1 Fixer Claude""Applies reviewer suggestions"

The rule for reviewers was uncompromising: “If you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code.”

Real Bugs Caught

Async close / use-after-free:

// Buggy: Box<uv::Pipe> drops before async close callback fires
pipe.close(Subprocess::on_pipe_close)
// Fix: leak Box so libuv can safely access it
Box::leak(pipe).close(Subprocess::on_pipe_close)

Negative time truncation:

// Buggy: trunc(-1.5) = -1, leaving nsec = -500_000_000 (invalid timespec)
let sec = t.trunc();
// Fix: floor keeps nsec in [0, 1e9)
let sec = t.floor();

Eager evaluation:

// Buggy: unwrap_or evaluates eagerly — panics when second.percentage is None
let p1 = first.percentage.unwrap_or(1.0 - second.percentage.unwrap());
// Fix: unwrap_or_else is lazy
let p1 = first.percentage.unwrap_or_else(|| 1.0 - second.percentage.unwrap());

The 16,000 Compiler Errors

Zig’s single compilation unit became ~100 Rust crates. Breaking up the monolith exposed cyclical dependencies that had been hidden. The fix required two separate workflows: one classified where cyclical code should live, the other performed the refactor.

Once the cycles were broken: ~16,000 compiler errors. “That is a massive number for one human, but not actually a crazy number for 64 Claude.” The errors were grouped by crate (40+ crates: bun_runtime, bun_bundler, bun_sql, bun_js_parser, bun_css, bun_http, bun_sys, etc.) and divvied among the 64 Claudes. Per crate: 1 fixer → 2 reviewers → 1 applier → commit lands → counters update.

The Test Suite: 1.3 Million Assertions

Bun’s test suite is the safety net that makes the AI-assisted rewrite credible. Three platforms:

PlatformAssertionsTestsFiles
Debian 13 x641,386,82660,6244,174
macOS 14 arm641,259,95358,8504,175
Windows 2019 x641,007,54457,3374,173

The tests include memory leak checks, integration tests running next dev and verifying hot reloading 100 times, TCP socket exhaustion tests, gigabyte-scale disk tests, and stress tests spawning ~10,000 processes. Used systemd-run (cgroups) for isolation. The machine crashed from disk space exhaustion several times.

CI progression: 972 failing files → 23 → zero across all 6 platforms (macOS x64, Linux arm64, Linux x64, macOS arm64, Windows x64, Windows arm64). Total: 135 CI builds across 420 shards mined from BuildKite.

19 Regressions: When Syntax Matches but Semantics Don’t

The rewrite introduced 19 known regressions, all fixed. Most came from syntactically identical code with different semantics:

debug_assert! side effects — Zig’s assert is a function (runs all builds). Rust’s debug_assert! is a macro (erased in release):

// Buggy: insert_stale call erased in release → HMR broke
debug_assert!(dev.client_graph.insert_stale(...) == react_refresh_index);

HMR broke for React projects with HTML routes in release builds. Issue #30678.

Odd-length slices — Zig’s reinterpretSlice(u16, bytes) silently truncated trailing bytes via @divTrunc. Rust’s bytemuck::cast_slice panics on them. Blob.text() on odd-length UTF-16 BOM panicked. Issue #31188.

Bounds checks — Zig’s ReleaseFast removes bounds checks; Rust keeps them. Placeholder BSS_OVERFLOW_BLOCK_SIZE = 64 lowered interned filename ceiling from 8.4M to 270K. Rust panicked on ptrs[4095] off-by-one that Zig silently overflowed. Issue #31503.

comptime format strings — Zig’s fmt is comptime (markers removed before args substituted). Rust functions can’t do this — markers overwrote arguments. bun update -i backslash eaten by marker parser, printing “oxfmt r” instead of “oxfmt”. Issue #30693.

These are the kind of bugs that compile, pass most tests, and break in production. The test suite caught them — but they illustrate why “faithful translation” is harder than it looks.

The Numbers

MetricValue
Uncached input tokens5.9 billion
Output tokens690 million
Cached reads72 billion
API cost~$165,000
Duration11 days
Lines added1,009,272
Bugs fixed128
Regressions19 (all fixed)

Binary size: 94 MB → 76 MB (Windows), 88 MB → 70 MB (Linux). Initial rewrite alone reduced size; after linker optimizations (ICF, ICU trimming, zstd lazy decompression): ~20% shrink on Linux & Windows. Cause: excessive comptime usage in the Zig code.

HTTP throughput (Bun.serve, Linux x64 EC2): 169.6k → 177.7k req/s (+4.8%). express: 64.5k → 66.6k (+3.2%). fastify: 91.5k → 95.9k (+4.8%).

Build benchmarks: next build 13.62s → 13.03s (+4.5%), vite build 1.69s → 1.65s (+2.2%), tsc -b 0.94s → 0.89s (+4.7%).

Memory leak fix: bun.build() went from leaking ~3MB per call to constant memory. 2,000 builds: 6,745 MB (Zig) → 609 MB (Rust).

Unsafe blocks: ~4% of code (~13,000 unsafe keywords across ~27,000 lines). 78% are single-line pointer operations from C++ interop. Expected to decrease as faithful Zig port → idiomatic Rust refactoring.

Claude Code: v2.1.181+ uses Rust Bun. Linux p50 startup: 517ms → 464ms (10% faster). “Barely anyone noticed. Boring is good.”

Manual equivalent: Jared estimated 3 engineers × 1 year. “We never would’ve done that.”

Andrew Kelly’s Critique: Not Technical, Relational

Andrew Kelly, creator of Zig, published “My Thoughts on the Bun Rust Rewrite” shortly after Bun’s announcement. His argument has two layers: a technical critique and a relationship critique.

The Technical Counter-Arguments

LTO was always available. Bun attributed performance gains to Link-Time Optimization in Rust. Kelly’s counter: “LTO, which Zig has supported for all of Bun’s existence. It used to be enabled by default until we ran into too many LLVM bugs, all of which also affect Rust.” LTO was available; Bun just didn’t enable it.

Binary size engineering was independent of the rewrite. “All that engineering work had nothing to do with the rewrite. I think this is precisely why it took so long for the blog post to come out. You were doing the engineering work that you should have done in the Zig codebase since the beginning.”

The test suite contradiction. Kelly identifies a logical gap in Jared’s argument: “The argument for shipping all the million lines of unreviewed code is that the test suite is good enough to catch everything. Then why are you saying you have so many annoying bugs in the Zig code? What happened to the test suite being sufficient to catch everything? It’s not sufficient to catch bugs in Zig code but it is sufficient to catch bugs in 1 million lines of unreviewed slop?”

The real differentiator is engineering investment. Kelly argues the dichotomy between “style guide vs language features” is a misdirect: “The sleight of hand misdirects the reader away from the main way bugs are eliminated: by dedicating engineering resources to it.” He contrasts Bun with TigerBeetle, which also uses Zig: “Quite simply they put in the time to find and eliminate the bugs, they make an effort to maintain a healthy relationship with ZSF, and Bun did neither of those things.”

Fuzzing discrepancy. Bun’s blog post claims they were “diligently fuzzing.” Kelly counters: “During our calls the Bun team told us that they were not fuzzing anything.”

Compilation times. Kelly benchmarks the Zig compiler itself (~600K LOC, similar to pre-rewrite Bun): 16 seconds from scratch, 90ms incremental. He notes Bun’s blog post never mentioned compilation speed.

The Relationship Breakdown

Kelly’s thesis: “The main issue here had nothing to do with the language features of Zig vs Rust, and everything to do with the diverging value systems of the two projects and the relationship breakdown that followed.”

He claimed Bun’s code was “hacks on top of hacks,” that features shipped recklessly, and that ZSF internally assessed Bun as a net liability for the language. He was blunt about Jared’s management: “Poor communication, unrealistic expectations, low empathy, no experience. Just a total shit show, from an employment perspective.”

The original post ended with “I actually don’t have any personal criticisms of Jared” and a shrug emoji. After self-reflection, he rewrote the ending — not softer, but harsher: “I resent Jared for making Bun into an embarrassment for Zig and I blame him partially for some of the slop we’ve been dealing with, and I stand by my criticism of his leadership.” Kelly also apologized to Zig users for “trashing an ex-Zig user.”

Synthesis: Both Are Right About Different Things

Kelly is correct that the rewrite was not technically forced. Bun could have invested in memory-safe discipline, enabled LTO, and improved tooling in Zig. Nothing about the rewrite was strictly required.

Jared is correct that after years of use-after-free bugs, “being more disciplined is not a valid strategy.” A compiler that makes an entire bug class impossible is superior to a style guide, no matter how good the engineers. The 19 semantic regressions prove translation is hard — but the 1.3 million test assertions caught them before they shipped.

On the AI question, the rewrite wasn’t magic. It was a good engineer designing a translation pipeline: porting documentation, lifetime specs, adversarial reviewers, and a test suite that served as the safety net. As the video narrator noted: AI agents depend on test suites the way humans depend on specs. Without those 1.3 million assertions, the rewrite would have produced code that compiles but breaks in ways no one would notice until production.

Bun’s rewrite proves that AI-assisted code transformation at scale is now real. It also proves that the most interesting story isn’t the technology — it’s the relationship that broke.

References

  1. Bun Moved To Rust… Zig’s Creator Fired Back — Better Stack YouTube (July 13, 2026)
  2. Bun’s Rust Rewrite Blog Post — Jared Smith, bun.sh
  3. My Thoughts on the Bun Rust Rewrite — Andrew Kelley, andrewkelley.me
  4. Bun is rewriting itself from Zig to Rust — Hacker News Discussion (2026)

This article was written by a Pi subagent (Qwen 3.6 27B | Alibaba), based on content from: https://www.youtube.com/watch?v=0TSxrzBVEwQ