Skip to content
Source
Sign inSign up
TanStack/router

Potential Memory Leak in TanStack Start with SSR Streaming #5289

Closedjlucaso1(GitHub profile, opens in a new tab) opened this issue 7 comments

Which project does this relate to?

Start

Describe the bug

When a TanStack Start application is put under load, its memory usage grows linearly with each request that involves SSR streaming of a component. This eventually leads to performance degradation, connection errors, and server crashes. The issue seems specific to SSR-rendered pages. Pure API routes (e.g., a GET handler returning a simple response) do not exhibit the same memory growth. We have been able to reproduce this behavior on the Bun runtime.

Your Example Website or App

https://github.com/TanStack/router/tree/main/examples/react/start-bun

Steps to Reproduce the Bug or Issue

cd start-bun bun install bun run build && bun run start oha "http://localhost:3000/" -c 100 -n 10000

While the test is running, observe the server's memory usage using a tool like htop or your system's activity monitor.

Expected behavior

The server's memory usage should remain stable and relatively low throughout the load test. The test should complete with a very high success rate (>99%) and minimal connection errors.

Screenshots or Videos

https://github.com/user-attachments/assets/32c1ce0c-8bd9-4c3b-80b3-390f851f2ccc

Platform

  • Router / Start Version: Start: 1.132.24; Router: 1.132.23
  • OS: Linux
  • Browser: Chrome
  • Browser Version: 140
  • Bundler: vite
  • Bundler Version: 7.1.7

Additional context

No response

  1. Adding this snippet to the top provides some useful info:

    setInterval(() => {
      console.log(require('bun:jsc').heapStats())
      console.log('RSS', (process.memoryUsage.rss() / 1024 / 1024) | 0, 'MB')
    }, 1000)

    We can see that protectedObjectTypeCounts shows 10000 instances of ReadableStream:

    {
      objectTypeCounts: {
        Object: 1150645,
        Function: 943790,
        Array: 570178,
        JSLexicalEnvironment: 390245,
        string: 383718,
        Promise: 120001,
        Set: 100032,
        AsyncFunction: 60170,
        Map: 60148,
        "Cell Butterfly": 50163,
        AbortController: 40002,
        Arguments: 30010,
        Headers: 30004,
        GetterSetter: 20247,
        SparseArrayValueMap: 20055,
        ReadableStream: 20002,
        ReadableStreamDefaultReader: 10002,
        AbortSignal: 10001,
        Request: 10001,
        Response: 10001,
        Structure: 4216,
        UnlinkedFunctionExecutable: 3270,
        FunctionExecutable: 3230,
        FunctionCodeBlock: 1410,
        SymbolTable: 850,
        UnlinkedFunctionCodeBlock: 772,
        NativeExecutable: 738,
        StructureRareData: 536,
        Error: 469,
        InternalPromise: 397,
        PropertyTable: 271,
        FunctionRareData: 261,
        symbol: 175,
        JSModuleEnvironment: 132,
        JSSourceCode: 132,
        ModuleRecord: 132,
        ModuleProgramExecutable: 122,
        UnlinkedModuleProgramCodeBlock: 122,
        RegExp: 108,
        CustomGetterSetter: 82,
        DOMAttributeGetterSetter: 68,
        StructureChain: 54,
        Module: 17,
        UnlinkedProgramCodeBlock: 14,
        WeakMap: 10,
        GeneratorFunction: 9,
        JSPropertyNameEnumerator: 8,
        ProgramExecutable: 7,
        ModuleNamespaceObject: 6,
        JSAsyncGeneratorFunction: 4,
        Callee: 3,
        ImportMeta: 3,
        Stats: 3,
        TextDecoder: 3,
        TextEncoder: 3,
        ArrayBufferSink: 2,
        ArrayBuffer: 2,
        AsyncGeneratorFunction: 2,
        BigInt: 2,
        ByteLengthQueuingStrategy: 2,
        CountQueuingStrategy: 2,
        DebugHTTPServer: 2,
        Dirent: 2,
        Iterator: 2,
        NodeJSFS: 2,
        Performance: 2,
        ReadableByteStreamController: 2,
        ReadableStreamBYOBReader: 2,
        ReadableStreamBYOBRequest: 2,
        ReadableStreamDefaultController: 2,
        StringDecoder: 2,
        TextDecoderStream: 2,
        TextEncoderStream: 2,
        Timeout: 2,
        TransformStreamDefaultController: 2,
        TransformStream: 2,
        URLSearchParams: 2,
        URL: 2,
        WritableStreamDefaultController: 2,
        WritableStreamDefaultWriter: 2,
        WritableStream: 2,
        "Array Iterator": 1,
        AsyncFromSyncIterator: 1,
        AsyncGenerator: 1,
        AsyncIterator: 1,
        BigInt64ArrayPrototype: 1,
        BigUint64ArrayPrototype: 1,
        Boolean: 1,
        Bun: 1,
        DataView: 1,
        ErrorCodeCache: 1,
        EventEmitter: 1,
        EventTarget: 1,
        FinalizationRegistry: 1,
        Float16ArrayPrototype: 1,
        Float32ArrayPrototype: 1,
        Float64ArrayPrototype: 1,
        Generator: 1,
        GlobalObject: 1,
        "Headers Iterator": 1,
        Int16ArrayPrototype: 1,
        Int32ArrayPrototype: 1,
        Int8ArrayPrototype: 1,
        InternalFieldTuple: 1,
        InternalModuleRegistry: 1,
        InternalPromisePrototype: 1,
        Intl: 1,
        "Iterator Helper": 1,
        JSGlobalLexicalEnvironment: 1,
        JSGlobalProxy: 1,
        JSON: 1,
        "Map Iterator": 1,
        Math: 1,
        ModuleLoader: 1,
        NextTickQueue: 1,
        Number: 1,
        ProcessBindingConstants: 1,
        Process: 1,
        Prototype: 1,
        ReadableHTTPResponseSinkController: 1,
        Reflect: 1,
        "RegExp String Iterator": 1,
        "Set Iterator": 1,
        ShadowRealm: 1,
        "String Iterator": 1,
        String: 1,
        Symbol: 1,
        TextEncoderStreamEncoder: 1,
        "URLSearchParams Iterator": 1,
        Uint16ArrayPrototype: 1,
        Uint32ArrayPrototype: 1,
        Uint8ArrayPrototype: 1,
        Uint8ClampedArrayPrototype: 1,
        WeakRef: 1,
        WeakSet: 1,
        WebAssembly: 1,
        console: 1,
        require: 1,
        resolve: 1,
      },
      protectedObjectTypeCounts: {
        ReadableStream: 10000,
        UnlinkedModuleProgramCodeBlock: 122,
        UnlinkedProgramCodeBlock: 14,
        DebugHTTPServer: 1,
        Function: 1,
        GlobalObject: 1,
        Timeout: 1,
      },
      heapSize: 279962463,
      heapCapacity: 372183343,
      extraMemorySize: 23547871,
      objectCount: 4799521,
      protectedObjectCount: 10140,
      globalObjectCount: 1,
      protectedGlobalObjectCount: 1,
    }
    RSS 698 MB

    Adding some console.logs shows it does call at least one end / close function for each ReadableStream. But there seem to be multiple ReadableStream's created per request. If the one directly attached to the Response object hasn't called close or end or similar, that would cause this to happen.

  2. i have identified what causes this:

    here https://github.com/TanStack/router/blob/3bf18a74328194c65c6b8a335d9f5cf9e259135d/packages/start-server-core/src/request-response.ts#L58

    we call toResponse from h3

    the actual problematic part is this:

    https://github.com/h3js/h3/blob/main/src/response.ts#L99

    For bun, FastResponse is just Response, see https://github.com/h3js/srvx/blob/main/src/adapters/bun.ts#L13

    So what this does is really just creating a new Response to set different headers and re-use the previous response's body /(which in case of SSR streaming is a ReadableStream).

    return new Response(
        val.body,
        {
          status: val.status,
          statusText: val.statusText,
          headers: mergeHeaders(eventHeaders, val.headers),
        },
      )

    This works as expected in node (i was not able to reproduce that memory issue there).

    So maybe this is just a bug in bun? @Jarred-Sumner

  3. waiting for upstream bug to be resolved

  4. @schiller-manuel The same seems to be happening with us while we are on node. The server rans out of memory in production after a couple days.

  5. It's a little tricky to fix in Bun without regressions, still working on it.

    I recommend against doing this though. The GC lifetime of ReadableStream is complex and passing the same ReadableStream into two Response objects makes it more complex. And likely one or more AbortSignal's are in use.

    It would not be at all surprising if this pattern creates memory leaks in other runtimes and in browsers too.

  6. @cloudycotton can you please provide a reproducer?

  7. The issue has fixed in latest bun canary (pre 1.3).

Sign in to join this conversation.