Skip to content

fix: SSE subscriptions don't reconnect after maxDurationMs (#7094) - #7207

Merged
Nick-Lucas merged 4 commits into
trpc:mainfrom
bxff:fix/sse-maxduration-reconnect
Mar 5, 2026
Merged

Nick-Lucas merged 4 commits into
trpc:mainfrom
bxff:fix/sse-maxduration-reconnect

Conversation

@bxff

@bxff bxff commented Mar 3, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #7094

When maxDurationMs is set, SSE subscriptions should end after the timeout and the client should reconnect automatically. Instead, the connection hangs silently and the client never reconnects.

Root cause

The server never actually ends the HTTP response. When maxDurationMs fires, it aborts combinedAbort.signal in resolveResponse.ts β€” but writeResponse.ts passes request.signal (client disconnect) to pipeTo(), not the combined signal. So the abort has no effect on the response pipe.

Meanwhile the subscription generator is typically blocked on an await (waiting for the next event), so readableStreamFrom.pull() hangs on iterator.next() indefinitely. The response stays open, the client never sees an error, EventSource never retries.

I confirmed this by writing a standalone script with EventSourcePolyfill + a plain HTTP server that calls res.end() after 500ms β€” the polyfill reconnected fine, 4 times in 5 seconds. The polyfill was never the problem.

Fix

I wrap the SSE ReadableStream in resolveResponse.ts with a reader that listens to combinedAbort.signal. When maxDurationMs fires, it cancels the reader directly, which unblocks the pipe and lets the response end. After that, EventSource's built-in retry does its thing β€” new connection, lastEventId resumption via tracked(), everything works.

I also considered modifying writeResponse.ts to take an extra abort signal and use AbortSignal.any(), which would be a bit cleaner architecturally. Happy to refactor if you'd prefer that approach.

Regression test sets maxDurationMs: 500, sends tracked data, waits for the reconnect, then verifies the client got [1, 2] across two connections. Completes in ~1.5s. All existing tests still pass.

Summary by CodeRabbit

  • Bug Fixes

    • Server-Sent Events streams now reliably terminate on subscription timeouts or external cancellations, preventing orphaned streams.
    • SSE reconnections resume delivering data from the last received event, avoiding duplicate or lost messages after reconnects.
    • Streaming responses now respect per-request cancellations and time limits, ensuring timely cleanup on aborts and reconnections.
  • Tests

    • Added regression tests verifying SSE timeout reconnection and data resumption behavior.

@bxff
bxff requested a review from a team as a code owner March 3, 2026 17:50
@vercel

vercel Bot commented Mar 3, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
next-prisma-starter Ready Ready Preview Mar 5, 2026 10:24pm
og-image Ready Ready Preview, Comment Mar 5, 2026 10:24pm

Request Review

@coderabbitai

coderabbitai Bot commented Mar 3, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▢️ Resume reviews
  • πŸ” Trigger review

Walkthrough

Adds a per-call abort signal to streaming RPC results and wires it into SSE/ReadableStream handling so subscription streams are wrapped with an abortable mirror and cancelled when the per-call (client disconnect + maxDurationMs) aborts, enabling reconnection/resume.

Changes

Cohort / File(s) Summary
Runtime streaming update
packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts
Add signal?: AbortSignal to per-call RPCResultOk data; compose a per-call combined abort (client disconnect + maxDurationMs); wrap subscription ReadableStreams with an abortable mirror and attach abort listeners to cancel the reader on per-call aborts.
Subscription regression tests
packages/tests/server/httpSubscriptionLink.test.ts
Add two regression tests validating SSE reconnection after maxDurationMs and resumed tracked events using lastEventId/tracked ids; assert reconnection, resumed data, and no errors/completion.

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Resolve as resolveResponse
    participant Stream as SSE_ReadableStream
    participant CallAbort as Per-call_AbortController

    Client->>Resolve: initiate subscription request
    Resolve->>CallAbort: create/compose per-call abort (client disconnect + maxDurationMs)
    Resolve->>Stream: wrap underlying ReadableStream with abortable mirror
    Resolve-->>Client: return abortable stream response
    Note right of CallAbort: timeout or client disconnect triggers abort
    CallAbort-->>Stream: abort -> cancel reader (stream closed)
    Stream-->>Resolve: reader canceled/ended
    Resolve-->>Client: connection ends (client may reconnect/resume)
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related issues

  • #7094: bug: No reconnect after maxDurationMs β€” this PR propagates per-call/maxDurationMs aborts and enables reconnection/resume behavior described in the issue.
  • trpc/trpc#6991: stream abort behavior β€” changes that propagate an AbortSignal into stream handling address the abort-not-terminating-stream scenarios noted there.

Possibly related PRs

  • trpc/trpc#7037: modifies resolveResponse to propagate combined/maxDurationMs abort into subscription handling β€” closely related code-level change.

Suggested reviewers

  • KATT
  • hmatthieu

Poem

🐰
I nibble bytes where streams align,
Stitch aborts and make reconnect fine.
Old request ends, a fresh one starts,
Tracked events resume β€” joyful hearts. πŸ₯•

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Title check βœ… Passed The title accurately and specifically describes the main fix: enabling SSE subscription reconnection after maxDurationMs timeout.
Description check βœ… Passed The description provides a clear root cause analysis, the fix implementation, and mentions regression tests, but lacks explicit reference to the template structure and checklist completion.
Linked Issues check βœ… Passed The PR successfully addresses the core requirement from #7094: enabling automatic SSE reconnection after maxDurationMs with tracked event resumption.
Out of Scope Changes check βœ… Passed All changes are scoped to fixing the maxDurationMs reconnection issue; the signal field addition to RPCResultOk and streaming abort integration are directly necessary for the fix.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
πŸ§ͺ Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/tests/server/httpSubscriptionLink.test.ts`:
- Around line 1528-1601: The test currently wraps setup in run(() => { ... })
and returns a resource; replace that with direct resource usage by creating the
router, onConnection, deferred and results as local variables first, then call
await using ctx = testServerAndClientResource(router, { server: {}, client(opts)
{ return { links: [linkSpy, httpSubscriptionLink({ url: opts.httpUrl,
transformer: superjson })] } } }); keep deferred, results and onConnection as
local closures/helpers (e.g. deferred = createDeferred(), results: number[] =
[], onConnection = vi.fn()) and expose them from the test context if needed
(e.g. add deferred: () => deferred, results, onConnection to the returned ctx),
removing the run(...) wrapper and its returned object.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between f489af0 and 40c8c8f.

πŸ“’ Files selected for processing (2)
  • packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts
  • packages/tests/server/httpSubscriptionLink.test.ts

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts (1)

549-559: Redundant type assertion after truthy check.

After the if (subscriptionAbortSignal) check, TypeScript narrows the type from AbortSignal | null to AbortSignal. The explicit cast is unnecessary.

πŸ”§ Suggested simplification
          if (subscriptionAbortSignal) {
-           const signal = subscriptionAbortSignal as AbortSignal;
-           const onAbort = () => void reader.cancel();
-           if (signal.aborted) {
+           const onAbort = () => void reader.cancel();
+           if (subscriptionAbortSignal.aborted) {
              onAbort();
            } else {
-             signal.addEventListener('abort', onAbort, {
+             subscriptionAbortSignal.addEventListener('abort', onAbort, {
                once: true,
              });
            }
          }
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`
around lines 549 - 559, The variable subscriptionAbortSignal is already narrowed
by the if (subscriptionAbortSignal) check, so remove the redundant type
assertion (as AbortSignal); change const signal = subscriptionAbortSignal as
AbortSignal; to const signal = subscriptionAbortSignal; and keep the rest of the
logic (onAbort -> reader.cancel(), signal.aborted check and addEventListener)
unchanged in the same block (refer to symbols subscriptionAbortSignal, signal,
onAbort, reader.cancel).
πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`:
- Around line 549-559: The variable subscriptionAbortSignal is already narrowed
by the if (subscriptionAbortSignal) check, so remove the redundant type
assertion (as AbortSignal); change const signal = subscriptionAbortSignal as
AbortSignal; to const signal = subscriptionAbortSignal; and keep the rest of the
logic (onAbort -> reader.cancel(), signal.aborted check and addEventListener)
unchanged in the same block (refer to symbols subscriptionAbortSignal, signal,
onAbort, reader.cancel).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 40c8c8f and 221f72a.

πŸ“’ Files selected for processing (2)
  • packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts
  • packages/tests/server/httpSubscriptionLink.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/tests/server/httpSubscriptionLink.test.ts

@pkg-pr-new

pkg-pr-new Bot commented Mar 3, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@trpc/client

npm i https://pkg.pr.new/@trpc/client@7207

@trpc/next

npm i https://pkg.pr.new/@trpc/next@7207

@trpc/react-query

npm i https://pkg.pr.new/@trpc/react-query@7207

@trpc/server

npm i https://pkg.pr.new/@trpc/server@7207

@trpc/tanstack-react-query

npm i https://pkg.pr.new/@trpc/tanstack-react-query@7207

@trpc/upgrade

npm i https://pkg.pr.new/@trpc/upgrade@7207

commit: d0cb53b

// but writeResponse uses request.signal for pipeTo() β€” which
// only fires on client disconnect. We need maxDurationMs abort
// to also terminate the SSE response body (fixes #7094).
const reader = stream.getReader();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey thanks for the contribution, still getting my head around it as I'm not really our expert in this bit of the codebase, but a couple questions:

  • Is there some reason we can't just call stream.cancel() instead of setting up another stream? Perhaps even pass the combinedSignal to sseStreamProducer and contain the abort checks inside there? This file is getting quite convoluted so the more we can push out the better
  • storing subscriptionAbortSignal outside the calls map seems a bit fragile, and while subscription connections aren't typically batches so calls shouldn't be >1 I do wonder if there's a more elegant and future-safe way to write this?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for taking a look!

Tried both ideas. stream.cancel() doesn't work because pipeTo() in writeResponse locks the reader β€” once that happens you can't cancel from outside.

I also went down the path of passing the signal into sseStreamProducer β†’ readableStreamFrom to call iterator.return() on abort. That seemed like it should work, but it turns out async generators serialize .next() and .return() β€” so when pull() is already stuck at await iterator.next() (generator waiting on user code), .return() just queues behind it and never fires. That's exactly the deadlock we're trying to break. So the wrapper stream approach is unfortunately necessary β€” reader.cancel() bypasses the generator entirely.

Good call on the hoisted variable though, that was definitely fragile. I replaced it by threading the signal through RPCResultOk instead (added signal?: AbortSignal), so the subscription handler just reads result?.signal. No mutable outer variable, no cast.

While I was at it I also tightened things up:

  • Only subscriptions get the signal on RPCResultOk, queries/mutations get undefined
  • The wrapper stream is only created when there's actually a signal to listen on (i.e. when maxDurationMs is configured), otherwise it just passes the stream through directly
  • Renamed a variable inside pull() that was shadowing the outer result
  • Added removeEventListener cleanup in the wrapper's cancel() to avoid leaking the listener

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great, thank you! It looks good. Just pushing a couple small convention adjustments, and addressing 1 ai review comment that looks valid

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts (1)

544-551: Remove the abort listener when the stream completes normally.

The addEventListener(..., { once: true }) pattern only removes the listener if an abort event fires. If the stream ends normally (when result.done is true or the stream is cancelled), the abort listener remains attached. Move onAbort outside the signal conditional and explicitly call removeEventListener in the stream's pull() callback (when done) and cancel() callback to ensure proper cleanup.

♻️ Proposed cleanup
           const signal = result?.signal;
           const reader = stream.getReader();
+          const onAbort = signal ? () => void reader.cancel() : null;
           const abortableStream = new ReadableStream({
             async pull(controller) {
               const result = await reader.read();
               if (result.done) {
+                if (signal && onAbort) {
+                  signal.removeEventListener('abort', onAbort);
+                }
                 controller.close();
               } else {
                 controller.enqueue(result.value);
               }
             },
             cancel() {
+              if (signal && onAbort) {
+                signal.removeEventListener('abort', onAbort);
+              }
               void reader.cancel();
             },
           });

-          if (signal) {
-            const onAbort = () => void reader.cancel();
+          if (signal && onAbort) {
             if (signal.aborted) {
               onAbort();
             } else {
               signal.addEventListener('abort', onAbort, { once: true });
             }
           }
πŸ€– Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`
around lines 544 - 551, The abort listener isn't removed when the stream
completes normally; move the onAbort handler declaration out of the if (signal)
block so it can be referenced for removal, register it only if signal exists,
and then explicitly call signal.removeEventListener('abort', onAbort) from the
stream's pull() path when result.done is true and from the stream cancel()
callback (the same places that finish or cancel the reader) to ensure the
listener is cleaned up; reference the onAbort function, the signal object,
reader.cancel(), the stream's pull() callback and cancel() callback in your
changes.
πŸ€– Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts`:
- Around line 544-551: The abort listener isn't removed when the stream
completes normally; move the onAbort handler declaration out of the if (signal)
block so it can be referenced for removal, register it only if signal exists,
and then explicitly call signal.removeEventListener('abort', onAbort) from the
stream's pull() path when result.done is true and from the stream cancel()
callback (the same places that finish or cancel the reader) to ensure the
listener is cleaned up; reference the onAbort function, the signal object,
reader.cancel(), the stream's pull() callback and cancel() callback in your
changes.

ℹ️ Review info
βš™οΈ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 7407fd02-588c-41be-843d-7b7dffcb7825

πŸ“₯ Commits

Reviewing files that changed from the base of the PR and between 221f72a and 2adcc0e.

πŸ“’ Files selected for processing (2)
  • packages/server/src/unstable-core-do-not-import/http/resolveResponse.ts
  • packages/tests/server/httpSubscriptionLink.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/tests/server/httpSubscriptionLink.test.ts

@Nick-Lucas Nick-Lucas left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for this, it's a solid fix and you've helped me understand some bits I didn't build too!

@github-actions

github-actions Bot commented Mar 7, 2026

Copy link
Copy Markdown
Contributor

This pull request has been locked because we are very unlikely to see comments on closed issues. If you think, this PR is still necessary, create a new one with the same branch. Thank you.

This branch was successfully deployed

5 active deployments
Preview – www β€” cd82c581 Deployed Mar 5, 2026 by vercel[bot]
Preview – trpc-next-app-dir β€” cd82c581 Deployed Mar 5, 2026 by vercel[bot]
Preview – next-prisma-starter β€” cd82c581 Deployed Mar 5, 2026 by vercel[bot]
Preview – examples-todomvc β€” cd82c581 Deployed Mar 5, 2026 by vercel[bot]
Preview – og-image β€” cd82c581 Deployed Mar 5, 2026 by vercel[bot]
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug: No reconnect after maxDurationMs

2 participants