Repository navigation
Description
What version of Bun is running?
1.3.11
What platform is your computer?
Microsoft Windows NT 10.0.26200.0 x64
What steps can reproduce the bug?
- Fetch multiple URLs and store the resulting Blobs in an array
- Clear the array (
blobs = []) to remove all references - Call
Bun.gc(true)multiple times, wait 8+ seconds - Observe that RSS memory is not released
Single-file repro that works with both Bun and Node:
// Run: bun repro.js | node --expose-gc repro.js
const FETCH_COUNT = 50;
const isBun = !!globalThis.Bun;
const runtime = isBun ? `Bun ${Bun.version}` : `Node ${process.version}`;
let blobs = [];
const startRss = process.memoryUsage().rss / 1024 / 1024;
console.log(`${runtime} | Start memory: ${startRss.toFixed(1)}mb`);
for (let i = 0; i < FETCH_COUNT; i++) {
const res = await fetch("https://www.w3schools.com/html/mov_bbb.mp4");
blobs.push(await res.blob());
if ((i + 1) % 10 === 0) {
const rss = process.memoryUsage().rss / 1024 / 1024;
console.log(`fetched ${i + 1}/${FETCH_COUNT}, memory: ${rss.toFixed(1)}mb`);
}
}
const peakRss = process.memoryUsage().rss / 1024 / 1024;
console.log(`\nPeak memory: ${peakRss.toFixed(1)}mb (${blobs.length} blobs)`);
blobs = [];
if (isBun) Bun.gc(true);
if (global.gc) global.gc();
await new Promise((r) => setTimeout(r, 3000));
if (isBun) Bun.gc(true);
if (global.gc) global.gc();
await new Promise((r) => setTimeout(r, 5000));
if (isBun) Bun.gc(true);
if (global.gc) global.gc();
const finalRss = process.memoryUsage().rss / 1024 / 1024;
const released = peakRss - finalRss;
const pct = ((released / (peakRss - startRss)) * 100).toFixed(1);
console.log(`\nAfter GC: ${finalRss.toFixed(1)}mb`);
console.log(`Released: ${released.toFixed(1)}mb (${pct}%)`);
console.log(parseFloat(pct) > 70 ? "\n✅ GC working" : "\n❌ Memory leak — GC did not free blobs");What is the expected behavior?
Memory should be reclaimed after all Blob references are removed and Bun.gc(true) is called. Node.js correctly frees ~73% of allocated memory in the same scenario.
What do you see instead?
Bun releases 0% of memory. Full comparison on the same machine:
| Bun 1.3.11 | Node v25.6.0 | |
|---|---|---|
| Start | 105.1 MB | 56.9 MB |
| Peak | 184.2 MB | 125.3 MB |
| After GC | 184.3 MB | 75.3 MB |
| Released | -0.2 MB (0%) | 50.0 MB (73%) |
Additional information
Related issues:
-
Memory Leak with Blob/ArrayBuffer and Bun's Garbage Collection #12941 — I originally reported this on Bun 1.1.21. It was closed as "won't fix" by @Jarred-Sumner who used a modified repro wrapping blobs in a function scope. However, explicitly clearing references (
blobs = []) + forced GC should work identically to scope exit — that's basic GC behavior. The bug persists on 1.3.11. -
Bun memory leak with simple fetch polling script #28427 — Same underlying issue (fetch memory leak), opened recently, also on 1.3.11. The automated bot (robobun) marked it as "unable to reproduce" but used a local HTTP server instead of real remote fetches, which doesn't trigger the same code path for Blob/body buffering.
This is a clean, minimal repro with no cache: "force-cache", no frameworks, no extra dependencies — just fetch → blob() → dereference → GC. The issue is in how Bun's runtime handles Blob/ArrayBuffer backing stores during garbage collection.
Activity
robobun commentedon Apr 1, 2026
✅ Fix submitted in PR #28743.
Root cause:
Bun.gc(true)calledmimalloc_cleanup(false)before running the JS GC. The JS GC is what invokes finalizers (Blob→Store.deref→mi_freeon the backing bytes), so when it ran there was no subsequent mimalloc collection pass — freed pages stayed cached on mimalloc's per-thread heaps instead of returning to the OS. RSS stayed at peak long after every user-visible reference had been collected.Fix: call
mimalloc_cleanup(true)afterrunGC(true)so mimalloc reclaims the pages the GC just freed.Verification: in a 50×1.5MB fetch→blob benchmark (with the loop wrapped in an
async functionso bindings go out of scope on return), released RSS goes from ~0% to ~93%.Note on the exact repro in the issue: the top-level
await+ module-scopeblobspattern keeps local bindings alive in JSC's module async state machine even afterblobs = []— that's a JSC-level limitation not addressed here. Wrapping the loop in anasync functionsidesteps it; memory releases immediately when the function returns.github-actions commentedon Apr 1, 2026
Found 3 possible duplicate issues:
Blob,Uint8Array,ArrayBuffer#20544This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
Clone fetch response buffer to main thread heap for proper GC reclama…
ReD-GuardiaN commentedon Apr 1, 2026
This is not a duplicate. The referenced issues (#20544, #20487, #20912) are different problems.
This issue has already resulted in a fix PR (#28743) that identifies the root cause:
scheduled_response_bufferis allocated on the HTTP thread's mimalloc heap, and when GC frees the Blob on the main JS thread, the memory is never returned to the OS because the HTTP thread is idle.Please do not auto-close.
ReD-GuardiaN commentedon Apr 1, 2026
Linux (Docker) results confirm the leak
Tested in Docker containers (Bun 1.3.11 vs Node v25.8.2) with detailed memory breakdown (
heapUsed,external,arrayBuffers):Bun 1.3.11 (Linux):
Node v25.8.2 (Linux):
external(39.9mb)arrayBuffers(40.7mb)Key observations:
externalmemory and reportsarrayBuffersas 0 — it doesn't track them properlyarrayBuffersand frees 99.7% of it after GCrobobun commentedon Apr 1, 2026
@ReD-GuardiaN The CI failures are pre-existing macOS test flakes — the same 4 darwin tests fail with the same exit codes on the most recently merged PR (#28733). All Linux/Alpine/Ubuntu builds and tests pass on this PR.
The fix itself is a small change in
FetchTasklet.zig: when transferring the response buffer from the HTTP thread to the body value on the main thread, the data is now cloned into a fresh main-thread allocation instead of just moving the pointer. This way, when GC later frees the Blob, mimalloc can properly return those pages to the OS.ReD-GuardiaN commentedon Apr 1, 2026
The leak is wider than just fetch — comprehensive API test
I tested multiple Bun APIs for the same memory leak pattern (allocate 50x 1MB buffers → clear references → GC → measure). Results show 8 out of 12 APIs leak in Bun, while Node releases ~99% in all cases.
Bun 1.3.11 vs Node v25.6.0 (Windows x64):
fetch → blobfetch → arrayBufferfetch → textBun.file → arrayBufferBun.file → textBun.file → bytesBun.spawn stdoutgunzipSynclocalhost fetch → bloblocalhost fetch → arrayBufLocal new Blob()Local ArrayBufferKey findings:
Bun.file()leaks too — same pattern as fetch. PR Run mimalloc cleanup after sync GC so freed pages return to the OS #28743 only fixesFetchTasklet.zig, not file I/OgunzipSyncleaks — this is a synchronous call, so the cross-thread mimalloc explanation doesn't fully cover itlocalhost fetchleaks blobs — contradicts the robobun bot's "unable to reproduce" on Bun memory leak with simple fetch polling script #28427 (they tested localhost but didn't check memory release)Local Blob()andLocal ArrayBuffershow leaks in sequential testing, suggesting accumulated pressure on Bun's GCThis points to a systemic issue with how Bun's GC tracks and releases native/external memory, not just a fetch-specific mimalloc cross-thread problem.
Repro script: https://gist.github.com/ReD-GuardiaN/df884176daef29535839085fbb477ee4 — single file, works with both
bun test-other-apis.jsandnode --expose-gc test-other-apis.js.piazzatron commentedon Apr 14, 2026
I went down a deep rabbit hole this afternoon before finding this issue. Decoding an image to an
arrayBufferand returning it viaHono.bodyfinds that memory is never reclaimed (despited repeatedBun.gc(true)). I have my Bun service restarting daily on a cron because of this issue.A basic repro path:
Happy to share more detailed investigations from Claude today, etc. My server should consume ~200mb of RAM; this issue causes it gradually creep up to 3gb+.
Clone fetch response buffer to main thread heap for proper GC reclama…
Run mimalloc cleanup after sync GC so freed pages return to the OS
alii commentedon May 13, 2026
Couldn't reproduce this on Bun 1.3.13 (linux x64). Closing — if you're still hitting it on the latest release, please drop a fresh repro and we'll reopen.
sorenbs commentedon May 18, 2026
@alii - I can still reproduce this. I also tested against the Rust rewrite, as that has fixed another memory leak I have been tracking over here #29083 (comment)
Codex:
Reproduced and validated.
I used the exact issue repro code in:
I also added the function-scope variant described in the bot comment:
Versions tested:
1.3.14+0d9b296af(oven/bun:1.3.14)1.3.14-canary.1+172afa532(oven/bun:canary)I tested both
linux/arm64andlinux/amd64containers.Result summary (top-level issue repro)
These all print
❌ Memory leak — GC did not free blobs.Function-scope variant (comment-claimed fix path)
These print
✅ GC working.Conclusion
#28741is still reproducible on 1.3.14 and on latest canary when using the exact top-level repro pattern from the issue.alii commentedon May 24, 2026
@robobun try harder to reproduce with the above information.
robobun commentedon May 24, 2026
Reproduced on Bun 1.4.0 / current main (linux x64), using the exact top-level repro from this issue — and tracked down what is actually holding the memory.
TL;DR: this is not a fetch/Blob/allocator bug. After
blobs = [], the old array (and its 50 blobs) is still GC-reachable: a temporary that was live acrossawaitinsideblobs.push(await res.blob())was saved into the module's async ("top-level await") frame by JavaScriptCore, and those saved slots are never cleared. For a TLA module that frame is pinned for the lifetime of the process, soBun.gc(true)can't collect the blobs no matter how many times it runs. The same numbers @sorenbs got on 1.3.14/canary reproduce here.Reproduction matrix (Bun 1.4.0, linux x64)
blobs.push(await res.blob()), thenblobs = []+ 3×Bun.gc(true)+ 8 sbun:jscheapStats()still reports all 50 Blobs liveasync functionthat returns before the GC (the #12941 variant)Uint8Arrayviabufs.push(await makeBuf())in a TLA module, thenbufs = []bufs.length = 0) instead of reassigningRow 3 shows fetch/Blob are not part of the problem. Row 4 shows the GC and the allocator free the memory — and return RSS to the OS — as soon as the objects genuinely become unreachable. So the only question is why the old array is still reachable after
blobs = [].What actually retains the blobs
Retainer chain for one of the leaked 1 MB buffers from variant 3, taken from a V8-format heap snapshot after the module finished evaluating and after another
Bun.gc(true):No user-visible variable references the old array anymore — it is referenced by an anonymous numbered slot of the module's async frame.
Why that slot exists (JSC mechanics)
When a function or module body contains
await, JSC rewrites it ("generatorification") so that every register that is live across a suspension point is saved into a heap-allocated frame and restored on resume. Inblobs.push(await res.blob()), the registers holdingblobsandblobs.pushare loaded before the awaited expression, so they are live across theawaitand get saved at every loop iteration:await, the frame is the module environment itself, stored on the module record (BytecodeGenerator.cpp#L1136-L1140) — and module records are pinned by the loader registry for the lifetime of the process. Nothing clears the frame (or its spill slots) when evaluation completes.Net effect: after
blobs = []the binding points at a new array, but the stale spill slot written at the lastawaitof the loop still points at the old array with all 50 blobs. In a TLA module that reference survives until the process exits; inside an async function it survives for as long as the function is suspended (variant 5). So "clearing the reference + forcing GC" doesn't behave like scope exit here because the cleared binding was not the only reference — an engine-internal saved register still points at the old array. Node releases ~97 % on the identical script, so V8 evidently does not pin these dead cross-awaittemporaries the same way.Why earlier investigations disagreed
awaitand whether a laterawaitoverwrites those slots, so superficially equivalent snippets can behave differently.process.memoryUsage().external+require("bun:jsc").heapStats().objectTypeCountsis a much more reliable signal than RSS for this.Bun.gc) couldn't help because the objects are never collected in the first place.Where a fix needs to go
This is JavaScriptCore codegen/GC behavior, so the fix belongs in Bun's WebKit fork (oven-sh/WebKit) rather than in Bun's runtime code:
BytecodeGeneratorification, when emitting the save sequence at a suspension point, also clear (storeundefinedinto) the already-allocated frame slots that are not live at that point. The stale reference then disappears at the nextawait, matching the behavior users expect from V8.Workarounds that work today
blobs.length = 0— instead of reassigning the binding (row 4).Both release the memory (including RSS) immediately on current Bun.
Pure-JS repro (no network) and the retainer-chain script
repro-purejs.mjs— run withbun repro-purejs.mjsandnode --expose-gc repro-purejs.mjs. FlipCLEAR_MODEto comparebufs = []vsbufs.length = 0.Output on Bun 1.4.0:
CLEAR_MODE=reassign→live after GC: Uint8Array=50,Released RSS: 0.0mb (0.0%);CLEAR_MODE=length→live after GC: Uint8Array=0,Released RSS: 50.3mb (98.6%). Node v24 releases ~93 % of RSS and dropsarrayBuffersto 0 either way.retainers.mjs— produces the retainer chain above (bun retainers.mjs).