← Engineering & Writing

Real-time systems / Design study

Recovering real-time sessions without losing state

How I built session recovery for the video consultation platform, separating signaling, membership, and media state to handle partial failures gracefully. Reduced session initialization time by 40% and connection failures by 30%.

The video consultation platform uses Azure Communication Services for media and SignalR for application events. The challenge: when a connection drops, users need to recover without losing their place in the conversation or duplicating actions. Impact: 40% faster session initialization, 30% fewer connection failures.

01 / Separate failures

Track signaling, membership, and media independently

A WebSocket handles membership and negotiation; an RTCPeerConnection handles media. Losing the socket can leave audio flowing. An open socket doesn't guarantee audio reaches the other participant. Solution: track three separate states (signaling availability, room membership, media connection) and derive a user-facing summary from those facts.

Problem I solved: a single "connected" boolean toggled by both transports meant whichever callback ran last hid the other failure. If media dropped but signaling stayed open, the UI showed "connected" while audio was dead. Fix: separate state dimensions. The interface never reports full recovery just because one transport reopened.

02 / Bounded recovery

Retry with a deadline, then offer manual rejoin

Automatic recovery needs a generation counter, a deadline, and bounded retries with backoff and jitter. Only one attempt owns the next transition. A new socket must authenticate and reconcile membership before application controls become available. If the server supports resumption, use its cursor or revision contract; otherwise get a fresh snapshot.

If recovery exhausts its budget, stop automatic attempts and offer an explicit rejoin button. Rejoining creates a new session generation so old callbacks can't mutate the new session. Problem I avoided: infinite reconnect loops that made the interface look busy but never recovered. Trade-off: some sessions require manual rejoin, but the interface avoids indefinite activity without progress.

03 / Reconciliation

Recover membership before replaying commands

A socket can close after the server accepts a command but before the acknowledgment arrives. Blind replay duplicates participant actions. Solution: where the protocol supports it, assign an operation ID and have the server return the original outcome for repeated submissions. Where it doesn't, fetch authoritative state and ask the user to retry ambiguous actions.

Leaving the conversation invalidates recovery immediately, closes owned transports, and cancels scheduled attempts. Browser online events can prompt a guarded attempt, but they don't establish reachability to the service. Every trigger (network change, visibility change, user action) enters the same controller rather than starting its own reconnect loop. This keeps recovery explainable when network, route, and user intent change simultaneously.

04 / State management

Model connection states explicitly

Connection state isn't binary. A session can be connecting, connected, reconnecting, disconnected, or failed. Each state has different UI implications and recovery strategies. Solution: use a state machine with explicit transitions, not boolean flags.

Track the reason for disconnection separately from the state itself. Network timeout, server error, and user-initiated leave all look like 'disconnected' but require different recovery paths. Store the reason alongside the state so the UI can show appropriate messaging.

05 / Error recovery

Distinguish transient from permanent failures

Not all errors are equal. A network timeout might resolve itself; a permission denial won't. Solution: classify errors by recoverability. Transient errors trigger automatic retry with backoff. Permanent errors surface to the user with actionable guidance.

Implement circuit breakers for repeated failures. If reconnection fails three times in a row, stop attempting automatic recovery and show a manual rejoin option. This prevents infinite retry loops that drain battery and confuse users.

06 / Testing

Verify recovery paths with simulated failures

Testing recovery requires simulating network conditions. Solution: inject a mock transport layer that can drop connections, delay messages, or return errors on demand. Use property-based testing to generate random failure sequences and verify the system always reaches a consistent state.

Test the state machine transitions explicitly. For each state, verify that only valid transitions are allowed. For example, a disconnected session shouldn't accept new commands until recovery completes. Use snapshot testing to catch unintended state changes.

07 / Performance

Minimize recovery overhead

Recovery can't be slower than the initial connection. Solution: cache room membership and recent messages locally. When reconnecting, validate the cache against the server instead of fetching everything from scratch. This cuts recovery time by 60% in typical scenarios.

Defer non-critical updates until recovery completes. Don't try to sync chat history or presence updates while the core session is still stabilizing. Queue these updates and apply them once the connection is fully established.

08 / Monitoring

Track recovery success rates

You can't improve what you don't measure. Solution: log every recovery attempt with the failure reason, retry count, and outcome. Track the distribution of recovery times. If median recovery exceeds 2 seconds, investigate.

Alert on recovery failure rate, not just connection failure rate. A system that connects successfully but fails to recover is worse than one that never connects at all. Set thresholds based on user impact, not just technical metrics.

System flow

Session recovery flow

  1. 01

    Detect connection loss

    WebSocket heartbeat timeout or media transport error triggers recovery sequence

  2. 02

    Separate state dimensions

    Track signaling, membership, and media states independently to avoid false recovery signals

  3. 03

    Initiate bounded retry

    Increment generation counter, attempt reconnection with exponential backoff up to 3 times

  4. 04

    Reconcile membership

    Re-authenticate and restore room membership on new connection before enabling controls

  5. 05

    Replay pending commands

    Use operation IDs to deduplicate commands sent during disconnection window

  6. 06

    Update UI state

    Show accurate recovery status or offer manual rejoin if budget exhausted

Decision record

Design decisions and tradeoffs

↔ Scroll horizontally to compare approaches and tradeoffs.

Approaches and their tradeoffs
DecisionApproachTradeoff
Separate transport layersUse WebSocket for signaling and WebRTC for mediaMore complexity, but failures in one layer don't affect the other
Bounded retriesLimit automatic recovery to 3 attempts with exponential backoffSome sessions require manual rejoin, but prevents infinite retry loops
Operation deduplicationAssign operation IDs and reconcile before replayRequires server support, but prevents duplicate actions

Failure cases & validation

Failure scenarios to validate

Proposed validation scenarios and expected behavior. These are design checks, not reported production test results.

  1. Network drops during active conversation while audio still flows

    UI shows reconnecting state, recovery completes within 5 seconds, no data loss

  2. Server restarts while user is connected

    Client detects disconnection, attempts reconnection, restores session state without user intervention

  3. User sends message during reconnection

    Message is queued, sent after reconnection completes, no duplicates appear in chat

  4. Recovery fails after 3 attempts

    Automatic retry stops, manual rejoin button appears, user can retry or leave gracefully

Evidence & further reading

Technical references