Skip to content

bug: SSE Subscription Never Aborts #6193

Closed

Description

@yspreen

Provide environment information

System:
OS: Linux 5.0 undefined
CPU: (6) x64 Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
Memory: 0 Bytes / 0 Bytes
Shell: 1.0 - /bin/jsh
Binaries:
Node: 18.20.3 - /usr/local/bin/node
Yarn: 1.22.19 - /usr/local/bin/yarn
npm: 10.2.3 - /usr/local/bin/npm
pnpm: 8.15.6 - /usr/local/bin/pnpm
npmPackages:
@tanstack/react-query: ^5.59.17 => 5.59.20
@trpc/client: ^11.0.0-rc.608 => 11.0.0-rc.608+f75de97b3
@trpc/next: ^11.0.0-rc.608 => 11.0.0-rc.608+f75de97b3
@trpc/react-query: ^11.0.0-rc.608 => 11.0.0-rc.608+f75de97b3
@trpc/server: ^11.0.0-rc.608 => 11.0.0-rc.608+f75de97b3
next: 15.0.2 => 15.0.2
react: ^19.0.0-rc-7c8e5e7a-20241101 => 19.0.0-rc-fb9a90fa48-20240614
typescript: ^5 => 5.6.3

Describe the bug

Subscription never gets aborted

Link to reproduction

https://stackblitz.com/~/github.com/yspreen/trpc-bug

To reproduce

https://stackblitz.com/~/github.com/yspreen/trpc-bug

Additional information

No response

👨‍👧‍👦 Contributing

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

Activity

  1. yspreen commented on Nov 6, 2024

    @yspreen
    ContributorAuthor

    here's the code:

    
    export const appRouter = router({
      loopBased: procedure.subscription(async function* ({ signal }) {
        try {
          while (!signal?.aborted) {
            console.log("loop", signal, signal?.aborted);
    
            yield "new data";
            await new Promise((r) => setTimeout(r, 1000));
          }
        } catch (error) {
          console.error("done", error);
        }
      }),
    });
    

    As far as I can tell, the signal should get aborted when the connection breaks. Instead, if I close the tab or refresh the page, I see next.js reporting that the SSE request finished, but trpc keeps running this loop. The console log confirms that abort is false.

  2. adri1wald commented on Nov 7, 2024

    @adri1wald

    We're experiencing related issues. Resources are never getting cleaned up because our return method on the AsyncIterable is not being called after connection closes. This is causing a memory leak and our servers to OOM every couple of hours.

  3. KATT commented on Nov 8, 2024

    @KATT
    Member

    Thanks so much for reporting this with a good repro.

    We just merged a PR that should fix this in #6204.

    Please let us know how it goes and open a new issue if it's still a problem or if you experience other issues. Thanks

  4. KATT commented on Nov 8, 2024

    @KATT
    Member

    FYI, not sure why, but I can't seem to verify the fix on StackBlitz, but when running the project locally it works well, seems like the request's events aren't properly propagated in that environment somehow

  5. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    @KATT yeah I was just testing it on stackblitz and the issue was still there. I'm seeing if manually purging all packages and running the install command again with 621 fixes it...

  6. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    it certainly feels like this issue is still 100% reproducible on stackblitz

  7. reopened this on Nov 8, 2024
  8. KATT commented on Nov 8, 2024

    @KATT
    Member

    Keeping it open until you've checked

  9. added
    ⏳ close if no activity
    on Nov 8, 2024
  10. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    @KATT I can confirm that the issue is fixed in my project. I'd still prefer some further investigation since stackblitz still shows the bug, and I think as long as it's reproducible the issue should stay open

  11. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    I just updated the stackblitz repo to use the new version.

  12. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    a good way to cause the error is simply to hit refresh in stackblitz. that doubles the frequency of calls

  13. yspreen commented on Nov 8, 2024

    @yspreen
    ContributorAuthor

    on the other hand, while the bug happened locally, I could still see next.js terminate the request once the page closed. stackblitz doesn't show that log line. so maybe it is an issue of their internal proxy not terminating the requests...

  14. 10 remaining items

  15. yspreen commented on Nov 9, 2024

    @yspreen
    ContributorAuthor

    Is that a change from the latest release? Because the latest release didn't seem to be working for me on fly.io I had to make the change with the three different handlers above.

  16. yspreen commented on Nov 11, 2024

    @yspreen
    ContributorAuthor

    I ended up moving to my own SSE server and client implementation so I won't be able to repro any further changes to this in my own infrastructure. I recommend testing on fly.io or another proxied provider before closing this.

  17. KATT commented on Nov 11, 2024

    @KATT
    Member

    I ended up moving to my own SSE server and client implementation so I won't be able to repro any further changes to this in my own infrastructure. I recommend testing on fly.io or another proxied provider before closing this.

    How come? Was there anything you were missing in ours? Happy to hop on a call to understand this better

    Spent a lot of time on SSE this week and got some more improvements coming, sad to see you go 😅

  18. SiNONiMiTY commented on Nov 12, 2024

    @SiNONiMiTY
    Contributor

    I am also encountering an issue that might be related to this

    (node:14844) MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 close listeners added to [Socket]. MaxListeners is 10. Use emitter.setMaxListeners() to increase limit
        at genericNodeError (node:internal/errors:983:15)
        at wrappedFn (node:internal/errors:537:14)
        at _addListener (node:events:592:17)
        at Socket.addListener (node:events:610:10)
        at Readable.on (node:internal/streams/readable:1128:35)
        at Socket.socketListenerWrap [as on] (node:_http_server:1201:54)
        at Socket.once (node:events:654:8)
        at incomingMessageToRequest (file:///node_modules/.pnpm/@[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/@trpc/server/dist/adapters/node-http/incomingMessageToRequest.mjs:92:17)
        at fastifyRequestHandler (file:///node_modules/.pnpm/@[email protected]_@[email protected][email protected][email protected][email protected]/node_modules/@trpc/server/dist/adapters/fastify/fastifyRequestHandler.mjs:27:17)
        at Object.handler (file:///packages/backend/dist/app/index.js:83:20)
    

    All I have to do is just call a procedure 10 times, and this error will be visible on the console

    Using the Fastify Adapter

    • NodeJS 22.10
    • @trpc/client v11.0.0-rc.630
    • @trpc/server v11.0.0-rc.630
  19. adri1wald commented on Nov 12, 2024

    @adri1wald
    const t = initTRPC.context<TRPCContext>().create({
      transformer: superjson,
      errorFormatter({ shape, error }) {
        // ...
      },
      experimental: {
        sseSubscriptions: {
          ping: {
            enabled: true,
          },
        },
      },
    })

    #6204 fixed the memory leak but when we enabled pings, it returned (possibly via another mechanism).

    We enabled pings because we are seeing extremely high numbers of ELB 502s (orders of magnitude above Target 5XXs) after we upgraded to TRPC11 with SSE, and we thought it's because the connection is idle for too long. Curiously, it also didn't fix the ELB 502s rate.

  20. tarekwiz commented on Nov 13, 2024

    @tarekwiz

    I can confirm this happens with the fetch adapter as well for Astro.
    The abortController never gets aborted when the browser tab exits (request drops)

  21. KATT commented on Nov 13, 2024

    @KATT
    Member

    Thanks for all the details everyone, we've now updated the code to:

    res.once('close', onAbort);
    req.socket.once('end', onAbort);

    This really should be sufficient to do detection of canceled requests.

    I don't think #6228 changes anything - what it aims to fix should have been a symptom of us not triggering the abort signal correctly, but the stream itself should be canceled as long as you listen to the abort signals as defined in the docs.


    Other new changes (changelog):

    • We've also added support on the client to do automatic reconnection on the client as EventSource itself isn't really great at detecting stale connections
      • (kill -9 of a server is enough to enough for Chrome's EventSource to hang in my testing)
      • We might add some defaults for ping/pong and timeouts
      • Feedback is very welcome in the 🎏-rfc-streaming channel on Discord.
    • experimental.sseSubscriptions: {} has moved to sse: {} (release note)

    Apologies to anyone who have encountered this issue. It should be addressed in latest release (11.0.0-rc.633), but I will keep this issue open until someone has confirmed this did it for them.

  22. added
    🐛 bug
    and removed
    ⏳ close if no activity
    on Nov 14, 2024
  23. SiNONiMiTY commented on Nov 14, 2024

    @SiNONiMiTY
    Contributor

    Thanks for all the details everyone, we've now updated the code to:

    res.once('close', onAbort);
    req.socket.once('end', onAbort);

    This really should be sufficient to do detection of canceled requests.

    I don't think #6228 changes anything - what it aims to fix should have been a symptom of us not triggering the abort signal correctly, but the stream itself should be canceled as long as you listen to the abort signals as defined in the docs.

    Other new changes (changelog):

    * We've also added support on the client to do [automatic reconnection](https://trpc.io/docs/client/links/httpSubscriptionLink#timeout) on the client as `EventSource` itself isn't really great at detecting stale connections
      
      * (`kill -9` of a server is enough to enough for Chrome's `EventSource` to hang in my testing)
      * We might add some defaults for ping/pong and timeouts
      * Feedback is very welcome in the [🎏-rfc-streaming](https://trpc.io/discord) channel on Discord.
    
    * `experimental.sseSubscriptions: {}` has moved to `sse: {}` ([release note](https://trpc.io/docs/migrate-from-v10-to-v11#moves-experimentalssesubscriptions---sse-non-breaking))
    

    Apologies to anyone who have encountered this issue. It should be addressed in latest release (11.0.0-rc.633), but I will keep this issue open until someone has confirmed this did it for them.

    I have updated to the latest next release and tried to replicate the previous scenarios that were failing. The MaxListenersExceededWarning is no longer being triggered on my side.

  24. KATT commented on Nov 14, 2024

    @KATT
    Member

    I will close this now then as there's been a confirmed fix.

    Don't hesitate to reopen issues if you experience any issues (even if you can't make a good repro, I know that is hard if it's deployment dependent)

  25. github-actions commented on Nov 15, 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.

  26. locked as resolved and limited conversation to collaborators on Nov 15, 2024
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

    🐛 bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions