再接続とサブスクリプションのクリーンアップ
接続切断、自動再接続、適切なクリーンアップを処理し、tRPCのサブスクリプションを本番環境に対応させます。
「再接続とサブスクリプションのクリーンアップ」はCoddyKit上の無料tRPC End-to-End Type Safe APIsレッスンです。 これはレッスン4/4です。 下記で完全なレッスンを無料で読むことができます。その後、ブラウザ内の組み込みコードエディタと24時間対応のAIチューターでハンズオン演習できます。 これはtRPC End-to-End Type Safe APIs学習パスの一部であり、ウェブとCoddyKitアプリ全体で進捗が同期されます。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。
このレッスンの一部はまだ翻訳されておらず、英語で表示されています。
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.
AI チューターと学ぶ tRPC End-to-End Type Safe APIs — 無料
ブラウザでリアルコードを書いて実行し、24/7 の AI チューターから瞬時にサポートを受け、ウェブまたはアプリで続きから学習できます。
- コース
- 10
- レッスン
- 40
よくある質問
「再接続とサブスクリプションのクリーンアップ」レッスンは無料ですか?
はい。「再接続とサブスクリプションのクリーンアップ」の完全なテキストはこのウェブで無料で読めます。インタラクティブに演習し(組み込みコードエディタと24時間対応のAIチューター)、tRPC End-to-End Type Safe APIsコースの残りをアンロックするには、CoddyKit PROにアップグレードしてください。 tRPC End-to-End Type Safe APIsコースには全4レッスンが含まれています。
「再接続とサブスクリプションのクリーンアップ」で何を学びますか?
接続切断、自動再接続、適切なクリーンアップを処理し、tRPCのサブスクリプションを本番環境に対応させます。 ブラウザで直接実行するハンズオンコードでtRPC End-to-End Type Safe APIsを演習し、24時間対応のAIチューターがレッスンを進める中での質問に答えます。
tRPC End-to-End Type Safe APIsを始めるのに経験は必要ですか?
事前経験は必要ありません。CoddyKitのtRPC End-to-End Type Safe APIsは初級者から上級者向けに構成されているため、ここから始めるか最初から始めて、自分のペースで進むことができます。 これはレッスン4/4です。
「再接続とサブスクリプションのクリーンアップ」レッスンにはどのくらい時間がかかりますか?
ほとんどのCoddyKitレッスンは約5~10分かかります。各レッスンはコンパクトでインタラクティブなので、着実に進歩し、ウェブとアプリ全体で正確に前回の場所から再開できます。
このtRPC End-to-End Type Safe APIsレッスンでコードを書いて実行できますか?
はい。すべてのtRPC End-to-End Type Safe APIsレッスンに組み込みコードエディタが含まれているため、ブラウザでリアルコードを書いて実行し、即座のAIフィードバックを取得できます。ローカル設定は不要です。
このコースのすべてのレッスン
- tRPCによるリアルタイム通信入門
- サブスクリプション用WebSocketの設定
- ライブデータサブスクリプションの実装
- 再接続とサブスクリプションのクリーンアップ