Skip to content

feat(client): don't spam retry when createContext fails #4774

Closed

Description

@joanrieu

Provide environment information

  Binaries:
    Node: 18.15.0 - ~/.nvm/versions/node/v18.15.0/bin/node
    npm: 9.5.0 - ~/.nvm/versions/node/v18.15.0/bin/npm
    pnpm: 8.1.0 - ~/.nvm/versions/node/v18.15.0/bin/pnpm
  npmPackages:
    @trpc/client: ^10.38.1 => 10.38.1 
    @trpc/server: ^10.38.1 => 10.38.1 
    typescript: ^5.2.2 => 5.2.2 

Describe the bug

The tRPC WebSocket client enters a fast infinite retry loop when createContext fails on the server.

Link to reproduction

https://gist.github.com/joanrieu/467431199bfeffadda4b9dea9831d608

To reproduce

Start a tRPC WebSocket server which throws an error during createContext (in my gist: pnpm ts-node server.ts).
Start a tRPC WebSocket client (in my gist: pnpm ts-node client.ts).
Watch as the client spams the server instead of applying exponential backoff.

The reproduction code is almost a verbatim example usage of createWSSHandler/createWS server-side and wsLink client-side. The only thing that matters is that createContext throws on the server and triggers the client-side socket open/close sequence.

Additional information

Here's what's happening behind the scenes:

  1. the server accepts the connection (client gets WS "open" event and resets its connection attempt counter)
  2. the server sends the error as a response-like message (client gets a WS "message" event with a JSON object with id=null and with an error property)
  3. the server closes the connection (client gets WS "close" event)
  4. the client retries instantly (since the connection attempt counter was reset at step 1)
  5. ... infinite loop ...

I see two ways to fix this:

  1. Could the tRPC context be created during the WebSocket handshake? That way a proper HTTP error code could be returned and the connection would be aborted. It's not clear to me why the server is accepting the WebSocket connection in the first place. I don't know the codebase enough at the moment to answer this.
  2. Or one way to fix it is to only reset the connection attempt counter to 0 only when a response to a request is received (ie, delay the reset of the counter for as long as it might take to have a successful exchange). This has negative consequences in other scenarios since the connection could potentially have no messages ever and the delay would be kept if a disconnection occurs, causing an undesirable reconnection delay then. If a "maximum success delay" is defined this could still work. This solution is more a hack in my opinion.

👨‍👧‍👦 Contributing

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

Activity

  1. KATT commented on Sep 11, 2023

    @KATT
    Member

    You should ensure that your createContext never fails. This is intended behavior, but some sort of exponential backoff mechanism would be nice

  2. changed the title [-]bug: WS client spams retry when createContext fails[/-] [+]feat(client): don't spam retry when createContext fails[/+] on Sep 11, 2023
  3. joanrieu commented on Sep 18, 2023

    @joanrieu
    Author

    You should ensure that your createContext never fails. This is intended behavior [...]

    This does not seem to be documented in the pages about context, error handling, and authorization. This also introduces a major difference in the error handling pattern between createContext and middlewares, for which all the examples in the docs happily throw errors. What are the reasons behind this choice and can it be revisited?

    some sort of exponential backoff mechanism would be nice

    If you get a chance to review the proposals mentioned in the report, or have ideas of your own, let me know, I could work on a fix if the desired solution is not too complex.

  4. vktrl commented on Nov 4, 2023

    @vktrl

    Watching this issue, have a similar problem. Right now I just moved authentication up into connection upgrade handler.

    There's a closely coupled issue on the front-end side that lead me to this happening: WS connections are eagerly created.
    I only have subscriptions for authenticated users and don't want site visitors creating and keeping open pointless connections. So far the best I've come up with is swapping public/user links in the TRPC provider or mocking a dummy WS Client.

  5. KATT commented on Nov 4, 2023

    @KATT
    Member

    Open for PRs!

  6. UltimateGG commented on Sep 5, 2024

    @UltimateGG

    You should ensure that your createContext never fails. This is intended behavior, but some sort of exponential backoff mechanism would be nice

    How do you authenticate with websockets correctly? If the context shouldn't throw errors then we could have tons of unauthenticated websocket connections open. For my http routes I can throw an error in createContext and the request will fail, with websockets it just stays open?

    Essentially how to reject a websocket connection?

  7. added
    ✅ accepted-PRs-welcome
    on Sep 5, 2024
  8. AmalkrishnaAS commented on Oct 20, 2026

    @AmalkrishnaAS

    I'd like to take this.

    It still happens on main. When createContext throws, the ws adapter sends an id: null error and closes the socket. On the client, open() succeeded, so the next close calls reconnect(), which starts again at attempt 0 — and exponentialBackoff(0) is 0 ms. Backoff only applies while open() itself keeps throwing, so a server that accepts and then closes gets reconnected to in a tight loop.

    Plan:

    • Keep the attempt index across reconnects instead of restarting at 0 on every close, and reset it only once the connection has proved itself: a message that isn't a connection-level error, or the socket staying open past a short threshold (so a quiet connection that later drops still reconnects quickly).
    • Add a regression test in packages/tests: a ws server whose createContext throws, asserting the client's reconnects back off.

    I'll target main. Happy to use a different reset point if you'd prefer one.

  9. aliamanatali commented on Oct 29, 2026

    @aliamanatali
    Contributor

    Hi @AmalkrishnaAS, are you still working on this? I have a fix with regression tests ready (continue the backoff after an id: null rejection instead of resetting to attempt 0). Happy to step back if you're close, or to open mine and add you as co-author, whichever you prefer.

  10. added a commit that references this issue on Nov 3, 2026
    fe6b241
  11. github-actions commented on Nov 4, 2026

    @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 Nov 4, 2026
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

    @trpc/client✅ accepted-PRs-welcome

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions