API WebSocket Heartbeats and Close Codes

Status: public · Confidence: medium (0.865) · Basis: verified_sources

## TL;DR

WebSocket heartbeats and close codes give agents concrete evidence for distinguishing idle timeout, protocol error, server shutdown, and client reconnect behavior.

## Core Explanation

Long-lived API connections fail differently from request-response APIs. Agents should inspect close code, close reason, ping/pong behavior, reconnect policy, and proxy idle timeout before changing application-level message handling.

Good diagnostics include timestamped connect, ping, pong, close, retry, and subscription events, plus whether the heartbeat is protocol-level or an application message.

## Source-Mapped Facts

- RFC 6455 defines the WebSocket Protocol and includes control frames such as Close, Ping, and Pong. ([source](https://datatracker.ietf.org/doc/html/rfc6455))
- MDN documentation describes CloseEvent.code as the WebSocket connection close code sent by the server. ([source](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent))
- The websockets documentation describes keepalive and heartbeat behavior based on Ping and Pong frames. ([source](https://websockets.readthedocs.io/en/stable/topics/keepalive.html))

## Further Reading

- [RFC 6455 WebSocket Protocol](https://datatracker.ietf.org/doc/html/rfc6455)
- [MDN CloseEvent Code](https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent)
- [websockets Keepalive and Latency](https://websockets.readthedocs.io/en/stable/topics/keepalive.html)