0Pricing
WebSockets & Real-Time Systems with Spring · Lección

Heartbeats y keep-alives Ping/Pong

Detecte pronto las conexiones WebSocket inactivas mediante tramas ping/pong y heartbeats de STOMP, para que el servidor libere recursos y los clientes se reconecten rápidamente.

Heartbeats y keep-alives Ping/Pong es una lección gratuita de WebSockets & Real-Time Systems with Spring en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de WebSockets & Real-Time Systems with Spring, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

The Silent Death Problem

A WebSocket can look open long after the peer has vanished. A laptop lid closes, a network drops, a NAT mapping expires — yet neither side gets a close frame. This is a half-open connection.

Why It Matters

Half-open sockets waste server memory, keep sessions in maps forever, and let the client believe it is still receiving updates. You need an active probe to discover the truth: a heartbeat.

Ping/Pong Control Frames

The WebSocket protocol defines ping and pong control frames. One side sends a ping; a healthy peer must reply with a pong. No pong within a deadline means the connection is dead.

STOMP Heartbeats in Spring

When you use STOMP over WebSocket, Spring exposes heartbeat configuration. The two numbers are the rate (ms) the server sends and the rate it expects to receive heartbeats.

registry.enableSimpleBroker("/topic")
  .setHeartbeatValue(new long[]{10000, 10000})
  .setTaskScheduler(heartbeatScheduler());

A Scheduler Is Required

Heartbeats need a TaskScheduler to fire on time. Without one Spring silently disables them.

@Bean
public ThreadPoolTaskScheduler heartbeatScheduler() {
  ThreadPoolTaskScheduler s = new ThreadPoolTaskScheduler();
  s.setPoolSize(1);
  s.initialize();
  return s;
}

Client-Side STOMP Heartbeats

The client declares the matching heartbeat interval. Negotiation picks the slower of each side's value.

const client = new StompJs.Client({
  brokerURL: 'wss://api.example.com/ws',
  heartbeatIncoming: 10000,
  heartbeatOutgoing: 10000
});

Raw Ping at the Container Level

For plain (non-STOMP) handlers you can send ping frames directly from the server session.

PingMessage ping = new PingMessage(ByteBuffer.wrap(new byte[]{1}));
session.sendMessage(ping);

Choosing an Interval

Tune the interval to your needs:

  • Too short wastes bandwidth and battery on mobile
  • Too long delays detection of dead peers
  • 10–30 seconds is a common sweet spot

Beating Idle Timeouts

Proxies and load balancers drop connections that are idle too long (often 60s). A heartbeat doubles as keep-alive traffic that resets those idle timers and stops them from killing a healthy socket.

Reacting to a Missed Beat

When a heartbeat is missed, Spring closes the session and fires afterConnectionClosed. Use that hook to clean up state and let the client trigger its reconnect logic.

@Override
public void afterConnectionClosed(WebSocketSession s, CloseStatus status) {
  registry.remove(s.getId());
  log.warn("Closed {} - {}", s.getId(), status);
}

Heartbeats vs Application Acks

A heartbeat proves the transport is alive; it does not prove your message was processed. For business-level guarantees you still need application acknowledgements on top of heartbeats.

Quick Check

Test your grasp of keep-alives.

Recap

You made connections self-healing:

  • Half-open sockets die silently; heartbeats expose them
  • Ping/pong control frames probe transport health
  • STOMP heartbeats need a TaskScheduler and matching client intervals
  • Heartbeats also defeat proxy idle timeouts
  • Use the close callback to clean up and trigger reconnects

Preguntas frecuentes

¿La lección «Heartbeats y keep-alives Ping/Pong» es gratis?

Sí — el texto completo de «Heartbeats y keep-alives Ping/Pong» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de WebSockets & Real-Time Systems with Spring, actualiza a CoddyKit PRO. El curso de WebSockets & Real-Time Systems with Spring incluye 4 lecciones en total.

¿Qué aprenderé en «Heartbeats y keep-alives Ping/Pong»?

Detecte pronto las conexiones WebSocket inactivas mediante tramas ping/pong y heartbeats de STOMP, para que el servidor libere recursos y los clientes se reconecten rápidamente. Practicas WebSockets & Real-Time Systems with Spring con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar WebSockets & Real-Time Systems with Spring?

No se requiere experiencia previa. WebSockets & Real-Time Systems with Spring en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.

¿Cuánto tiempo toma la lección «Heartbeats y keep-alives Ping/Pong»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de WebSockets & Real-Time Systems with Spring?

Sí. Cada lección de WebSockets & Real-Time Systems with Spring incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. Gestión adecuada de errores de WebSocket
  2. Gestión del ciclo de vida de las conexiones
  3. Reintentos y mecanismos alternativos
  4. Heartbeats y keep-alives Ping/Pong
← Volver a WebSockets & Real-Time Systems with Spring