{"slug": "rewriting-bun-in-rust", "title": "Rewriting Bun in Rust", "summary": "Bun, the JavaScript runtime acquired by Anthropic in December 2025, is being rewritten from Zig to Rust to address persistent memory safety bugs and stability issues. The rewrite, led by Bun's original creator using a pre-release version of Claude Fable 5, aims to systematically prevent use-after-free crashes and memory leaks that have plagued the runtime despite its 22 million monthly downloads.", "body_md": "Disclosure: Bun was acquired by Anthropic in December 2025. I and others on the Bun team work at Anthropic. I used a pre-release version of Claude Fable 5 for much of the Rust rewrite.\n\nBun started as a line-for-line port of esbuild's JavaScript & TypeScript transpiler from Go to Zig. I wrote my first line of Zig on [April 16, 2021](https://github.com/ziglang/zig/issues/8575). I bet on Zig after seeing the single-page [Zig Language Reference](https://ziglang.org/documentation/master/) on Hacker News and getting really excited about the low-level control and care for performance.\n\nFrom the start, Bun's scope was massive:\n\n- JavaScript, TypeScript, and CSS transpiler, minifier, and bundler\n- npm-compatible package manager\n- Jest-like test runner\n- Node.js & TypeScript-compatible module resolution\n- HTTP/1.1 & WebSocket client\n- Node.js API implementations like\n`fs`\n\n,`net`\n\n,`tls`\n\n, and dozens of other modules\n\nThe initial version of Bun was written by me in 1 year, in a cramped Oakland apartment, pre-LLM, in Zig. The default outcome for ambitiously-scoped projects like Bun is joining the graveyard of dead side projects on a GitHub profile page. Zig made Bun possible. I would never have been able to build this much in 1 year if it wasn't for Zig.\n\nNowadays, Bun's CLI gets over 22 million monthly downloads. Popular tools like Claude Code and OpenCode bet on Bun as their runtime. Vercel, Railway, DigitalOcean and more have 1st-party support for Bun.\n\nBun's scope has also been a challenge for stability. Here's a small sample of bugs we fixed in Bun v1.3.14:\n\n- heap-use-after-free crash in\n`node:zlib`\n\nwhen calling`.reset()`\n\non a zlib, Brotli, or Zstd stream while an async`.write()`\n\nis still in progress on the threadpool - use-after-free crash in\n`node:zlib`\n\nwhen an`onerror`\n\ncallback issued a re-entrant`write()`\n\nfollowed by`close()`\n\non native handles - use-after-free crashes in\n`node:http2`\n\nwhen re-entrant JS callbacks (e.g.`session.request()`\n\ninside a timeout listener, an options getter, or a write callback) triggered a hashmap rehash, invalidating internal stream pointers - use-after-free in\n`UDPSocket.send()`\n\nand`sendMany()`\n\nwhere user code in`valueOf()`\n\nor`toString()`\n\ncallbacks could detach an`ArrayBuffer`\n\nbetween payload capture and the actual send - crash and out-of-bounds read in\n`Buffer#copy`\n\nand`Buffer#fill`\n\nwhen a`valueOf`\n\ncallback detaches or resizes the underlying`ArrayBuffer`\n\nduring argument coercion - heap out-of-bounds write in\n`UDPSocket.sendMany()`\n\nwhen the socket's connection state changed mid-iteration via user JS callbacks - memory leak in\n`crypto.scrypt`\n\nwhere the callback and protected password/salt buffers were never released when the output buffer allocation failed `SSLWrapper.init`\n\nleaked the strdup'd passphrase on error paths- memory leak in\n`tlsSocket.setSession()`\n\nwhere each call leaked one`SSL_SESSION`\n\n(~6.5 KB per call) due to a missing`SSL_SESSION_free`\n\nafter`d2i_SSL_SESSION`\n\n- memory leak where\n`fs.watch()`\n\nwatchers were never garbage collected after`.close()`\n\n, caused by a reference count underflow that permanently pinned each watcher as a GC root - double-free crash in the CSS parser when\n`background-clip`\n\nhad vendor prefixes and multi-layer backgrounds `DuplexUpgradeContext`\n\nwas never freed — a full leak per`tls.connect({ socket: duplex })`\n\n- race condition crash in\n`MessageEvent`\n\nwhere the GC marker thread could observe a torn variant in`m_data`\n\nduring concurrent access from a`BroadcastChannel`\n\nor`MessagePort`\n\nWe could have kept fixing these kinds of bugs one-off in perpetuity, but we owe it to our users counting on us to do better than that, and systematically prevent these kinds of bugs from recurring.\n\n[What we were already doing](#what-we-were-already-doing)\n\n- We patched the Zig compiler to add Address Sanitizer support. We run our test suite with ASAN on every commit.\n- We ship Zig safety-checked ReleaseSafe builds on Windows\n- We fuzz Bun's runtime APIs 24/7 using\n[Fuzzilli](https://github.com/googleprojectzero/fuzzilli), the JavaScript engine fuzzer used by V8 & JavaScriptCore - We have a whole lot of end-to-end memory leak tests\n\nThis is more than many projects do.\n\n[Just be really smart and don't make mistakes?](#just-be-really-smart-and-don-t-make-mistakes)\n\nOur bugfix list felt bad and I was tired of going to sleep worrying about crashes in Bun. I don't blame Zig for that - other users of Zig don't have the bugs we had, and mixing GC with manually-managed memory is an uncommon enough thing for software to need that no language really designs for it. We wouldn't have gotten this far if not for Zig, and I'll always be grateful. Until very recently, programming language choice was a one-way decision for a project like Bun.\n\nJavaScript is a garbage-collected language and modern JavaScript engines like JavaScriptCore (and V8) have strict rules around exception handling and the garbage collector. Zig, like C, doesn't manage memory for you and this is a tradeoff that for many projects is a great reason to use Zig. Zig does not have constructors/destructors, and most cleanup is expected to be written out explicitly at each call site with `defer`\n\n.\n\nFor Bun, correctly handling the lifetimes of garbage-collected values and manually-managed values has been a major source of stability issues - most often small memory leaks and occasionally, crashes. Every memory allocation has to be meticulously reviewed. Where do these bytes get freed? How do we ensure it only gets freed once? Did we check for JavaScript exceptions properly? Is this garbage-collected pointer visible to the conservative stack scanner? Is this garbage collected memory or manually managed memory?\n\nFor stability issues, knowing as early as possible is best. Fuzzing happens after code is merged. CI happens when code is pushed. Runtime safety checks & address sanitizer happens when code is run (hopefully in development, before CI).\n\nOne common way to reduce this class of issue is to ensure cleanup code is always run exactly once for code that needs it. Zig is designed to be a simple language with no hidden control flow, and so it prefers the explicit `defer`\n\nkeyword to run code at the end of a scope over C++'s implicit ~Destructor or Rust's implicit `Drop`\n\n.\n\n| Language | Cleanup |\n|---|---|\n| Zig | `defer` , `errdefer` |\n| C++ | ~Destructor, &&Move |\n| Rust | Drop |\n\nFor Zig code, when exactly should we be running the cleanup code? If we're passing the same `*T`\n\nto many different functions, how do we know when it's no longer accessible and can be cleaned up? How does it work when some functions need to continue to reference the memory after the function is called? Our current approach is a mix of:\n\n- arena lifetimes, where the scope of when it's accessible is clear (parser state doesn't escape the calling function and so AST nodes are a good choice there)\n- reference-counting\n- pay really close attention\n\nMany projects opt to answer these kinds of questions through a style guide. TigerBeetle's [TigerStyle](https://tigerstyle.dev/) is an example in Zig and Google's 31,000 word [C++ style guide](https://google.github.io/styleguide/cppguide.html) is another. The challenge with style guides is enforcement. How do you make sure the style guide is followed? Historically, code review was the answer with best-effort enforcement via linters & static analyzers.\n\nHaving a rigid style guide with clear ownership expectations explicitly spelled out in the type system was a real option for Bun. Since Zig has no operator overloading, we would likely end up with a lot of code looking something like this:\n\n``` js\nfn foo(a_ptr: SharedPtr(TCPSocket)) !void {\n  const a: *TCPSocket = a_ptr.get();\n  defer a_ptr.deref();\n\n  const b = try do_something_with_a(a);\n  defer b.deref();\n\n  // ...\n}\n```\n\nThis is less ergonomic than the Zig we expect:\n\n``` js\nfn foo(a: *TCPSocket) !void {\n  const b = try do_something_with_a(a);\n  // ...\n}\n```\n\n[What about C/C++?](#what-about-c-c)\n\nAbout 20% of Bun's code is written in C++ and Bun embeds several C/C++ libraries:\n\n- JavaScriptCore, the JavaScript engine that powers Safari\n- uWebSockets & usockets - our HTTP/WebSocket server, and event loop\n- lshpack & lsquic -\n`HPACK`\n\nand HTTP/3 libraries - BoringSSL, Google's OpenSSL fork\n- SQLite\n\nC++ instead of Zig would be a reasonable choice for Bun. We would get constructors & destructors. We could delete lots of `extern \"C\"`\n\nwrapper code.\n\nBut, we would still be reliant on style guides enforced through code review, and even with ASAN, memory corruption and memory leaks would still happen.\n\n[Why Rust?](#why-rust)\n\nA large percentage of bugs from that list are use-after-free, double-free, and \"forgot to free\" in an error path. In safe Rust, these are compiler errors and RAII-like automatic cleanup with `Drop`\n\n. Compiler errors are a better feedback loop than a style guide.\n\nHistorically, rewrites are a terrible idea. Excluding comments, Bun is 535,496 lines of Zig. A rewrite in another language would take a small team of engineers a full year. It would mean freezing bugfixes, security fixes or feature development for that time. The least risky approach to getting something shippable would be a mechanical port from Zig to Rust, with the minimal number of behavioral changes, using the exact same test suite we already use for testing Bun.\n\nFortunately, Bun's own test suite is written in TypeScript which means it doesn't depend on the runtime's programming language.\n\nA year of zero user-facing impact is not a realistic option we could consider. So, enforcement through code-style to fix stability issues was our best bet, and was our plan when we added Rust-inspired [smart pointers](https://github.com/oven-sh/bun/blob/3a79bd746b11601c9db970b608c73f0b9f96ac81/src/ptr/shared.zig#L569) to Bun's codebase.\n\nBut honestly, I didn't want to do it. Homegrown smart pointers offer worse ergonomics than Rust, with none of the guarantees.\n\nWhat if, instead, I spend a week testing if Anthropic's new model can rewrite Bun in Rust?\n\nAt first, I didn't expect it to work. A few days in, a high % of the test suite started passing and I saw how much the new Rust code matched up with the original Zig codebase. My opinion went from \"this is worth trying\" to \"I'm going to merge this\".\n\n[Claude, rewrite Bun in Rust.](#claude-rewrite-bun-in-rust)\n\nThere are a lot of ways to do a terrible job of this. For example, prompting Claude \"Rewrite Bun in Rust. Don't make any mistakes.\" and then praying it would work is not what I did.\n\nThink about how a person would do this. The first big question is:\n\nIncremental rewrite? Or, everything all at once?\n\nIn my experience porting esbuild's transpiler from Go to Zig for the initial version of Bun (without LLMs), everything all at once is better. An incremental rewrite adds temporary code that you hope gets deleted eventually, and would be painful in the short-medium term.\n\nThe second big question: how?\n\nHow do we keep Bun in Rust the same Bun as before, with the same architecture, performance, and feature-set while also getting the language features of Rust like the borrow checker? How do we ensure the team can still maintain it after the rewrite?\n\nDo the rewrite that looks like we transpiled our Zig code to Rust. We can gradually refactor it to reduce `unsafe`\n\nusage and look more like idiomatic Rust after Bun v1.4 ships.\n\nThose are the only two big questions. Everything else is tactics.\n\n[Loops that write & review code](#loops-that-write-review-code)\n\nA lot of day-to-day engineering work as software engineers can be over-simplified into loops.\n\n``` js\n// Pseudocode, not real code:\nlet task;\nwhile ((task = todoList.pop())) {\n  const result = task();\n  const feedback = await Promise.all([review(result), review(result)]);\n  await apply(feedback, result);\n}\n```\n\nA `task`\n\nhas some context associated with it (a Jira ticket, a GitHub issue, etc). The `result`\n\nis the code you wrote to fix it. Code reviewer(s) `review`\n\nthe changes to check for regressions & correctness. And then you address the feedback.\n\nI rewrote Bun in Rust using about 50 dynamic workflows in Claude Code run continuously over the course of 11 days.\n\nEach dynamic workflow was a loop like this - a workflow for:\n\n- Generate a porting guide mapping Zig patterns & types to Rust patterns & types\n- Mechanically port every\n`.zig`\n\nfile to a`.rs`\n\nfile, matching the PORTING.md and LIFETIMES.tsv - Fix every crate's compiler errors\n- Get subcommands like\n`bun test`\n\nor`bun build`\n\nto work - Get every test in Bun's entire test suite to pass\n- Several large refactors and cleanup passes\n\nFor most of those 11 days (and after), I monitored workflows - manually reading the outputs to check for issues and bugs, and prompting Claude to edit the loop to fix things.\n\nHow do you review a PR with +1 million lines added? How do you start to build the confidence needed to responsibly merge large quantities of LLM-authored code?\n\nA language-independent test suite with a million assertions, adversarial code review and when something does go wrong, fixing the process that generates the code instead of hand-fixing the code.\n\n[Adversarial review](#adversarial-review)\n\nAdversarial review asks Claude (in a separate context window) to exhaustively come up with reasons why the changes create bugs or do not work.\n\n#### Split context windows\n\nUsually with humans, the person reviewing the code is not the person who authored the code. The person writing the code wants to merge the code, which can bias their actions to ship before it's ready.\n\nClaude is the same way. The Claude that wrote the code wants the code to get accepted. The Claude that reviews wants to find issues in the code.\n\n1 implementer, 2 or more adversarial reviewers per implementer. The reviewer's only job: find bugs & reasons why the code does not work. The implementer doesn't review. The reviewer doesn't implement.\n\n[What does this look like?](#what-does-this-look-like)\n\nIf you're about to do something big and expensive, it saves time and money to de-risk it first.\n\n[Prep work](#prep-work)\n\nBefore writing any code, I spent about 3 hours talking to Claude about how to map patterns from our Zig codebase closely to Rust. Claude serialized this discussion into a `PORTING.md`\n\ndocument, which ended up on [Hacker News](https://news.ycombinator.com/item?id=48016880).\n\nThe next question: how do you add Rust lifetimes to code that manually manages memory?\n\nThat's where I prompted Claude something like this:\n\nMe: Let's kick off a dynamic workflow to analyze the proper lifetimes of every struct field in the codebase. This workflow should read every struct field within every single file and trace the control flow. First, look for struct fields with complex lifetimes to express in Rust, then propose a lifetime for that field, then use 2 adversarial review agents to review that lifetime, then apply any feedback and serialize into a LIFETIMES.tsv for other claudes to look at.\n\nThen a round of adversarial reviews on the `PORTING.md`\n\nand the `LIFETIMES.tsv`\n\ntogether to fix any conflicting suggestions and double check everything. I also manually read over it.\n\n[Trial run](#trial-run)\n\nBefore asking Claude to translate all 1,448 .zig files to .rs files, I started with just 3. For each of the 3 files, 1 implementer wrote the new `.rs`\n\nfile, 2 adversarial reviewers checked the `.rs`\n\nfile matched the behavior of the `.zig`\n\nfile and that it followed the `PORTING.md`\n\n& `LIFETIMES.tsv`\n\n. After that, 1 fixer applied any suggestions.\n\n[False starts](#false-starts)\n\nI asked Claude to loop the workflow on all 1,448 .zig files, and about 2 minutes in, one Claude ran `git stash`\n\nbefore committing. Another ran `git stash pop`\n\n. And then `git reset HEAD --hard`\n\n. They were stepping on each other! And if I put each Claude into a separate worktree, I would run out of disk space because Bun's git repository is too big and eventually the changes will need to be compiled and seen together.\n\nSo, I asked Claude to edit the workflow to instruct Claude to never run `git stash`\n\nor `git reset`\n\nor any `git`\n\ncommand that doesn't commit a specific file at once. No `cargo`\n\neither. No slow commands at all.\n\nThen, Claude resumed the workflows. And it was working! Too slowly, so I split it into just 4 workflow shards each with their own worktree (4 worktrees total), each running 16 claudes committing and pushing files.\n\n[Finally writing the code](#finally-writing-the-code)\n\nThanks to all the parallelization & this prep work, at peak Claude wrote about 1,300 lines of code per minute. Every line of code was reviewed by two separate adversarial reviewers (also Claude) and went through a round of fixes before committing. Absolutely none of it worked yet.\n\nNotice the inconsistent timing? I forgot to increase the default IOPS on the EC2 instance this ran on. One slow `grep`\n\ncommand was all it took to freeze disk reads & writes for minutes.\n\n[Compiler errors as a work queue](#compiler-errors-as-a-work-queue)\n\nAfter writing all the code, I asked Claude to write a workflow fixing every compiler error. We went crate-by-crate.\n\nThe trickiest class of error was cyclical dependencies.\n\nOur Zig codebase was one compilation unit (effectively one crate). I wanted to split the new Rust codebase into ~100 crates so the Rust would compile faster, but this needed to avoid cyclical dependencies while minimizing changes compared to the original Zig implementation. [My PR](https://github.com/oven-sh/bun/pull/30224) to do this immediately before starting the Rust rewrite was insufficient. Instead of starting over, I ran another workflow to classify where the code with cyclical dependencies should go and write it all down - and then another workflow to do the refactor.\n\nFixing the cyclical dependencies revealed about 16,000 compiler errors. A massive number for 1 human, but not a crazy number for 64 claudes at once.\n\nTo maximize parallelism, the workflow looped over each crate.\n\n- For each crate, run\n`cargo check`\n\n, group the output by file and save the errors to a file - Fix all the compiler errors within that crate\n- 2 adversarial reviewers for the crate's changes\n- 1 fixer applies the fixes\n\nTo prevent claudes from stepping on each other, `cargo check`\n\nonly ran at the very start and like the other runs, no `git`\n\nuntil the end.\n\n#### Another false start\n\nClaude interpreted \"let's get all the crates to compile\" as \"stub out the functions with compilation errors\". Claude also started adding suspiciously long explanatory comments to document workarounds, so I added this rule for the adversarial reviewers to reject:\n\nIf you need a paragraph-long comment to justify why the workaround is OK, the code is wrong — fix the code.\n\nOne prompt edit and a few hours later, these things stopped happening.\n\n[Smoke tests](#smoke-tests)\n\nModels love saying \"smoke tests\"\n\nOnce `cargo check`\n\npassed, getting it to compile and run `bun --version`\n\nwas next. It had linker errors. Then, it panicked immediately on start.\n\nThe next goal was to get it to run `bun test <file>`\n\n. Once that worked, we could start running tests! Time for another workflow, looping over bun CLI subcommands:\n\n- Save each failing stacktrace to a file along with its subcommand\n- For each failing stacktrace grouped by subcommand, have 1 Claude fix\n- 2 adversarial reviewers\n- 1 fixer applies the suggestions\n\n[Get the test suite passing locally](#get-the-test-suite-passing-locally)\n\nThis workflow looped on test files.\n\nRun about 100 random test files sharded to one of 4 worktrees by folder in the codebase. For each failing test, save the stacktrace & errors to a file, 1 implementer proposes a fix, 2 adversarial reviewers, then 1 fixer applies.\n\n#### Even more false starts\n\nOur test suite has lots of memory leak tests and a handful of integration tests that can take more than a minute - for example: a test that runs `next dev`\n\nand checks hot module reloading can pick up on changes 100 times. Several of these tests timeout in debug builds.\n\nWe also have stress tests that exhaust the max number of TCP sockets on the machine, tests that read & write gigabytes to disk, and tests that spawn ~10k processes.\n\nThis needed stronger isolation than \"please\", so we used `systemd-run`\n\n(cgroups) to limit memory & CPU usage and isolate pid namespaces. The machine ran out of disk space and crashed several times anyway.\n\n[Get the test suite passing in CI](#get-the-test-suite-passing-in-ci)\n\nTwo days after the first CI run, the failing list was down from 972 test files to 23. A day and a half after that, Linux went fully green — and for the first time, it felt like this Rust rewrite was actually going to work.\n\nThe rest of the time leading up to merging it was straightforward. A workflow that looped on fixing CI test failures for each platform until there were no more test failures. Several workflows for Windows-related cleanup, to deduplicate code, to reduce unsafe usage, and to generally clean up some code.\n\n[Merging the Rust rewrite](#merging-the-rust-rewrite)\n\nOnce 100% of Bun's test suite passed in CI on all platforms (and I manually verified the tests were in fact running and not being skipped), I ran a bunch of commands locally to test things - and then I pressed the merge button.\n\nMerging into `main`\n\nisn't a versioned release. At this point, I was confident enough to move forward and commit to the rewrite, but not yet confident enough to release it.\n\n[Stats](#stats)\n\nAt peak, we were running 4 of these workflows at once each in a separate worktree, each with 16 Claudes per workflow. About 64 Claudes at a time.\n\n#### 0 tests skipped or deleted\n\n11 days (May 3 → merged May 14) · 6,778 commits\n\n| Platform | expect() calls | Tests | Files |\n|---|---|---|---|\n| Debian 13 x64 | 1,386,826 | 60,624 | 4,174 |\n| macOS 14 arm64 | 1,259,953 | 58,850 | 4,175 |\n| Windows 2019 x64 | 1,007,544 | 57,337 | 4,173 |\n\nPre-merge, this took 5.9 billion uncached input tokens, 690 million output tokens, and 72 billion cached input token reads — around $165,000 at API pricing. By hand, I think this would've taken 3 engineers with full context on the codebase about a year, during which time we wouldn't be able to improve Node.js compatibility, fix bugs, fix security issues or implement new features. We never would've done that. The realistic alternative was to do nothing and keep fixing the bugs at the top of this post forever.\n\nThis is the bleeding edge of what's possible today. I used a pre-release version of [Claude Fable 5](https://www.anthropic.com/news/claude-fable-5-mythos-5), a Mythos-class model. Claude Code's dynamic workflows kept 64 Claudes running for 11 days (I would've had to write my own harness to pull this off otherwise).\n\n[The work continues](#the-work-continues)\n\nSince merging the Rust port, we've completed 11 rounds of security review from [Claude Code Security](https://claude.com/product/claude-security) and addressed the findings.\n\nWe've also added 24/7 coverage-guided fuzzing of every parser in Bun — JavaScript, TypeScript, JSX, CSS, JSON5, JSONC, TOML, YAML, Markdown, INI, Bun Shell scripts, semver ranges, .patch files, and CSS colors. The fuzzer automatically sends the bugs it finds to Claude to submit a PR reproducing & fixing, and humans review the PRs. So far, it's executed our parsers 100 billion times which has led to around 15 PRs.\n\nAt the time of writing, about 4% of Bun's Rust code sits inside an `unsafe`\n\nblock (~13,000 `unsafe`\n\nkeywords across ~27,000 lines / ~780,000 lines), and 78% of those blocks are a single line — a pointer that came from C++, or one call into a C library. I expect this number to go down over time as we refactor from a faithful Zig port (which had no greppable `unsafe`\n\nkeyword) to idiomatic Rust, but we are going to continue using C & C++ libraries like JavaScriptCore so it will always have more `unsafe`\n\nthan pure Rust projects.\n\n[Porting mistakes](#porting-mistakes)\n\nThe focus of the Rust rewrite is stability, but it would be impossible to ship a massive change like this and introduce zero regressions.\n\nThis rewrite introduced 19 known regressions, each of which has been fixed.\n\nMost of the regressions came from code that's syntactically identical in both languages but semantically different.\n\n#### Side effect inside `debug_assert!`\n\nThese two snippets look similar but behave differently. Zig's `assert`\n\nis a function, so its argument runs in every build. Rust's `debug_assert!`\n\nis a macro, so in release builds the whole expression is erased, including the `insert_stale`\n\ncall.\n\n```\n// Zig:\nif (dev.framework.react_fast_refresh) |rfr| {\n    assert(try dev.client_graph.insertStale(rfr.import_source, false) == IncrementalGraph(.client).react_refresh_index);\n}\n\n// Rust:\nif let Some(rfr) = &dev.framework.react_fast_refresh {\n    debug_assert!(dev.client_graph.insert_stale(&rfr.import_source, false)? == react_refresh_index);\n}\n```\n\n`insert_stale`\n\nadds a file to the frontend dev server's hot reload graph. In release builds it stopped running, and HMR broke in certain cases for projects with HTML routes that use React while a hot reloaded file gets invalidated: `Cannot destructure property 'isLikelyComponentType' of 'k'`\n\n. Debug builds worked. [#30678](https://github.com/oven-sh/bun/issues/30678)\n\n#### Slices of odd length\n\nBun's Zig helper `reinterpretSlice(u16, bytes)`\n\n(predating builtin casts supporting slices) used `@divTrunc`\n\nand ignored a trailing odd byte. `bytemuck::cast_slice`\n\npanics on it instead. `Blob.text()`\n\non a UTF-16 byte order mark followed by an odd number of bytes stopped returning a string and panicked the process. We went back to ignoring the odd byte: `&buf[..buf.len() & !1]`\n\n. [#31188](https://github.com/oven-sh/bun/issues/31188)\n\n#### Bounds checks\n\nOn macOS & Linux, we compiled Bun's Zig code with `ReleaseFast`\n\n, which removes bounds checks. Rust's release builds keep them.\n\nBun's module resolver interns long filenames into a global list that spills into overflow blocks. The original Zig code sized each block at `count / 4`\n\n, or 2048. The port left a placeholder:\n\n```\n/// ... so use a nonzero stand-in until Phase B threads the\n/// per-instantiation value through.\npub const BSS_OVERFLOW_BLOCK_SIZE: usize = 64;\n```\n\nThat lowered the ceiling from 8.4 million interned filenames to 270,272, which real projects hit, and made a `ptrs[4095]`\n\noff-by-one we ported from Zig reachable. Rust panicked instead of writing past the end. Zig would also panic in this case, if we used `ReleaseSafe`\n\n(we only did on Windows). [#31503](https://github.com/oven-sh/bun/issues/31503)\n\n`comptime`\n\nformat strings\n\n`Output.pretty`\n\nrewrites `<r>`\n\nand `<d>`\n\ncolor markers into ANSI escapes. In Zig, `fmt`\n\nis `comptime`\n\n, so the markers are gone before the arguments are substituted. Rust functions don't have comptime parameters, so `Output::pretty`\n\nonly ever saw the finished string, and rewrote markers over the arguments too.\n\n```\n// Zig:\npub inline fn pretty(comptime fmt: string, args: anytype) void;\nOutput.pretty(\"<r>{f}<r>\", .{hyperlink});\n\n// Rust:\npub fn pretty(payload: impl PrettyFmtInput);\nOutput::pretty(format_args!(\"<r>{}<r>\", hyperlink));\n```\n\n`bun update -i`\n\nprints package names as [OSC 8](https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda) hyperlinks, terminated by `ESC \\`\n\n. That backslash sits right before the `<`\n\nof the trailing `<r>`\n\n, the marker parser eats it, and the `r`\n\nprints as text.\n\nIn Rust it has to be a macro: `bun_core::pretty!(\"<r>{}<r>\", hyperlink)`\n\n. [#30693](https://github.com/oven-sh/bun/issues/30693)\n\n[Bun is better in Rust](#bun-is-better-in-rust)\n\nSo far, Bun v1.4.0 fixes 128 bugs that reproduce in v1.3.14. These range from memory leaks to crashes to miscolored help text.\n\n[Reduced memory usage](#reduced-memory-usage)\n\nRust has a powerful language-level tool for cleaning up memory: `Drop`\n\n. When `Drop`\n\nis implemented, the `drop`\n\nfunction is automatically called every time the value goes out of scope.\n\n```\nimpl Drop for Bytes {\n    fn drop(&mut self) {\n        if !self.pinned.is_empty() {\n            JSC__JSValue__unpinArrayBuffer(self.pinned);\n        }\n    }\n}\n```\n\nIn Zig, `defer`\n\ncan be used to run code at the end of a scope:\n\n``` js\nconst bytes: ArrayBuffer = try .fromPinned(global, value);\ndefer bytes.unpin();\n```\n\nIn Zig, `defer`\n\nneeds to be added to every individual call site that might need cleanup. It's easy to end up forgetting to clean up (a memory leak), or to run cleanup code twice in rarely-reached error handling code (a double-free). In Rust, `Drop`\n\nruns automatically when the value is no longer accessible - trading \"no hidden control flow\" for preventing a common footgun.\n\n`Drop`\n\nfixed several memory leaks in Bun related to file paths in error handling code.\n\n#### We fixed every instrumentable memory leak\n\nWe improved Bun's [LeakSanitizer](https://clang.llvm.org/docs/LeakSanitizer.html) integration to track all [native code memory allocations](https://github.com/oven-sh/bun/pull/30875).\n\nHere's an example: every in-process `Bun.build()`\n\ncall leaked several megabytes of memory — parsed source text and AST symbol tables that outlived the build they belonged to.\n\n``` js\n// Bundle the same 60-module project 2,000 times in one process\nfor (let i = 0; i < 2_000; i++) {\n  await Bun.build({\n    entrypoints: [\"./index.js\"],\n    minify: true,\n    sourcemap: \"external\",\n  });\n}\n```\n\nIn Bun v1.3.14, every build leaks about 3 MB, forever — tools like dev servers that bundle on every request eventually run out of memory. In Bun v1.4.0, memory levels off:\n\n| Builds | Bun v1.3.14 | Bun v1.4.0 |\n|---|---|---|\n| 500 | 1,914 MB | 526 MB |\n| 1,000 | 3,506 MB | 586 MB |\n| 1,500 | 5,097 MB | 608 MB |\n| 2,000 | 6,745 MB | 609 MB |\n\nA [previous attempt](https://github.com/oven-sh/bun/pull/24741) to do this in Zig was not merged because the lack of an equivalent of Drop made it more difficult to feel confident merging.\n\n[Smaller binary size](#smaller-binary-size)\n\nThe initial changes in the Rust rewrite reduced binary size by 3.8 MB on Windows, 5.5 MB on macOS, and 6.8 MB on Linux. This is largely because we used too much `comptime`\n\nin our Zig code.\n\n— Bun (@bunjavascript)[May 18, 2026]\n\nAfter that initial shrinkage, the team explored more opportunities for binary size reduction using linker optimizations like Identical Code Folding, removing unused data from ICU, and lazily decompressing small parts of libicu with a zstd dictionary on-demand.\n\nCombined with the Rust rewrite, ICU changes, and identical code folding, **Bun's binary size shrinks by ~20%** on Linux & Windows.\n\n| Version | Platform | Size |\n|---|---|---|\n| Bun v1.4.0 (canary) | Windows | 76 MB |\n| Bun v1.3.14 | Windows | 94 MB |\n| Bun v1.4.0 (canary) | Linux | 70 MB |\n| Bun v1.3.14 | Linux | 88 MB |\n\n[Reduced stack space usage](#reduced-stack-space-usage)\n\nThe TOML parser, and all of the other recursive-descent parsers in Bun (JSON, YAML, JavaScript, TypeScript, and more) now use less stack space.\n\nThis caused some test failures before merging the Rust rewrite:\n\n```\nbun test v1.3.14-canary.1 (e99311e58)\n.......\n\n105 | });\n106 |\n107 | it(\"Bun.TOML.parse throws on deeply nested inline tables instead of crashing\", () => {\n108 |   const depth = 25_000;\n109 |   const deepToml = \"a = \" + \"{ b = \".repeat(depth) + \"1\" + \" }\".repeat(depth);\n110 |   expect(() => Bun.TOML.parse(deepToml)).toThrow(RangeError);\n                                               ^\nerror: expect(received).toThrow(expected)\n\nExpected constructor: RangeError\n\nReceived function did not throw\nReceived value: {\n  a: {\n    b: {\n      b: {\n        b: {\n          b: {\n            b: {\n              b: {\n                b: {\n                  b: [Object ...],\n                },\n              },\n            },\n          },\n        },\n      },\n    },\n  },\n}\n\n      at <anonymous> (/var/lib/buildkite-agent/build/test/js/bun/resolve/toml/toml.test.js:110:42)\n\n✗ Bun.TOML.parse throws on deeply nested inline tables instead of crashing [2907.64ms]\n```\n\nRust's LLVM IR codegen emits LLVM's [ llvm.lifetime.start](https://llvm.org/docs/LangRef.html#llvm-lifetime-start-intrinsic) and\n\n[intrinsics for stack variables when they are no longer in use, which lets LLVM reuse stack space slots. This lets large functions with nested scopes use significantly less stack space.](https://llvm.org/docs/LangRef.html#llvm-lifetime-end-intrinsic)\n\n`llvm.lifetime.end`\n\nPreviously, we manually worked around [an open issue](https://github.com/ziglang/zig/issues/23475) by [refactoring particularly large functions](https://github.com/oven-sh/bun/pull/15993) into many smaller functions.\n\n[2% - 5% faster](#2-5-faster)\n\nRust supports cross-language link-time optimization between C/C++ and Rust, which enables inlining across programming languages (how cool is that!!).\n\nWe benchmarked Bun v1.3.14 against Bun v1.4.0 on Linux x64 (EC2, Xeon Platinum 8488C). HTTP throughput measured with [oha](https://github.com/hatoo/oha) against hello-world servers, app workloads measured with [hyperfine](https://github.com/sharkdp/hyperfine).\n\n**HTTP throughput (req/s, avg of 3 rounds)**\n\n| server | Bun v1.3.14 | Bun v1.4.0 | Δ |\n|---|---|---|---|\n| Bun.serve | 169.6k | 177.7k | +4.8% |\n| node:http | 103.8k | 108.5k | +4.5% |\n| Elysia | 158.9k | 163.3k | +2.8% |\n| express | 64.5k | 66.6k | +3.2% |\n| fastify | 91.5k | 95.9k | +4.8% |\n\n**Apps / CLI (hyperfine)**\n\n| workload | Bun v1.3.14 | Bun v1.4.0 | Δ |\n|---|---|---|---|\n| next build | 13.62 s | 13.03 s | +4.5% |\n| vite build (tsc + vite) | 1.69 s | 1.65 s | +2.2% |\n| tsc -b --force | 0.94 s | 0.89 s | +4.7% |\n\n[Production](#production)\n\nPrisma launched the [Prisma Compute](https://www.prisma.io/blog/bun-rust-rewrite-prisma-compute) public beta on Bun's Rust rewrite.\n\n\"We ran into memory leaks and a connection pool that couldn't recover after a VM was paused and resumed. When the Rust rewrite appeared, we tested it against the same failure modes. It handled them perfectly.\" - Alexey Orlenko\n\nClaude Code v2.1.181 (released June 17th) and later use the Rust port of Bun. Startup got 10% faster on Linux but otherwise, barely anyone noticed. Boring is good.\n\n[Shipping](#shipping)\n\nBun v1.3.14 was the last version of Bun written in Zig. Bun v1.4.0 will be the first version of Bun written in Rust. It's available in canary now - please report any issues you find:\n\n```\nbun upgrade --canary\n```\n\n[Maintainability](#maintainability)\n\nFor myself and the team, our new Rust codebase feels very similar to the old Zig codebase. For example, here's a snippet of the original Zig code and the new Rust code:\n\n```\npub fn canMergeSymbols(\n    scope: *Scope,\n    existing: Symbol.Kind,\n    new: Symbol.Kind,\n    comptime is_typescript_enabled: bool,\n) SymbolMergeResult {\n    if (existing == .unbound) {\n        return .replace_with_new;\n    }\n\n    if (comptime is_typescript_enabled) {\n        // In TypeScript, imports are allowed to silently collide with symbols within\n        // the module. Presumably this is because the imports may be type-only:\n        //\n        //   import {Foo} from 'bar'\n        //   class Foo {}\n        //\n        if (existing == .import) {\n            return .replace_with_new;\n        }\n\n        // ...\n    }\n\n    // ...\n}\njs\npub fn can_merge_symbol_kinds<const IS_TYPESCRIPT_ENABLED: bool>(\n    scope_kind: Kind,\n    existing: symbol::Kind,\n    new: symbol::Kind,\n) -> SymbolMergeResult {\n\n    if existing == symbol::Kind::Unbound {\n        return SymbolMergeResult::ReplaceWithNew;\n    }\n\n    if IS_TYPESCRIPT_ENABLED {\n        // In TypeScript, imports are allowed to silently collide with symbols within\n        // the module. Presumably this is because the imports may be type-only:\n        //\n        //   import {Foo} from 'bar'\n        //   class Foo {}\n        //\n        if existing == symbol::Kind::Import {\n            return SymbolMergeResult::ReplaceWithNew;\n        }\n\n        // ...\n    }\n\n    // ...\n}\n```\n\nAnyone who understands the original Zig code understands the mechanically translated Rust code. I reviewed the original Rust rewrite PR by checking the adversarial code review agents were correctly catching discrepancies between the Zig code and the Rust code, that they were ensuring the porting guide and lifetime guide were being followed, and also manually reading a lot of the code myself side-by-side with the Zig vs Rust.\n\n[What's next](#what-s-next)\n\nBun v1.4 makes Bun faster, smaller, use less memory and gives the team incredibly powerful tools for systematically improving stability going forward: Rust's borrow checker, Miri (which runs for a growing chunk of code in CI), LeakSanitizer, and 24/7 coverage-guided fuzzing for parsers. There's still [more to refactor](https://bun.com/bun-unsafe-audit), but things are off to a great start.\n\nThis Rust rewrite would've taken a team of engineers with full-context on the codebase a year of work. With 1 engineer using Fable & closely monitoring Claude Code, we went from start to 100% of the test suite passing on all platforms in 11 days.\n\nOne engineer can do a lot more today than a year ago.", "url": "https://wpnews.pro/news/rewriting-bun-in-rust", "canonical_source": "https://bun.com/blog/bun-in-rust", "published_at": "2026-07-08 16:00:00+00:00", "updated_at": "2026-07-08 21:48:20.220505+00:00", "lang": "en", "topics": ["developer-tools", "ai-tools"], "entities": ["Bun", "Anthropic", "Claude Fable 5", "Zig", "Rust", "Vercel", "Railway", "DigitalOcean"], "alternates": {"html": "https://wpnews.pro/news/rewriting-bun-in-rust", "markdown": "https://wpnews.pro/news/rewriting-bun-in-rust.md", "text": "https://wpnews.pro/news/rewriting-bun-in-rust.txt", "jsonld": "https://wpnews.pro/news/rewriting-bun-in-rust.jsonld"}}