Heartbeats and Ping/Pong Keep-Alives
Detect dead WebSocket connections early using ping/pong frames and STOMP heartbeats so the server reclaims resources and clients reconnect promptly.
Heartbeats and Ping/Pong Keep-Alives is a free WebSockets & Real-Time Systems with Spring 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 WebSockets & Real-Time Systems with Spring learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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
TaskSchedulerand matching client intervals - Heartbeats also defeat proxy idle timeouts
- Use the close callback to clean up and trigger reconnects
Frequently asked questions
Is the “Heartbeats and Ping/Pong Keep-Alives” lesson free?
Yes — the full text of “Heartbeats and Ping/Pong Keep-Alives” is free to read here on the web, and the WebSockets & Real-Time Systems with Spring 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 WebSockets & Real-Time Systems with Spring course, upgrade to CoddyKit PRO.
What will I learn in “Heartbeats and Ping/Pong Keep-Alives”?
Detect dead WebSocket connections early using ping/pong frames and STOMP heartbeats so the server reclaims resources and clients reconnect promptly. You practise WebSockets & Real-Time Systems with Spring 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 WebSockets & Real-Time Systems with Spring?
No prior experience is required. WebSockets & Real-Time Systems with Spring 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 “Heartbeats and Ping/Pong Keep-Alives” 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 WebSockets & Real-Time Systems with Spring lesson?
Yes. Every WebSockets & Real-Time Systems with Spring 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
- Handling WebSocket Errors Gracefully
- Connection Lifecycle Management
- Retries and Fallbacks
- Heartbeats and Ping/Pong Keep-Alives