tRPC End-to-End Type Safe APIs · Aula

Tratamento de reconexão e limpeza de assinaturas

Prepare as assinaturas tRPC para produção tratando conexões interrompidas, reconexão automática e limpeza adequada.

Aula 4 de 413 etapas

Tratamento de reconexão e limpeza de assinaturas é uma aula grátis de tRPC End-to-End Type Safe APIs no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de tRPC End-to-End Type Safe APIs, e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de tRPC End-to-End Type Safe APIs inclui 4 aulas no total.

Partes desta aula ainda não foram traduzidas e aparecem em inglês.

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.

Grátis para começar

Aprenda tRPC End-to-End Type Safe APIs com um tutor de IA — grátis

Escreva e execute código real no seu navegador, obtenha ajuda instantânea de um tutor de IA 24/7 e continue de onde parou na web ou no app.

Cursos
10
Aulas
40

Perguntas Frequentes

A aula “Tratamento de reconexão e limpeza de assinaturas” é grátis?

Sim — o texto completo de “Tratamento de reconexão e limpeza de assinaturas” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de tRPC End-to-End Type Safe APIs, atualize para CoddyKit PRO. O curso de tRPC End-to-End Type Safe APIs inclui 4 aulas no total.

O que vou aprender em “Tratamento de reconexão e limpeza de assinaturas”?

Prepare as assinaturas tRPC para produção tratando conexões interrompidas, reconexão automática e limpeza adequada. Você pratica tRPC End-to-End Type Safe APIs com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.

Preciso ter experiência prévia para começar tRPC End-to-End Type Safe APIs?

Nenhuma experiência prévia é necessária. tRPC End-to-End Type Safe APIs no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.

Quanto tempo leva a aula “Tratamento de reconexão e limpeza de assinaturas”?

A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.

Posso escrever e executar código nesta aula de tRPC End-to-End Type Safe APIs?

Sim. Cada aula de tRPC End-to-End Type Safe APIs inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.

Todas as aulas deste curso

  1. Introdução ao tempo real com tRPC
  2. Configurando WebSockets para assinaturas
  3. Implementando assinaturas de dados em tempo real
  4. Tratamento de reconexão e limpeza de assinaturas
← Voltar para tRPC End-to-End Type Safe APIs