Skip to content

bug: memory leak in trpc 11 subscriptions. #6156

Closed

Description

@AlexSua

Provide environment information

Binaries:
Node: 18.20.4 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 10.7.0 - /usr/local/bin/npm
pnpm: 8.9.2 - /usr/local/bin/pnpm
bun: 1.0.7 - /usr/local/bin/bun
npmPackages:
@trpc/server: 11.0.0-rc.593 => 11.0.0-rc.593+f73cd3fd9
typescript: ^5.5.4 => 5.6.2

node --version
v18.20.4

Nest app with typeorm that uses trpc.

Describe the bug

When emitting large strings, either using observables or the yield function in generators, I notice memory usage increases while the WebSocket connection is open. Once the connection closes, the memory is released.

In my original setup, where I detected the leak, I had Redis subscribers listening for events within the observable, and I was properly freeing all resources and closing any open connections.

This issue occurs in version 11 of tRPC but not in version 10.

node --inspect --expose_gc --max_old_space_size=700 --optimize_for_size dist/src/main.js

Using the same setup for trpc 11 and 10:

// TRPC 11
The script uses approximately 198.88 MB - cache 0
The script uses approximately 198.21 MB - cache 0
The script uses approximately 198.93 MB - cache 0
The script uses approximately 196.57 MB - cache 0
The script uses approximately 195.12 MB - cache 0
The script uses approximately 195.05 MB - cache 0
The script uses approximately 195.04 MB - cache 0
The script uses approximately 195.11 MB - cache 0
The script uses approximately 195.22 MB - cache 0
The script uses approximately 195.6 MB - cache 0
The script uses approximately 195.29 MB - cache 0
The script uses approximately 195.89 MB - cache 0
The script uses approximately 195.37 MB - cache 0
The script uses approximately 195.27 MB - cache 0
The script uses approximately 195.14 MB - cache 0
The script uses approximately 195.11 MB - cache 0
The script uses approximately 195.37 MB - cache 0
The script uses approximately 195.11 MB - cache 0
//HERE STARTS THE TRPC SUBSCRIPTION
The script uses approximately 200.96 MB - cache 0.06345272064208984
The script uses approximately 241.62 MB - cache 0.3078422546386719
The script uses approximately 213.58 MB - cache 0.3078422546386719
The script uses approximately 263.7 MB - cache 0.3078422546386719
The script uses approximately 238.31 MB - cache 0.3078422546386719
The script uses approximately 288.44 MB - cache 0.3078422546386719
The script uses approximately 263.23 MB - cache 0.30820369720458984
The script uses approximately 313.07 MB - cache 0.30820369720458984
The script uses approximately 286.77 MB - cache 0.30820369720458984
The script uses approximately 336.95 MB - cache 0.30820369720458984
The script uses approximately 311.63 MB - cache 0.30820369720458984
The script uses approximately 361.76 MB - cache 0.30820369720458984
The script uses approximately 336.34 MB - cache 0.30820369720458984
The script uses approximately 386.75 MB - cache 0.30820369720458984
The script uses approximately 361.23 MB - cache 0.30820369720458984
The script uses approximately 411.57 MB - cache 0.30820369720458984
The script uses approximately 430.67 MB - cache 0.30820369720458984
The script uses approximately 397.54 MB - cache 0.30820369720458984
The script uses approximately 447.75 MB - cache 0.30820369720458984
The script uses approximately 461.06 MB - cache 0.30820369720458984
The script uses approximately 474.29 MB - cache 0.30820369720458984
The script uses approximately 487.8 MB - cache 0.30820369720458984
The script uses approximately 462.29 MB - cache 0.30820369720458984
The script uses approximately 473.89 MB - cache 0.30820369720458984
The script uses approximately 560.98 MB - cache 0.30820369720458984
The script uses approximately 535.57 MB - cache 0.30820369720458984
The script uses approximately 585.57 MB - cache 0.30820369720458984
The script uses approximately 560.33 MB - cache 0.30820369720458984
The script uses approximately 610.53 MB - cache 0.30820369720458984
The script uses approximately 585.13 MB - cache 0.30820369720458984
The script uses approximately 598.48 MB - cache 0.30820369720458984
The script uses approximately 573.07 MB - cache 0.30820369720458984
The script uses approximately 623.29 MB - cache 0.30820369720458984
The script uses approximately 597.75 MB - cache 0.30820369720458984
The script uses approximately 646.25 MB - cache 0.30820369720458984

//TRPC 10
The script uses approximately 197.55 MB - cache 0
The script uses approximately 197.59 MB - cache 0
//HERE STARTS THE TRPC SUBSCRIPTION
The script uses approximately 204.9 MB - cache 2.951091766357422
The script uses approximately 223.55 MB - cache 0
The script uses approximately 196.85 MB - cache 0
The script uses approximately 196.32 MB - cache 0
The script uses approximately 217.12 MB - cache 0.12111759185791016
The script uses approximately 217.19 MB - cache 0.12111759185791016
The script uses approximately 217.48 MB - cache 0.12111759185791016
The script uses approximately 217.05 MB - cache 0.12111759185791016
The script uses approximately 217.25 MB - cache 0.12111759185791016
The script uses approximately 219.32 MB - cache 0.12111759185791016
The script uses approximately 217.07 MB - cache 0.12111759185791016
The script uses approximately 217.17 MB - cache 0.12111759185791016
The script uses approximately 217.26 MB - cache 0.12111759185791016
The script uses approximately 217.31 MB - cache 0.12111759185791016
The script uses approximately 217.22 MB - cache 0.12111759185791016
The script uses approximately 219.24 MB - cache 0.12111759185791016
The script uses approximately 217.23 MB - cache 0.12111759185791016
The script uses approximately 217.1 MB - cache 0.12111759185791016
The script uses approximately 217.45 MB - cache 0.12111759185791016
The script uses approximately 217.33 MB - cache 0.12111759185791016
The script uses approximately 217.19 MB - cache 0.12111759185791016
The script uses approximately 217.2 MB - cache 0.12111759185791016
The script uses approximately 219.34 MB - cache 0.12111759185791016
The script uses approximately 217.35 MB - cache 0.12111759185791016
The script uses approximately 219.59 MB - cache 0.12111759185791016
The script uses approximately 217.27 MB - cache 0.12111759185791016
The script uses approximately 217.74 MB - cache 0.12111759185791016
The script uses approximately 217.21 MB - cache 0.12111759185791016
The script uses approximately 217.5 MB - cache 0.12111759185791016
The script uses approximately 217.22 MB - cache 0.12111759185791016
The script uses approximately 217.51 MB - cache 0.12111759185791016
The script uses approximately 217.61 MB - cache 0.12111759185791016
The script uses approximately 217.34 MB - cache 0.12111759185791016
The script uses approximately 217.6 MB - cache 0.12111759185791016
The script uses approximately 217.34 MB - cache 0.12111759185791016
The script uses approximately 217.33 MB - cache 0.12111759185791016
The script uses approximately 217.75 MB - cache 0.12111759185791016
The script uses approximately 217.3 MB - cache 0.12111759185791016
The script uses approximately 217.35 MB - cache 0.12111759185791016
The script uses approximately 217.39 MB - cache 0.12111759185791016
The script uses approximately 219.45 MB - cache 0.12111759185791016
The script uses approximately 217.66 MB - cache 0.12111759185791016
The script uses approximately 217.26 MB - cache 0.12111759185791016
The script uses approximately 217.35 MB - cache 0.12111759185791016
The script uses approximately 219.52 MB - cache 0.12111759185791016
The script uses approximately 217.28 MB - cache 0.12111759185791016
The script uses approximately 219.69 MB - cache 0.12111759185791016
The script uses approximately 217.38 MB - cache 0.12111759185791016
The script uses approximately 219.6 MB - cache 0.12111759185791016
The script uses approximately 217.67 MB - cache 0.12111759185791016
The script uses approximately 217.26 MB - cache 0.12111759185791016
The script uses approximately 217.41 MB - cache 0.12111759185791016
The script uses approximately 217.31 MB - cache 0.12111759185791016
The script uses approximately 217.55 MB - cache 0.12111759185791016
The script uses approximately 217.74 MB - cache 0.12111759185791016
The script uses approximately 217.28 MB - cache 0.12111759185791016
The script uses approximately 217.81 MB - cache 0.12111759185791016
The script uses approximately 217.4 MB - cache 0.12111759185791016
The script uses approximately 219.52 MB - cache 0.12111759185791016
The script uses approximately 217.36 MB - cache 0.12111759185791016
The script uses approximately 219.5 MB - cache 0.12111759185791016
The script uses approximately 217.42 MB - cache 0.12111759185791016
The script uses approximately 217.35 MB - cache 0.12111759185791016
The script uses approximately 217.39 MB - cache 0.12111759185791016
The script uses approximately 217.43 MB - cache 0.12111759185791016
The script uses approximately 219.58 MB - cache 0.12111759185791016
The script uses approximately 217.7 MB - cache 0.12111759185791016
The script uses approximately 217.42 MB - cache 0.12111759185791016
The script uses approximately 217.32 MB - cache 0.12111759185791016
The script uses approximately 217.41 MB - cache 0.12111759185791016
The script uses approximately 219.63 MB - cache 0.12111759185791016
The script uses approximately 217.39 MB - cache 0
The script uses approximately 217.15 MB - cache 0
The script uses approximately 217.15 MB - cache 0
The script uses approximately 217.05 MB - cache 0
The script uses approximately 217.09 MB - cache 0
The script uses approximately 217.44 MB - cache 0
The script uses approximately 217.08 MB - cache 0
The script uses approximately 217.08 MB - cache 0
The script uses approximately 219.54 MB - cache 0
The script uses approximately 217.14 MB - cache 0
The script uses approximately 219.36 MB - cache 0
The script uses approximately 217.16 MB - cache 0
The script uses approximately 219.37 MB - cache 0
The script uses approximately 217.29 MB - cache 0
The script uses approximately 219.53 MB - cache 0
The script uses approximately 217.39 MB - cache 0
The script uses approximately 217.11 MB - cache 0
The script uses approximately 217.12 MB - cache 0
The script uses approximately 217.19 MB - cache 0
The script uses approximately 219.41 MB - cache 0
The script uses approximately 217.36 MB - cache 0

Link to reproduction

Not needed.

To reproduce

...
 trpc.procedure.
...
 .subscription(
        async function* (this, _) {
          while (true) { //for example purposes.
            const bigString = Array(100000).fill('a').join('');
            yield bigString;
            await new Promise((resolve) => setTimeout(resolve, 100));
          }
            ....
          };
        }.bind(this),
      ),

Additional information

I grabbed one of those "aaa..." strings in the memory inspector, and here’s what I found. Something related with the new getRawInput introduced in version 11 holding data?
image

👨‍👧‍👦 Contributing

  • 🙋‍♂️ Yes, I'd be down to file a PR fixing this bug!

Activity

  1. added
    🙋‍♂️ help wanted
    ⏮ needs reproduction
    on Oct 27, 2024
  2. AlexSua commented on Oct 27, 2024

    @AlexSua
    Author

    Hello again,
    I went into the code and I think I found the issue in here:

    packages/server/src/adapters/ws.ts : 286

      utils.run(async ()=>{
          while(true){
              // THIS SEEMS TO LEAK
              // const next = await Promise.race([
              //     iterator.next().catch(TRPCError.getTRPCErrorFromUnknown),
              //     abortPromise
              // ]);
              // THIS SEEMS TO WORK FINE
              const next = await  iterator.next().catch(TRPCError.getTRPCErrorFromUnknown)
    

    The issue seems related to this: nodejs/node#17469

    To reproduce the leak, you can create a subscription using the code above and monitor the memory usage of the Node instance with this snippet:

      setInterval(() => {
        const used = process.memoryUsage().heapUsed / 1024 / 1024;
        console.log(
          `The script uses approximately ${Math.round(used * 100) / 100} MB`,
        );
      }, 1000);
    

    I am continuing my investigation. If I have time, I'll create a GitHub project for reproduction.

  3. KATT commented on Oct 27, 2024

    @KATT
    Member

    If you can prove it in our test suite itself, it'd be awesome (not sure if possible with vitest), but the tests are easy to run (faster than doing a new repo)

    git clone [email protected]:trpc/trpc.git
    cd trpc
    
    pnpm i
    pnpm test-watch websocket
  4. KATT commented on Oct 27, 2024

    @KATT
    Member

    ... we use Promise.race() in a few places in the same way - sounds wild that it'd cause a memory leak :|

    Edit: leaving this here: https://levelup.gitconnected.com/unfixable-memory-leaks-in-promise-race-28e5c5a6032c

  5. KATT commented on Oct 28, 2024

    @KATT
    Member

    I'd like to fix this without adding a new dep (we have no hard deps and I'd like us keeping it that way, but we could vendor)

  6. self-assigned this
    on Oct 28, 2024
  7. added
    🐛 bug
    and removed
    🙋‍♂️ help wanted
    ⏮ needs reproduction
    on Oct 29, 2024
  8. oleasteo commented on Oct 29, 2024

    @oleasteo
    Contributor

    @AlexSua no worries, I am able to reproduce and in the works to define a proper test case. Thank you very much for the input!

    So far, I can confirm for the Promise.race to be the issue.

  9. AlexSua commented on Oct 29, 2024

    @AlexSua
    Author

    @oleasteo, just to add, I tried reproducing the issue using the tests that @KATT mentioned. Not only I encountered the same memory leak problem, I tried to run them with the Promise.race removed and it happens that there’s still a leak somewhere, possibly on the client side? I’m unsure how to set up tests that assess the server and client individually. This is what I did and it was leaking (Maybe I did something wrong that is why I didn't post before about this):

    
            iterableInfiniteMemoryLeak: t.procedure
              .output(zAsyncGenerator({ yield: z.string() }))
              .subscription(async function* (_) {
                setInterval(() => {
                  const used = process.memoryUsage().heapUsed / 1024 / 1024;
                  // eslint-disable-next-line no-console
                  console.log(
                    `The script uses approximately ${
                      Math.round(used * 100) / 100
                    } MB`,
                  );
                  (global as any).gc();
                }, 1000);
                while (true) {
                  // eslint-disable-next-line no-console
                  console.log('yielding');
                  const bigString = Array(1000000).fill('a').join('');
                  yield bigString;
                  await new Promise((resolve) => setTimeout(resolve, 1000));
                }
              }),
          },
        });
    
    test('iterable event memory leak', async () => {
      const { client } = ctx;
    
      const onStarted = vi.fn<() => void>();
      const onData = vi.fn<() => void>();
      const subscription = client.sub.iterableInfiniteMemoryLeak.subscribe(
        undefined,
        {
          onData(it) {
            // eslint-disable-next-line no-console
            console.log('onData');
            // onData();
          },
        },
      );
    
      await waitFor(
        () => {
          expect(onData).toHaveBeenCalledTimes(10000);
        },
        {
          timeout: 300_000,
        },
      );
    }, 100_000);
    
    

    By the way, thanks for your excellent work with tRPC.

  10. oleasteo commented on Oct 29, 2024

    @oleasteo
    Contributor

    @AlexSua You probably just don't have that global.gc() exposed in your attempt. You need to add it in the vitest.config.ts via

      [...]
      test: {
        [...]
        poolOptions: {
          [...]
          forks: {
            execArgv: ['--expose-gc'],
          },
        },
      },
    

    Then, your test case will likely work just fine.

  11. github-actions commented on Oct 30, 2024

    @github-actions
    Contributor

    This issue has been locked because we are very unlikely to see comments on closed issues. If you are running into a similar issue, please create a new issue. Thank you.

  12. locked as resolved and limited conversation to collaborators on Oct 30, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

@trpc/server🐛 bug

Type

No type

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions