Guide · Runtimes

Bun memory usage: find leaks and slow code with profiling

"Bun uses too much memory" can mean a leak, a large cache, native memory or nothing wrong at all. This guide shows how to tell them apart with object counts, heap snapshots and CPU flamegraphs, plus the practices that keep memory stable in production.

The short answer

  • Memory too high? Compare RSS with the JS heap first. They point to different causes.
  • Memory keeps climbing? Force a garbage collection, compare object counts, then compare two heap snapshots.
  • CPU too high or responses slow? Record a CPU profile and read it as a flamegraph.
  • Whatever you find: change one thing and repeat the same test.

A workflow that works

Observe

Is there a problem?
  1. Reproduce Send the same steady load to the same build every time.
  2. Watch the trend Compare memory after each round, not one peak.

Locate

JS heap or native?
  1. Compare metrics Put RSS, heap and buffers side by side.
  2. Take snapshots One after warm-up, one after more load. Compare them.

Fix

Prove it worked
  1. Change one thing Otherwise you won't know what helped.
  2. Repeat the test Same load, same duration, and compare again.

RSS, heap and native memory

“Bun uses 300 MB” doesn't say much on its own. Bun has two heaps: one for JavaScript objects (JavaScriptCore), and one for everything else (mimalloc).

MetricWhat it tells youWhere to read it
RSSMemory the process holds in RAMprocess.memoryUsage()
JS heapMemory tracked by JavaScriptCoreheapStats()
BuffersBinary data such as Uint8Arrayexternal in process.memoryUsage()
Native heapBun's own allocationsBun.unsafe.mimallocDump()

Don't add these up, because they overlap. In a test on Bun 1.4.4, holding 60 MB of Uint8Array data showed up in both external and heapSize, while arrayBuffers stayed at 0.

How to read them together:

  • RSS and object counts both climb: your code is probably holding on to objects. Start with heap snapshots.
  • RSS climbs but the heap and counts don't: suspect native memory, such as a native addon or the runtime itself. Check the mimalloc output and try the latest Bun version.
  • RSS jumps, then stays flat: often normal. Freed memory isn't always returned to the operating system right away.
  • RSS looks smaller than the heap: possible when the system compresses or swaps memory, for example on macOS. Don't compare a Mac number with a Linux one.

Measure live memory, not garbage

This helper forces a collection first, so you compare what is really being kept:

JavaScript · memory.js
import { heapStats } from "bun:jsc";

const mb = (bytes) => Math.round(bytes / 1024 / 1024);

export function memory() {
  Bun.gc(true); // collect first: compare live objects, not garbage
  const { rss, external } = process.memoryUsage();
  const { heapSize, objectCount, objectTypeCounts } = heapStats();
  const top = Object.entries(objectTypeCounts).sort((a, b) => b[1] - a[1]).slice(0, 8);
  return {
    rssMB: mb(rss), heapMB: mb(heapSize),
    externalMB: mb(external), objectCount, top: Object.fromEntries(top),
  };
}

Watch top between rounds. In a test that kept adding entries to a Map, Date grew from 20,000 to 80,000 over four rounds, and stayed high after every collection. A type that rises steadily with each round is your suspect.

Forcing a collection pauses the process, so use this for diagnosis, not on every request.

CPU flamegraphs

A CPU profile shows which functions are using your time. Bun writes one when the process exits:

Shell
bun --cpu-prof server.js        # .cpuprofile for Chrome DevTools or VS Code
bun --cpu-prof-md server.js     # Markdown report you can read in the terminal

Open the .cpuprofile in the Performance tab of Chrome DevTools with “Load profile”, or in VS Code.

Example flamegraphhandleRequest spans the full width. Below it, buildReport takes about 70 percent, and most of that is JSON.stringify.handleRequestparsebuildReportJSON.stringifysort
Illustrative example. Width is time spent; each lower row was called by the one above it. The wide JSON.stringify is where to look first.
  • Look for wide blocks, not tall stacks. Width is cost; depth is only how many calls led there.
  • Compare self time and total time. High self time means the function itself is expensive. High total time can come from what it calls.
  • Profile under realistic load. An idle server's profile tells you nothing about a busy one.
  • A slow endpoint with an empty CPU profile is probably waiting on a database or network, so optimize that instead.

No profile file? Add a shutdown handler

This one is easy to miss. On Bun 1.4.4, stopping a server with Ctrl+C or SIGTERM wrote no profile at all. After adding a handler that exits cleanly, both the CPU and heap profiles were saved:

JavaScript · server.js
const server = Bun.serve({ port: 3000, fetch: () => new Response("ok") });
for (const signal of ["SIGINT", "SIGTERM"]) {
  process.once(signal, () => {
    server.stop(true); // closes open connections: fine for a profiling run
    process.exit(0);
  });
}

Heap snapshots

A heap snapshot shows what is in memory and what is keeping it there. You can write one on exit, or from a running process:

Shell
bun --heap-prof server.js       # snapshot on exit
bun --heap-prof-md server.js    # Markdown report instead
JavaScript · debug.js (local only)
import { memory } from "./memory.js";
if (process.env.DEBUG_MEMORY === "1") {
  Bun.serve({
    hostname: "127.0.0.1", // never expose this publicly
    port: 6061,
    routes: {
      "/memory": () => Response.json(memory()),
      "/snapshot": async () => {
        const file = `heap-${Date.now()}.heapsnapshot`;
        await Bun.write(file, Bun.generateHeapSnapshot("v8"));
        return new Response(file + "\n");
      },
    },
  });
}
  • Start with DEBUG_MEMORY=1, warm the app up, and take snapshot A.
  • Run the load, stop it, let the app settle, and take snapshot B.
  • Load both in the Memory tab of Chrome DevTools. If the file ends in .heapprofile, rename it to .heapsnapshot.
  • Select B, switch from Summary to Comparison, and sort by Delta.
  • Open a growing type and follow its Retainers. That chain is the code keeping it alive.

Treat snapshots as secrets. They contain your app's real data, including tokens and personal details. Taking one also pauses the app and needs extra memory, so avoid it on an instance that is already near its limit.

Common causes of growing memory

  • Unbounded caches: a Map that only ever grows. Add a size limit or an expiry.
  • Listeners never removed: everything they reference stays alive. Use once or remove them.
  • Forgotten timers: clear every setInterval when its owner goes away.
  • Closures over large objects: keep only the fields you need.
  • Promises that never settle: put a timeout on outgoing calls, for example AbortSignal.timeout(5000).
  • Whole files or responses in memory: stream large data, and don't start unlimited work at once.

A cache with a limit is only a few lines, with no dependency:

JavaScript · bounded-cache.js
class BoundedCache {
  #map = new Map();
  constructor(max = 1000) { this.max = max; }
  get(key) {
    if (!this.#map.has(key)) return undefined;
    const value = this.#map.get(key);
    this.#map.delete(key);       // re-insert so recently used keys go last
    this.#map.set(key, value);
    return value;
  }
  set(key, value) {
    this.#map.delete(key);
    this.#map.set(key, value);
    if (this.#map.size > this.max) this.#map.delete(this.#map.keys().next().value);
  }
}

Common practices for production

  • Set a memory limit on the container and alert before you reach it.
  • Chart RSS over days, next to request rate and deploys. One reading can't show a trend.
  • Load test for hours before migrating. Short benchmarks miss slow leaks.
  • Test --smol on small instances. It collects garbage more often to use less memory, which can cost CPU.
  • Pin the Bun version and repeat your memory test when you upgrade.
  • Restarting on a schedule is a stopgap. It buys time, but keep looking for the cause.

Bun and Node.js profiling commands

TaskBunNode.js
CPU profilebun --cpu-profnode --cpu-prof
Readable reportbun --cpu-prof-mdNo built-in equivalent flag
Heap snapshotBun.generateHeapSnapshot("v8")v8.writeHeapSnapshot()
Force collectionBun.gc(true)gc() with --expose-gc
Heap statisticsheapStats() from bun:jscv8.getHeapStatistics()

The Bun commands were tried on Bun 1.4.4. They change between releases, so check bun --help on yours. Still choosing a runtime? See Bun vs Node.js in production.

FAQ

How do I check Bun memory usage?

Use process.memoryUsage() for RSS and heapStats() from bun:jsc for the JavaScript heap. Run Bun.gc(true) first when diagnosing, so you compare live objects instead of garbage, and look at the trend over several rounds of load.

Does Bun use less memory than Node.js?

It depends on the workload, the versions and the operating system, and published results disagree. Run your own app on both runtimes with the same load for several hours and compare RSS over time.

How do I create a flamegraph in Bun?

Run your app with bun --cpu-prof, send it realistic load and exit cleanly. Bun writes a .cpuprofile file that you can open in the Performance tab of Chrome DevTools or in VS Code.

Why did bun --cpu-prof not create a file?

Bun writes the profile when the process exits. In a test on Bun 1.4.4, stopping a server with Ctrl+C or SIGTERM wrote nothing until the app handled the signal and called process.exit().

How do I know if my Bun app has a memory leak?

Apply the same load in rounds, force a garbage collection after each one, and compare. If memory or the count of one object type keeps rising every round and never levels off, it's probably a leak. Compare two heap snapshots to find what is holding on to it.