How do streaming client applications handle unexpected network drops and implement automatic reconnection logic?
Answer
Basics: CometD uses long polling: the client holds an HTTP connection open and the server responds when events arrive. Connections get dropped by networks, proxies and the server itself, so reconnection is a normal part of operation, not an edge case.
How it works:
- Client does a
/meta/handshake, then/meta/subscribeto/event/Order_Event__e(or/data/...ChangeEvent). - With the replay extension, the client supplies a ReplayId per channel:
-1for only new events,-2for all retained events, or a specific stored value to resume. - Client persists the ReplayId of each processed message (after successful processing).
- On disconnect or a handshake/connect failure, wait with exponential backoff (for example 1s, 2s, 4s up to a cap, plus random jitter), then re-handshake and resubscribe with the stored ReplayId.
- If the server says the client is unknown (session expired), a full re-handshake is required.
Advanced / deep dive: Retained events can be replayed for 72 hours; a ReplayId older than that is invalid and the server returns an error, so detect it and fall back to a full resync via query. Since processing is at-least-once, replay produces duplicates, so make handlers idempotent. Newer integrations should consider the gRPC-based Pub/Sub API, which uses client-pulled, flow-controlled streams and explicit replay positions. Handle token expiry by refreshing the OAuth token before re-handshake. Stagger reconnects across many clients to avoid thundering herds, and respect concurrent-client allocation limits per org (verify numbers per edition). In LWC, lightning/empApi handles CometD for you but does not persist ReplayId, so store it yourself if you need it.