Repository navigation
Description
What version of Bun is running?
1.3.13
What platform is your computer?
Linux x86_64
What steps can reproduce the bug?
A minimal program is enough - no Postgres, no parsing, no business logic.
// repro.ts
import {
GetRecordsCommand,
GetShardIteratorCommand,
KinesisClient,
ListShardsCommand,
type Shard,
} from "@aws-sdk/client-kinesis"
const STREAM = process.env.KINESIS_STREAM!
const REGION = process.env.AWS_REGION ?? "eu-central-1"
const CONCURRENCY = Number(process.env.SHARD_CONCURRENCY ?? "64")
const POLL_MS = 1000
const kinesis = new KinesisClient({ region: REGION })
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms))
const listAllShards = async (): Promise<Shard[]> => {
const shards: Shard[] = []
let nextToken: string | undefined
do {
const resp = await kinesis.send(
new ListShardsCommand({
StreamName: nextToken ? undefined : STREAM,
NextToken: nextToken,
}),
)
if (resp.Shards) shards.push(...resp.Shards)
nextToken = resp.NextToken
} while (nextToken)
return shards
}
const pollShard = async (shardId: string) => {
const { ShardIterator } = await kinesis.send(
new GetShardIteratorCommand({
StreamName: STREAM,
ShardId: shardId,
ShardIteratorType: "LATEST",
}),
)
let iterator = ShardIterator
while (iterator) {
const resp = await kinesis.send(
new GetRecordsCommand({ ShardIterator: iterator, Limit: 1000 }),
)
// Discard records — the leak is in the fetch path, not the consumer
iterator = resp.NextShardIterator
await sleep(POLL_MS)
}
}
const main = async () => {
const shards = (await listAllShards()).slice(0, CONCURRENCY)
console.log(`polling ${shards.length} shards`)
setInterval(() => {
const m = process.memoryUsage()
console.log(
JSON.stringify({
rssMb: Math.round(m.rss / 1024 / 1024),
heapUsedMb: Math.round(m.heapUsed / 1024 / 1024),
externalMb: Math.round(m.external / 1024 / 1024),
}),
)
}, 10_000)
await Promise.all(shards.map((s) => pollShard(s.ShardId!)))
}
main()Run on a Kinesis stream with at least 64 active shards under steady load.
Watch rssMb over a 20-minute window.
- Bun 1.3.13 / 1.3.14:
rssMbclimbs roughly linearly.heapUsedMb
stays small. - Node 22:
rssMbsettles to a plateau within ~5 minutes and stays.
If you can't reproduce against a real stream, localstack Kinesis with a
synthetic shard generator works too — what matters is the sustained
GetRecordsCommand rate (≥ 64 RPS combined), not the data content. Records
can be empty.
What is the expected behavior?
No response
What do you see instead?
No response
Additional information
A long-running Bun service that polls many Amazon Kinesis shards in parallel
via @aws-sdk/client-kinesis (AWS SDK v3) leaks native RSS at ~1 GB/hour. The
JavaScript heap stays flat throughout — RSS growth is entirely outside the
managed heap. Forcing GC via Bun.gc(true) does not reclaim the memory.
The same code, same dependencies, same workload — running on Node 22.22.2 —
shows a flat RSS plateau (slope in measurement noise, ~13 MB/hour). The
runtime is the only variable that changed.
This matches the symptom shape of #18488
(open since Bun 1.1.27); we suspect the same underlying cause but have a
production-scale data set that may help narrow it.
| Field | Value |
|---|---|
| Bun versions tested | 1.3.13 (latest stable at time of test) and 1.3.14 (canary) — both leak |
| Node version compared against | 22.22.2 — does not leak |
| OS | Linux x86_64 |
| Container | Docker, base oven/bun:1.3.13-debian (Bun) / node:22-slim (Node), running on AWS Fargate |
| Memory limit | 8192 MiB (Fargate) |
@aws-sdk/client-kinesis |
^3.700.0 |
@aws-sdk/credential-providers |
^3.700.0 |
aws-kinesis-agg |
^4.2.8 (KPL deaggregation; pure JS / protobufjs under the hood) |
pg |
^8.20.0 |
pino |
^10.3.1 |
| Workload | 128 Kinesis shards × 1 GetRecordsCommand per second per shard, ~5K events/sec post-deaggregation |
Slope was measured by reading process.memoryUsage().rss every 10 s and
fitting a linear slope over a 15+ minute post-startup window.
| Build | Runtime | RSS slope |
|---|---|---|
| ALS-on (default) | Bun 1.3.13 | ~484 MB/hr at hour 1, accelerating to ~1,300 MB/hr by hour 4 |
| ALS-off | Bun 1.3.13 | ~1,254 MB/hr |
| Canary | Bun 1.3.14 | ~1,284 MB/hr |
| Reference | Node 22.22.2 | ~13 MB/hr (in noise) |
Sample log line from a Bun task during the climb:
{"shardsActive":128,"memRssMb":4660,"memHeapTotalMb":20,"memHeapUsedMb":33,
"memExternalMb":23,"memArrayBuffersMb":11,"memNativeApproxMb":4607,"msg":"stats"}Sample log line from the Node task at a comparable lifecycle point:
{"shardsActive":128,"memRssMb":851,"memHeapTotalMb":20,"memHeapUsedMb":31,
"memExternalMb":9,"memArrayBuffersMb":5,"memNativeApproxMb":811,"msg":"stats"}memNativeApproxMb = rss - heapUsed - external — i.e. RSS minus everything
the JS engine and Node-style external buffers explicitly account for. On
Bun, this approaches RSS itself; on Node, it stays roughly proportional to
RSS (reasonable JIT / native-stack cost) and does not grow.
A post-Bun.gc(true) heap report taken from a Bun task at ~7 GB RSS:
{"rssAfterMb":7383,"heapSizeMb":19,"heapCapacityMb":25,"extraMemoryMb":12,
"objectCount":105781,"msg":"heap report (post-gc)"}JS heap is tiny and stable. The leak is entirely outside the managed heap.
What we ruled out:
We ran a series of canaries that each isolated one variable. All preserved
the same code paths and dependencies; only the toggled variable changed.
| Hypothesis | How it was tested | Result |
|---|---|---|
AsyncLocalStorage cost / leak |
Replaced the asyncContext.run(...) wrapper around each batch with a direct call (no ALS) |
RSS slope identical (~1,254 MB/hr) |
| Bun 1.3.13 → 1.3.14 regression | Re-ran on oven/bun:canary-debian (resolved to 1.3.14) |
RSS slope identical (~1,284 MB/hr) |
| JS heap retention | Bun.gc(true) + heapStats() snapshot at high-water RSS |
Heap stays at 19–43 MB regardless of RSS |
Buffer pool growth |
process.memoryUsage().external and arrayBuffers over time |
Both stay tiny (10–30 MB) |
| The application code (parser, pg, pino, AWS SDK) | Identical code on Node 22 | RSS plateau, no leak |
The last row is the load-bearing one: identical code, same dependency
versions, same workload — switching only the runtime makes the leak vanish.
Related issues(?):
- #18488 — open since Bun 1.1.27, "memory leak when streaming responses via fetch". Likely the same root cause given that the AWS SDK v3 client uses
fetch/undiciunder the hood for HTTP transport. - #21560 — RSS grows in spawned child process even when idle.
- #27514 — severe RSS retention with low JS heap (Next.js SSR on Bun).
- #13678 — memory leak if accessing
bodyof fetch response before consuming the stream.
Activity
github-actions commentedon May 9, 2026
Found 3 possible duplicate issues:
This issue will be automatically closed as a duplicate in 3 days.
🤖 Generated with Claude Code
robobun commentedon May 9, 2026
✅ Reproduced — 64 concurrent h2 streams via
NodeHttp2Handlerleak ~380 MB/hr on Bun; Node stays flat.Cause:
H2FrameParser.streamsnever dropped entries on stream close — everysession.request()added a*Streamand only full session teardown freed them. On an AWS SDK pooled session (onehttp2.connect()per origin) memory grows linearly with request count.Fix: #30416 — reclaim closed streams on every terminal transition, with careful re-entry safety (detach-before-freeResources, re-resolve across user getters / Symbol.toPrimitive / dispatchWriteCallback).
Diff is green across every CI lane except a recurring Windows HTTP/1 flake —
test-http-should-emit-close-when-connection-is-aborted.ts(fetch+AbortController, no h2 involvement) timing out 4× on x64-baseline. Builds 53010, 53012, 53016 all failed on Windows-only flakes unrelated to h2. Already spent the oneci: retriggerearlier — needs a maintainer to merge.h2: scope stale-stream detection to the client side
h2: don't remove server-side streams from the map
Jarred-Sumner commentedon Aug 13, 2026
Thanks for the detailed report and the ruled-out list, it made this easy to pin down. robobun's diagnosis in the thread was right: closed client streams stayed in the http2 session's stream map for the life of the pooled session the AWS SDK's NodeHttp2Handler keeps open, so RSS grew per GetRecords call. That retention was fixed by the node:http2 engine rewrite in #31584, and rerunning your poll loop with the real Kinesis client against a local endpoint now stays flat on the current canary while 1.3.14 still climbs.
What I ran (in Docker,
oven/bun:1.3.14vs canary1.4.0-canary.1):Results
This is in the current canary now (
bun upgrade --canary) and will be in Bun v1.4.0. If it still reproduces for you there, comment here and we'll reopen.(This comment was written by Claude, on behalf of the Bun team.)