Skip to content

feat: Controlling retry behavior of useSubscription #7064

Open

Description

@nfadili

Describe the feature you'd like to request

Allow controlling retry behavior for httpSubscriptionLink on a per-request basis via the useSubscription hook options. Currently, httpSubscriptionLink automatically retries on certain error codes (INTERNAL_SERVER_ERROR, BAD_GATEWAY, SERVICE_UNAVAILABLE, GATEWAY_TIMEOUT) without any way to opt out. This retry logic seems to be hardcoded in the link and happens before onError is called, making it impossible to prevent from the call site. For subscriptions that trigger side effects (e.g., sending a message to an AI conversation), automatic retries can cause duplicate operations on the backend.

Describe the solution you'd like to see

Maybe add a retry option directly to useSubscription:

api.conversation.streamMessages.useSubscription(
  { conversationId },
  {
    onData: (data) => { /* ... */ },
    onError: (error) => { /* ... */ },
    retry: false // or a function: (error) => boolean
  }
);

Describe alternate solutions

I tried a few things without finding success.

  1. Using the retryLink and checking for an error code. I updated my backend (what the subscription ends up calling) to simply respond with a 500 for testing and the retryLink wasn't even hit. So I don't think I can control it? The event source data contains:
event: connected
data: {}

event: serialized-error
data: { /* a big ol json blob */ }

Here is what my retryLink:

splitLink({
    condition: (op) => op.type === 'subscription',
    true: [
        retryLink({
            retry: (opts) => {
                console.log('retrying'); // This is not logged
                opts.op.type;
                const code = opts.error.data?.code;
                if (!code) {
                    console.error('No error code found, retrying');
                    return true;
                }
                if (code === 'INTERNAL_SERVER_ERROR') {
                    return false;
                }
                return false;
            }
        }),
        httpSubscriptionLink({
            url: `${getBaseUrl()}/api/trpc`,
            transformer: superjson
        })
    ],
    false: httpBatchLink({
        url: `${getBaseUrl()}/api/trpc`,
        transformer: superjson
    })
})
  1. I also attempted to use a useEffect in the component where my useSubscription is established. I'm able to prevent retries here, but I don't seem to be able to discern the error code to check for only INTERNAL_SERVER_ERROR. This might be user error on my part, but inspected everything about the error and didn't see access to a code.
    useEffect(() => {
        if (subscription.status === 'connecting' && subscription.error) {
            subscription.reset();
            resetStreamingState(subscription.error.message || 'An error occurred while processing your message.');
        }
    }, [subscription, resetStreamingState]);

Additional information

My use case here is:

  • React page uses a subscription to send a message to a chat bot backend type thing. Works great
  • If an error occurs during the request (you close your laptop or the server responds with a 500), the subscription retries automatically and the message is sent to the chat again
  • I want to prevent retrying in certain cases

As far as I can tell, the event source event: serialized-error prevents me from using the existing tooling tRPC provides for controlling this.

Thanks so much for your time and attention! Huge fan of the library and appreciate all you do :)

👨‍👧‍👦 Contributing

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

Activity

  1. coderabbitai commented on Dec 20, 2025

    @coderabbitai
    Contributor

    📝 CodeRabbit Plan Mode

    Generate an implementation plan and prompts that you can use with your favorite coding agent.

    • Create Plan
    Examples

    🔗 Similar Issues

    Related Issues

    🔗 Related PRs

    #6694 - feat(client): add retryDelayMs-option to retryLink [merged]
    #6770 - useSubscription should abort when input changes [merged]
    #6797 - fix: useSubscription calls onConnectionStateChange [merged]
    #7037 - fix(server): pass maxDurationMs timeout signal to subscription handlers [merged]

    👤 Suggested Assignees

    🧪 Issue enrichment is currently in open beta.

    You can configure auto-planning by selecting labels in the issue_enrichment configuration.

    To disable automatic issue enrichment, add the following to your .coderabbit.yaml:

    issue_enrichment:
      auto_enrich:
        enabled: false

    💬 Have feedback or questions? Drop into our discord or schedule a call!

  2. nfadili commented on Dec 21, 2025

    @nfadili
    Author

    Here is what I ended up going with. I can't figure out how to discern error types, so I cancel the subscription on any error. Whether thats user error or not I'm still trying to determine, but either way it'd be awesome if this control was baked into the lib itself :)

    const subscription = api.chat.sendMessageToChat.useSubscription(
        questionToSend ? { chatId, message } : skipToken,
        {
            onData: (event: MessageEvent) => {
                // handle event
            },
            onError: (error) => {
                resetStreamingState(error.message ?? 'An error occurred while processing your message.');
            }
        }
    );
    
    // Abort subscription when tRPC enters 'connecting' state with an error (5xx errors, network issues)
    // This prevents automatic reconnection which would re-send the same question to the backend
    useEffect(() => {
        if (subscription.status === 'connecting' && subscription.error) {
            subscription.reset();
            resetStreamingState(subscription.error.message ?? 'Connection lost. Please try again.');
        }
    }, [subscription, resetStreamingState]);
  3. ArjunCodess commented on Sep 19, 2026

    @ArjunCodess

    hi, i'd like to work on this.

    httpsubscriptionlink retries before retrylink, so usesubscription retry:false is a no-op. i'd honor retry on the hook, and actually skip the link reconnect when retry is false. same option on the ws link would keep both transports in sync.

    should retrydelay still apply when retry is a number, or only the boolean off switch for v1? and is ws in scope too?

  4. KATT commented on Nov 2, 2026

    @KATT
    Member

    🤖 In v12, a subscription called with { reconnect: false } ends with a NETWORK_ERROR instead of reconnecting, on both the HTTP and WebSocket links. https://v12.trpc.io/v12/docs/client/links/http#subscriptions. v12 isn't released yet and there's no ETA.

  5. added
    next-major/definite
    on Nov 2, 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

    next-major/definite

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions