0Pricing
tRPC End-to-End Type Safe APIs · Lesson

Handling Reconnection and Subscription Cleanup

Make tRPC subscriptions production-ready by handling dropped connections, automatic reconnection, and proper cleanup.

Handling Reconnection and Subscription Cleanup is a free tRPC End-to-End Type Safe APIs lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the tRPC End-to-End Type Safe APIs learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Real-time Is Unreliable

You can set up subscriptions, but networks drop, servers restart, and tabs sleep. Production real-time code must handle disconnects and cleanup gracefully.

The wsLink and Reconnection

tRPC clients use a WebSocket client that can automatically reconnect when a connection is lost.

import { createWSClient, wsLink } from "@trpc/client";

const wsClient = createWSClient({
  url: "ws://localhost:3000",
  retryDelayMs: (attempt) => Math.min(1000 * attempt, 5000),
});

Backoff Strategy

Reconnect attempts should use exponential backoff so a downed server is not hammered by every client at once.

Subscription Lifecycle

A subscription exposes lifecycle callbacks: data, error, started, and stopped.

trpc.onMessage.subscribe(undefined, {
  onData: (msg) => add(msg),
  onError: (err) => console.error(err),
  onStarted: () => console.log("live"),
});

Cleaning Up on Unmount

Every subscription returns an unsubscribe handle. Call it when the component unmounts to free resources.

const sub = trpc.onMessage.subscribe(undefined, { onData });
// later
sub.unsubscribe();

React Cleanup Pattern

In React, return the cleanup from useEffect so it runs on unmount.

useEffect(() => {
  const sub = trpc.onMessage.subscribe(undefined, { onData });
  return () => sub.unsubscribe();
}, []);

Server-Side Cleanup

On the server, the subscription generator must release resources when the client disconnects.

onMessage: publicProcedure.subscription(async function* (opts) {
  const queue = subscribe();
  try {
    for await (const msg of queue) yield msg;
  } finally {
    queue.close(); // cleanup on disconnect
  }
})

Detecting Missed Events

After a reconnect, the client may have missed events. Track a last-seen id and refetch the gap on reconnect.

onStarted: () => {
  fetchMissedSince(lastSeenId);
}

Heartbeats and Timeouts

Heartbeat pings detect a silently dead connection so the client can trigger a reconnect instead of waiting forever.

Avoiding Memory Leaks

Forgetting to unsubscribe leaks listeners and slowly degrades both client and server. Always pair every subscribe with an unsubscribe.

Showing Connection Status

Surface the connection state in the UI so users know when data is live versus reconnecting, improving trust in real-time views.

wsClient.connectionState; // "connecting" | "open" | "closed"

Quick Check

Test your subscription reliability knowledge.

Recap

You made subscriptions production-ready:

  • Use the WS client with exponential backoff reconnection
  • Always unsubscribe on unmount to avoid leaks
  • Clean up server-side generators and refetch missed events

Robust reconnection and cleanup keep real-time apps reliable in the real world.

Frequently asked questions

Is the “Handling Reconnection and Subscription Cleanup” lesson free?

Yes — the full text of “Handling Reconnection and Subscription Cleanup” is free to read here on the web, and the tRPC End-to-End Type Safe APIs course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the tRPC End-to-End Type Safe APIs course, upgrade to CoddyKit PRO.

What will I learn in “Handling Reconnection and Subscription Cleanup”?

Make tRPC subscriptions production-ready by handling dropped connections, automatic reconnection, and proper cleanup. You practise tRPC End-to-End Type Safe APIs with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start tRPC End-to-End Type Safe APIs?

No prior experience is required. tRPC End-to-End Type Safe APIs on CoddyKit is structured for beginners through advanced learners; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Handling Reconnection and Subscription Cleanup” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this tRPC End-to-End Type Safe APIs lesson?

Yes. Every tRPC End-to-End Type Safe APIs lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Real-time with tRPC
  2. Setting Up WebSockets for Subscriptions
  3. Implementing Live Data Subscriptions
  4. Handling Reconnection and Subscription Cleanup
← Back to tRPC End-to-End Type Safe APIs