Heartbeats and Keep-Alives
Learn to use ping/pong frames and application-level heartbeats to maintain connection liveness and detect dead peers.
Why Heartbeats Matter
In realtime applications, maintaining an active and healthy connection is crucial. But what happens if a connection silently drops?
- Heartbeats are small, periodic messages exchanged between connected parties.
- They act as a 'pulse check' to confirm that both the client and server are still alive and responsive.
- This helps detect 'dead' connections that haven't properly closed, preventing resources from being tied up indefinitely.
The Silent Dead Peer
Imagine a client suddenly losing network connectivity (e.g., Wi-Fi drops, device sleeps) without gracefully closing its WebSocket connection.
- The server might still think the client is connected.
- Messages sent to this 'dead' client will never arrive.
- This wastes server resources and leads to inconsistent application states.
- Heartbeats provide a way to proactively identify and terminate these unresponsive connections.