# How do streaming client applications handle unexpected network drops and implement automatic reconnection logic?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Reconnection Strategies, CometD Resiliency

Read it on the site: https://www.forcechallenges.com/interview-questions/how-do-streaming-client-applications-handle-unexpected-network-drops-and-implement-automatic-reconnection

## 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:**
1. Client does a `/meta/handshake`, then `/meta/subscribe` to `/event/Order_Event__e` (or `/data/...ChangeEvent`).
2. With the replay extension, the client supplies a ReplayId per channel: `-1` for only new events, `-2` for all retained events, or a specific stored value to resume.
3. Client persists the ReplayId of each processed message (after successful processing).
4. 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.
5. 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.

**Code / config example:**
```javascript
// Generic reconnect loop; connect() is your CometD/Pub-Sub wrapper that resolves when the stream ends
async function run() {
  let attempt = 0;
  for (;;) {
    try {
      const replayId = await loadReplayId();          // from durable storage, default -1
      await connect(replayId, async (msg) => {
        await process(msg);                           // idempotent handler
        await saveReplayId(msg.event.replayId);       // checkpoint after success
        attempt = 0;
      });
    } catch (e) { /* log */ }
    const delay = Math.min(60000, 1000 * 2 ** attempt++) + Math.random() * 500;
    await new Promise(r => setTimeout(r, delay));
  }
}
```

**Hidden gotchas & must-remember points:**
- Save the ReplayId only after successful processing.
- `-1` skips missed events; `-2` replays everything retained.
- Invalid or expired ReplayId causes subscription errors; plan a resync path.
- Subscriptions are not automatically restored after a re-handshake; resubscribe explicitly.
- Tokens expire; refresh before reconnect.
- Retention window is 72 hours for platform events and Change Data Capture is commonly cited the same; legacy PushTopic events are 24 hours (verify).

**Best practice:** Persist ReplayIds, back off with jitter, and keep handlers idempotent.

---
Source: ForceChallenges · last updated 2026-11-02
