Skip to content

Native RSS grows linearly under sustained AWS SDK v3 Kinesis GetRecords; identical Node 22 workload is flat #30415

Closed

Description

@hevar

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: rssMb climbs roughly linearly. heapUsedMb
    stays small.
  • Node 22: rssMb settles 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/undici under 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 body of fetch response before consuming the stream.

Activity

  1. github-actions commented on May 9, 2026

    @github-actions
    Contributor

    Found 3 possible duplicate issues:

    1. Bun memory leak with simple fetch polling script #28427
    2. Doing a large amount of fetch requests results in a memory leak #20912
    3. Blob/ArrayBuffer memory not reclaimed by GC after dereferencing #28741

    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

  2. robobun commented on May 9, 2026

    @robobun
    Collaborator

    ✅ Reproduced — 64 concurrent h2 streams via NodeHttp2Handler leak ~380 MB/hr on Bun; Node stays flat.

    Cause: H2FrameParser.streams never dropped entries on stream close — every session.request() added a *Stream and only full session teardown freed them. On an AWS SDK pooled session (one http2.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 one ci: retrigger earlier — needs a maintainer to merge.

  3. Jarred-Sumner commented on Aug 13, 2026

    @Jarred-Sumner
    Collaborator

    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.14 vs canary 1.4.0-canary.1):

    const kinesis = new KinesisClient({ region: "us-east-1", endpoint: "http://127.0.0.1:34568", credentials: { accessKeyId: "x", secretAccessKey: "y" }, maxAttempts: 1 }); // default handler = NodeHttp2Handler
    const pollShard = async (shardId) => { let { ShardIterator: it } = await kinesis.send(new GetShardIteratorCommand({ StreamName: "s", ShardId: shardId, ShardIteratorType: "LATEST" })); while (it && !stop) { it = (await kinesis.send(new GetRecordsCommand({ ShardIterator: it, Limit: 1000 }))).NextShardIterator; reqs++; } };
    setInterval(() => { Bun.gc(true); console.log(reqs, process.memoryUsage().rss / 1048576); }, 5000);
    await Promise.all(Array.from({ length: 64 }, (_, i) => pollShard("shard-" + i)));
    // server: node:http2 createServer, on("stream") -> respond 200 application/x-amz-json-1.1 {"Records":[],"NextShardIterator":"AAAA...","MillisBehindLatest":0}

    Results

    • Bun 1.3.14: client RSS climbed monotonically 163.5 MB -> 264.5 MB over 240 s / ~650k GetRecords requests with the SDK's default NodeHttp2Handler (+101 MB, ~163 B/request, JS heapUsed flat at ~10-45 MB after Bun.gc(true)); printed "BUG: mode=h2 client RSS grew 101.0MB". The 90 s run also grew +36 MB (h2) and +59 MB (forced http/1 handler).
    • Canary: same workload, client RSS 115.1 MB -> 106.5 MB over 240 s / ~660k requests (flat, slightly down), printed "OK: mode=h2 client RSS delta -8.6MB"; forced http/1 handler also flat (111 -> 108.5 MB over 485k requests).
    • Node (reference): RSS 172.6 MB -> 144.2 MB over 240 s / ~460k requests (flat plateau), printed OK — matches the reporter's "Node is flat" baseline; canary now behaves the same.

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

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions