Skip to content

Blob/ArrayBuffer memory not reclaimed by GC after dereferencing #28741

Open

Description

@ReD-GuardiaN

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?

  1. Fetch multiple URLs and store the resulting Blobs in an array
  2. Clear the array (blobs = []) to remove all references
  3. Call Bun.gc(true) multiple times, wait 8+ seconds
  4. 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

  1. robobun commented on Apr 1, 2026

    @robobun
    Collaborator

    ✅ Fix submitted in PR #28743.

    Root cause: Bun.gc(true) called mimalloc_cleanup(false) before running the JS GC. The JS GC is what invokes finalizers (Blob → Store.deref → mi_free on 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) after runGC(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 function so 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-scope blobs pattern keeps local bindings alive in JSC's module async state machine even after blobs = [] — that's a JSC-level limitation not addressed here. Wrapping the loop in an async function sidesteps it; memory releases immediately when the function returns.

  2. github-actions commented on Apr 1, 2026

    @github-actions
    Contributor

    Found 3 possible duplicate issues:

    1. Blob allocations cause excessive memory, and GC does not release all memory / Windows 10 / Blob,Uint8Array,ArrayBuffer #20544
    2. Memory leak when downloading file (both @google-cloud/storage and Bun's S3) #20487
    3. Doing a large amount of fetch requests results in a memory leak #20912

    This issue will be automatically closed as a duplicate in 3 days.

    • If your issue is a duplicate, please close it and 👍 the existing issue instead
    • To prevent auto-closure, add a comment or 👎 this comment

    🤖 Generated with Claude Code

  3. added a commit that references this issue on Apr 1, 2026
    9f38736
  4. ReD-GuardiaN commented on Apr 1, 2026

    @ReD-GuardiaN
    Author

    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_buffer is 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.

  5. ReD-GuardiaN commented on Apr 1, 2026

    @ReD-GuardiaN
    Author

    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):

    Start: rss=31.0mb heap=0.2mb ext=0.0mb ab=0.0mb
    Peak:  rss=84.9mb heap=40.1mb ext=39.9mb ab=0.0mb
    After GC: rss=85.1mb heap=37.9mb ext=37.7mb ab=0.0mb
    Released: heap=2.2mb ext=2.2mb ab=0.0mb
    

    Node v25.8.2 (Linux):

    Start: rss=41.4mb heap=3.7mb ext=1.4mb ab=0.0mb
    Peak:  rss=136.7mb heap=8.4mb ext=6.6mb ab=40.7mb
    After GC: rss=136.8mb heap=7.8mb ext=3.6mb ab=0.1mb
    Released: heap=0.6mb ext=3.0mb ab=40.6mb
    
    Bun 1.3.11 Node v25.8.2
    Blob storage external (39.9mb) arrayBuffers (40.7mb)
    After GC 37.7mb external (5% freed) 0.1mb arrayBuffers (99.7% freed)

    Key observations:

    • Bun stores blob data as external memory and reports arrayBuffers as 0 — it doesn't track them properly
    • Node correctly tracks blob data under arrayBuffers and frees 99.7% of it after GC
    • RSS doesn't drop on Linux for either runtime (normal OS behavior — pages stay mapped), but the underlying allocations are freed in Node and retained in Bun
    • Confirms the root cause: blob data lives on the HTTP thread's mimalloc heap and can't be reclaimed by main-thread GC
  6. robobun commented on Apr 1, 2026

    @robobun
    Collaborator

    @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.

  7. ReD-GuardiaN commented on Apr 1, 2026

    @ReD-GuardiaN
    Author

    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):

    API Bun released Node released Status
    fetch → blob 69.7% 76.6% OK
    fetch → arrayBuffer 0.7% 99.4% LEAK
    fetch → text -0.0% 91.3% LEAK
    Bun.file → arrayBuffer -15.8% — LEAK
    Bun.file → text 42.0% — LEAK
    Bun.file → bytes 204.4% — OK
    Bun.spawn stdout 90.3% 97.6% OK
    gunzipSync 37.3% 100.7% LEAK
    localhost fetch → blob 33.7% — LEAK
    localhost fetch → arrayBuf 93.2% — OK
    Local new Blob() 27.1% 99.8% LEAK
    Local ArrayBuffer 0.2% 92.0% LEAK

    Key findings:

    This 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.js and node --expose-gc test-other-apis.js.

  8. piazzatron commented on Apr 14, 2026

    @piazzatron

    I went down a deep rabbit hole this afternoon before finding this issue. Decoding an image to an arrayBuffer and returning it via Hono.body finds that memory is never reclaimed (despited repeated Bun.gc(true)). I have my Bun service restarting daily on a cron because of this issue.

    A basic repro path:

    1. An outbound fetch() from inside a Bun.serve handler that receives a multi-MB JSON body
    2. JSON.parse() on that body to extract a large base64 string
    3. A main-thread Buffer.from(b64, 'base64') allocation
    4. Hono → Bun.serve writing a ~1.2 MB ArrayBuffer back out to the client

    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+.


      Stack: Bun 1.3.12, Hono, Bun.serve, openai@5.12.2 calling openai.images.generate() which returns a JSON response containing a ~1.6 MB b64_json image payload. I decode to a
      Buffer and return it as an ArrayBuffer via Hono's c.body().
    
  9. added 2 commits that reference this issue on May 5, 2026
    9dc77d6
    00214a8
  10. alii commented on May 13, 2026

    @alii
    Member

    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.

  11. sorenbs commented on May 18, 2026

    @sorenbs

    @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:

    • Stable: 1.3.14+0d9b296af (oven/bun:1.3.14)
    • Canary: 1.3.14-canary.1+172afa532 (oven/bun:canary)

    I tested both linux/arm64 and linux/amd64 containers.

    Result summary (top-level issue repro)

    Runtime Arch Start MB Peak MB After GC MB Released
    1.3.14 arm64 32.6 85.5 83.3 4.2%
    canary arm64 33.3 82.0 81.1 1.9%
    1.3.14 amd64 47.1 101.6 101.2 0.8%
    canary amd64 49.0 104.8 103.7 1.9%

    These all print ❌ Memory leak — GC did not free blobs.

    Function-scope variant (comment-claimed fix path)

    Runtime Arch Released
    1.3.14 arm64 81.2%
    canary arm64 80.7%
    1.3.14 amd64 71.9%
    canary amd64 74.2%

    These print ✅ GC working.

    Conclusion

    • Yes, issue #28741 is still reproducible on 1.3.14 and on latest canary when using the exact top-level repro pattern from the issue.
    • The “fixed” claim appears to be true only for the function-scope variant; it does not hold for the original top-level-await/module-scope repro.
  12. reopened this on May 24, 2026
  13. alii commented on May 24, 2026

    @alii
    Member

    @robobun try harder to reproduce with the above information.

  14. robobun commented on May 24, 2026

    @robobun
    Collaborator

    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 across await inside blobs.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, so Bun.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)

    # Variant Bun Node v24
    1 Exact issue repro: TLA module, blobs.push(await res.blob()), then blobs = [] + 3× Bun.gc(true) + 8 s ❌ ~0 % RSS / 6 % external released; bun:jsc heapStats() still reports all 50 Blobs live ✅ ~97 % of blob bytes released
    2 Same code, but inside an async function that returns before the GC (the #12941 variant) ✅ 78 % RSS / 100 % external released; Blob count drops to 1 ✅
    3 No fetch at all: 50 × 1 MB Uint8Array via bufs.push(await makeBuf()) in a TLA module, then bufs = [] ❌ 0 % released; 50 Uint8Arrays still live ✅ ~97 %
    4 Same as 3, but clear in place (bufs.length = 0) instead of reassigning ✅ 95 % RSS released; 0 live ✅
    5 Same as 3, but inside an async function that is still suspended when the GC runs ❌ 0 % released; 50 still live ✅

    Row 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):

    GC roots
      └─ GlobalObject
          └─ ModuleLoader                          (module registry — lives for the whole process)
              └─ ModuleRegistryEntry
                  └─ ModuleRecord
                      └─ JSModuleEnvironment       (the module's scope, which doubles as its async frame)
                          └─ context slot "16"     (anonymous spill slot — not a user variable)
                              └─ Array             (the OLD `bufs` array that was reassigned away)
                                  └─ [19] → Uint8Array (1.0 MB)
    

    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. In blobs.push(await res.blob()), the registers holding blobs and blobs.push are loaded before the awaited expression, so they are live across the await and get saved at every loop iteration:

    • Each spilled register gets a permanent, dedicated slot in the frame; a later suspension point only overwrites the slots for registers live at that point and never clears stale ones — an intentional optimization (BytecodeGeneratorification.cpp#L142-L167, save sequence at #L234-L256).
    • The GC marks every slot of the frame, whether or not it is still live (JSLexicalEnvironment.cpp#L40-L46, JSModuleEnvironment.cpp#L63-L70).
    • For a module that uses top-level 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 last await of 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-await temporaries the same way.

    Why earlier investigations disagreed

    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:

    1. In BytecodeGeneratorification, when emitting the save sequence at a suspension point, also clear (store undefined into) the already-allocated frame slots that are not live at that point. The stale reference then disappears at the next await, matching the behavior users expect from V8.
    2. Additionally (narrower): clear the frame internal field / spill slots when a generator, async function, or async module body completes, so a finished TLA module doesn't pin its last-saved temporaries for the rest of the process.

    Workarounds that work today

    • Keep large temporary collections inside a function scope that returns before you expect the memory back (row 2), or
    • Clear the collection in place — 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 with bun repro-purejs.mjs and node --expose-gc repro-purejs.mjs. Flip CLEAR_MODE to compare bufs = [] vs bufs.length = 0.

    const COUNT = 50;
    const CLEAR_MODE = process.env.CLEAR_MODE === "length" ? "length" : "reassign";
    const isBun = !!globalThis.Bun;
    
    function mem(label) {
      const m = process.memoryUsage();
      const mb = n => (n / 1024 / 1024).toFixed(1);
      console.log(`${label}: rss=${mb(m.rss)}mb heapUsed=${mb(m.heapUsed)}mb external=${mb(m.external)}mb arrayBuffers=${mb(m.arrayBuffers)}mb`);
      return m;
    }
    
    function liveTypedArrays() {
      if (!isBun) return "(n/a)";
      const c = require("bun:jsc").heapStats().objectTypeCounts;
      return `Uint8Array=${c.Uint8Array ?? 0}`;
    }
    
    async function makeBuf() {
      await new Promise(r => setTimeout(r, 1)); // force a real suspension
      return new Uint8Array(1024 * 1024).fill(7);
    }
    
    let bufs = [];
    const start = mem("Start");
    
    for (let i = 0; i < COUNT; i++) {
      bufs.push(await makeBuf());
    }
    
    console.log(`live at peak: ${liveTypedArrays()}`);
    const peak = mem(`Peak (${bufs.length} buffers)`);
    
    if (CLEAR_MODE === "length") bufs.length = 0;
    else bufs = [];
    
    if (isBun) Bun.gc(true);
    if (global.gc) global.gc();
    await new Promise(r => setTimeout(r, 1000));
    if (isBun) Bun.gc(true);
    if (global.gc) global.gc();
    await new Promise(r => setTimeout(r, 1000));
    if (isBun) Bun.gc(true);
    if (global.gc) global.gc();
    
    console.log(`live after GC: ${liveTypedArrays()}`);
    const final = mem("After GC");
    const pctRss = ((peak.rss - final.rss) / (peak.rss - start.rss)) * 100;
    console.log(`Released RSS: ${((peak.rss - final.rss) / 1024 / 1024).toFixed(1)}mb (${pctRss.toFixed(1)}%)`);

    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 drops arrayBuffers to 0 either way.

    retainers.mjs — produces the retainer chain above (bun retainers.mjs).

    const COUNT = 20;
    
    async function makeBuf() {
      await new Promise(r => setTimeout(r, 1));
      return new Uint8Array(1024 * 1024).fill(7);
    }
    
    let bufs = [];
    for (let i = 0; i < COUNT; i++) bufs.push(await makeBuf());
    
    const { heapStats } = require("bun:jsc");
    console.log("live Uint8Array at peak:", heapStats().objectTypeCounts.Uint8Array ?? 0);
    
    bufs = [];
    Bun.gc(true);
    await new Promise(r => setTimeout(r, 50));
    Bun.gc(true);
    console.log("live Uint8Array after clear+GC:", heapStats().objectTypeCounts.Uint8Array ?? 0);
    
    // Take the snapshot from a macrotask AFTER module evaluation has finished, so
    // whatever retains the buffers at this point retains them for the process lifetime.
    setTimeout(() => {
      Bun.gc(true);
      console.log("live Uint8Array after module evaluation finished + GC:", heapStats().objectTypeCounts.Uint8Array ?? 0);
      analyze(JSON.parse(Bun.generateHeapSnapshot("v8")));
    }, 100);
    
    function analyze(snap) {
      const meta = snap.snapshot.meta;
      const NF = meta.node_fields.length, EF = meta.edge_fields.length;
      const nodeTypes = meta.node_types[0], edgeTypes = meta.edge_types[0];
      const F = Object.fromEntries(meta.node_fields.map((f, i) => [f, i]));
      const E = Object.fromEntries(meta.edge_fields.map((f, i) => [f, i]));
      const { nodes, edges, strings } = snap;
      const nodeCount = nodes.length / NF;
      const nodeName = i => strings[nodes[i * NF + F.name]];
      const nodeType = i => nodeTypes[nodes[i * NF + F.type]];
      const nodeSelfSize = i => nodes[i * NF + F.self_size];
    
      const firstEdge = new Uint32Array(nodeCount + 1);
      for (let i = 0, e = 0; i < nodeCount; i++) {
        firstEdge[i] = e;
        e += nodes[i * NF + F.edge_count];
        firstEdge[i + 1] = e;
      }
      const incoming = new Map();
      for (let from = 0; from < nodeCount; from++) {
        for (let e = firstEdge[from]; e < firstEdge[from + 1]; e++) {
          const to = edges[e * EF + E.to_node] / NF;
          if (!incoming.has(to)) incoming.set(to, []);
          incoming.get(to).push([from, e]);
        }
      }
      const edgeDesc = e => {
        const type = edgeTypes[edges[e * EF + E.type]];
        const n = edges[e * EF + E.name_or_index];
        return { type, name: type === "element" || type === "hidden" ? `[${n}]` : strings[n] };
      };
    
      const targets = [];
      for (let i = 0; i < nodeCount; i++)
        if (nodeName(i) === "Uint8Array" && nodeSelfSize(i) >= 1024 * 1024) targets.push(i);
      console.log(`\nUint8Array nodes >= 1MB still in snapshot: ${targets.length}`);
      if (!targets.length) return;
    
      // BFS from the leaked buffer back to the root along reverse (non-weak) edges.
      const target = targets[0];
      const prev = new Map([[target, null]]);
      const queue = [target];
      while (queue.length) {
        const n = queue.shift();
        if (n === 0) break;
        for (const [from, e] of incoming.get(n) ?? []) {
          if (edgeDesc(e).type === "weak") continue;
          if (!prev.has(from)) { prev.set(from, [n, e]); queue.push(from); }
        }
      }
      console.log("\nRetainer chain from GC root down:");
      let cur = 0;
      while (cur !== null) {
        const p = prev.get(cur);
        const edge = p ? p[1] : null;
        let line = `  ${nodeType(cur)} "${nodeName(cur)}"${nodeSelfSize(cur) >= 1024 * 1024 ? ` (${(nodeSelfSize(cur) / 1048576).toFixed(1)}MB)` : ""}`;
        if (edge !== null) line += `\n      └─(${edgeDesc(edge).type} edge "${edgeDesc(edge).name}")─>`;
        console.log(line);
        cur = p ? p[0] : null;
      }
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions