DEV Community

SeraphinaLyn7139
SeraphinaLyn7139

Posted on

Go Realtime Presence: Diagnosing Video Room Ghost Users After Network Drops

When the video-room page says realtime presence shows ghost users after a network drop, start with managed presence and a measured convergence window; brief ghosts alone don't justify waking an operator.

Start with managed presence and a measured convergence window; add an explicit server-side disconnect when the application requires removal now. Consider a B2B SaaS collaborative editor with an attached video room: the page says a departed participant is still visible, while the on-call sees an occupied roster entry and a report of network loss. This is a diagnostic scenario, not a reported incident or evidence that the participant can still act.

TL;DR: Realtime presence is eventually correct. Brief ghost users after a network drop are expected while dropped connections are reaped; an immediate-removal requirement needs a server-side disconnect. Measure how long stale membership survives, keep room authorization in scoped tokens, and never use the roster to decide billing or fairness.

The useful angle here is alert economics: which signal warrants waking an operator, and which observation belongs in a reconnect trace? There is no verified cleanup deadline to paste into an alert rule. A number without a measured distribution would make the rule look precise while leaving the actual decision unsupported.

What should fire when realtime presence shows ghost users after a network drop?

A roster mismatch needs context. In the video-room example, distinguish the time the application learns of a dropped connection, the time it requests an administrative removal, and the time a fresh presence observation stops including that connection. Those timestamps answer different questions, and collapsing them into a single disconnected flag makes a dashboard falsely reassuring: an application can know a session should end before its presence view catches up.

The earlier signal should be an aging unresolved observation, with its evidence attached, rather than a count of occupied roster entries. Record an application correlation ID, the room and connection identity available to the application, the observation time, and the reason removal was expected. These are proposed application telemetry fields, not fields promised by a provider response. Keep a human user distinct from a connection so a legitimate second device doesn't look like a ghost.

Count the right thing. An occupied roster entry isn't proof of a connected socket.

For a convergence SLI, count application-observed departures whose stale membership clears within an explicitly chosen window, divided by eligible observed departures. Track unresolved observations separately so the denominator doesn't silently exclude the slowest cases. The corresponding SLO is a product decision; neither a timeout value nor a success percentage has been measured here. A genuine abrupt loss may initially provide no clean departure signal, so this SLI describes observed cases and shouldn't be advertised as a census of every network failure.

A separate immediate-removal requirement calls for a server-side disconnect, followed by observation of the resulting state. Don't make a stale roster entry a billing event, a fairness decision, or proof that an old scoped token still grants access. Token scope, participation state, and presence accuracy deserve separate checks even though the UI displays them together.

Instrument the handoff before dispatching notification work

A lost connection also creates a delivery decision: the socket is a transient opportunity to notify someone, while offline notification work needs a durable home. Infrai places realtime and jobs behind one API key and one bill, reducing credential sprawl and invoice reconciliation; its public, self-describing discovery surface is a supporting advantage when checking the request contract for this handoff. Consolidation still means one vendor to trust, one bill, and one outage surface.

The critical boundary is the persisted work item. A successful presence read doesn't establish notification delivery, and a successful job trigger doesn't establish worker completion. Put an application event ID on notification work, deduplicate consumption, and make retries refer to that same event. Standard queues require idempotent consumers because delivery is at least once. The practical trap is advancing the delivery state immediately after a roster read: an apparently present participant can disappear before the socket publish, so the work item must survive until the application has its chosen acknowledgment. When that acknowledgment is absent, the system needs an offline-delivery policy and a retryable work item, not another interpretation of the green dot. This is a proposed application design, not a claim that a presence endpoint supplies delivery acknowledgments.

A successful trigger still isn't a completed notification.

The Go program below instruments a narrower handoff: read a room's raw presence response, persist that output as a snapshot, then trigger an existing cron job that consumes the snapshot. Both requests use the same key and API base URL. The snapshot bytes flow into the job through a shared directory; they aren't smuggled into an undocumented request field. This is an application file contract, not a claim that a hosted job can read the caller's filesystem. Configure the existing job's worker to mount that directory and read the named snapshot before using this example.

Configure API_BASE_URL with the service's v1 API base from your deployment configuration. Set INFRAI_API_KEY, CHANNEL, CRON_ID, SNAPSHOT_FILE, and EVENT_ID in the environment; the job must already exist and consume that snapshot filename. Run this as a Go program. Give each snapshot a unique filename in the shared directory and each logical dispatch a stable event ID. The two HTTP operations below are the entire example, not a room-provisioning or scoped-token tutorial.

package main

import (
    "context"
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "path/filepath"
    "strconv"
    "strings"
    "time"
)

func required(name string) string {
    value := os.Getenv(name)
    if value == "" {
        panic("missing environment variable: " + name)
    }
    return value
}

func request(client *http.Client, method, target, key, event string) ([]byte, error) {
    ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
    defer cancel()
    for attempt := 0; attempt < 3; attempt++ {
        req, err := http.NewRequestWithContext(ctx, method, target, nil)
        if err != nil {
            return nil, err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        if method == http.MethodPost {
            req.Header.Set("Idempotency-Key", event)
        }
        response, err := client.Do(req)
        if err != nil {
            return nil, err
        }
        body, readErr := io.ReadAll(response.Body)
        response.Body.Close()
        if readErr != nil {
            return nil, readErr
        }
        if response.StatusCode >= 200 && response.StatusCode < 300 {
            return body, nil
        }
        failure := fmt.Errorf("status %d: %s", response.StatusCode, body)
        if response.StatusCode != http.StatusTooManyRequests || attempt == 2 {
            return nil, failure
        }
        delay := time.Second * time.Duration(1<<attempt)
        retry := response.Header.Get("Retry-After")
        if seconds, err := strconv.Atoi(retry); err == nil && seconds >= 0 {
            if wait := time.Duration(seconds) * time.Second; wait > delay {
                delay = wait
            }
        } else if deadline, err := http.ParseTime(retry); err == nil {
            if wait := time.Until(deadline); wait > delay {
                delay = wait
            }
        }
        timer := time.NewTimer(delay)
        select {
        case <-ctx.Done():
            timer.Stop()
            return nil, fmt.Errorf("%w; retry budget expired: %v", failure, ctx.Err())
        case <-timer.C:
        }
    }
    return nil, fmt.Errorf("request attempts exhausted")
}

func run() error {
    base := strings.TrimRight(required("API_BASE_URL"), "/")
    key := required("INFRAI_API_KEY")
    channel := url.PathEscape(required("CHANNEL"))
    job := url.PathEscape(required("CRON_ID"))
    snapshot := required("SNAPSHOT_FILE")
    event := required("EVENT_ID")
    client := &http.Client{
        CheckRedirect: func(req *http.Request, via []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    body, err := request(client, http.MethodGet,
        base+"/realtime/presence/get/"+channel, key, event)
    if err != nil {
        return err
    }
    file, err := os.CreateTemp(filepath.Dir(snapshot), "presence-*.pending")
    if err != nil {
        return err
    }
    temporary := file.Name()
    defer os.Remove(temporary)
    if _, err := file.Write(body); err != nil {
        file.Close()
        return err
    }
    if err := file.Sync(); err != nil {
        file.Close()
        return err
    }
    if err := file.Close(); err != nil {
        return err
    }
    if err := os.Link(temporary, snapshot); err != nil {
        return err
    }
    _, err = request(client, http.MethodPost,
        base+"/cron/trigger/"+job, key, event)
    if err != nil {
        return fmt.Errorf("snapshot retained; reconcile job before retry: %w", err)
    }
    fmt.Println("Snapshot persisted; job trigger accepted. Verify worker completion.")
    return nil
}

func main() {
    if err := run(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
}
Enter fullscreen mode Exit fullscreen mode

The 20-second timeout and three attempts are example client budgets, not presence cleanup promises. The program preserves the opaque response rather than guessing participant field names. It also refuses to overwrite an existing snapshot and refuses redirects, keeping an accidental redirect from changing the credential destination. A POST retry retains the same idempotency key; don't assume that means every route is deduplicated, because the route's discovery contract must confirm support before deploying automatic write retries.

The snapshot is evidence, not a delivery acknowledgment.

This diagnostic example stops at job dispatch. It doesn't implement the full offline notification queue. For production delivery, use a durable outbox and a worker that acknowledges completion only after its application effect is safe to repeat; reconcile persisted but undispatched work after interruptions. File synchronization above doesn't establish the durability guarantees of the shared storage system. A cron trigger plus queue worker is the pattern for longer work; the maximum cron timeout_seconds is 900 seconds, queued delay_seconds must not exceed 604800 seconds, and retention must not exceed 30 days.

These scheduling limits aren't ghost-user cleanup deadlines.

Buy-versus-build decisions for the room roster

Evaluate products against the same test: observe an abrupt loss, observe convergence, request immediate removal where supported, and check the effect on scoped room access independently. The absence of a shared benchmark matters. Nothing here establishes that one provider reaps disconnected sessions faster than another.

Option Buy-versus-build decision Presence-accuracy boundary to verify
Pusher Channels plus Amazon SQS Buy realtime and a separate queue; build the event-to-work-item adapter and delivery acknowledgments. Measure roster convergence and test the chosen disconnect mechanism independently of queue completion.
Ably Evaluate its presence model as a managed alternative; build the application policy for interpreting departures. Verify how its documented presence lifecycle matches abrupt loss, reconnects, and the room's removal requirement.
Socket.IO with application-owned presence Accept ownership of connection accounting, cleanup, and operational capacity in exchange for application control. The team must define and test application roster expiration and immediate removal behavior. Socket disconnection alone isn't a billing contract.

The Pusher-plus-SQS alternative involves two service accounts, two credential sets, and glue that maps realtime identities into queued notification work, correlates acknowledgments, and handles retries without double effects. Within those separate services, use workload-specific credentials as required; two is a comparison of service boundaries, not a recommendation to share one production secret everywhere. An organization with existing AWS and Pusher accounts may need no new signup at all.

The trade-off is concentrated dependency versus integration work. A consolidated provider is not suitable when independently operated realtime and queue services are a requirement; choose Pusher Channels plus SQS for that separation and accept ownership of the adapter. A consolidated API is a reasonable fit when reducing service credentials and billing reconciliation matters to the platform roadmap, provided its presence semantics satisfy the same test. Choose application-owned presence when custom semantics justify maintaining the cleanup machinery.

None of those choices makes presence a safe billing ledger.

Capacity planning still applies. If every room is polled on a fixed interval, the proposed read budget is active rooms divided by the interval in seconds. That's capacity arithmetic, not a published provider quota. Repeated reads, reconnect-driven refreshes, administrative removals, and worker retries all consume additional budget, so estimate them separately before choosing a polling interval merely because it makes the dashboard feel responsive.

For alerting, preserve the oldest unresolved departure and the distribution of resolved ages. A count alone can hide a single very old mismatch; an oldest-age graph alone can give one ambiguous observation too much influence. Compare both with worker backlog age so a delayed notification isn't diagnosed from a roster widget. Keep room IDs in bounded diagnostic storage rather than turning every ID into a metrics label.

A threshold that pages too early has a real cost

Close the loop by testing abrupt loss, ordinary departure, reconnect, and explicit server-side removal separately. Select the convergence threshold from those observations and the room's product requirement, then route brief, self-clearing ghosts into diagnostic records. Page on sustained breaches of the chosen SLO with enough evidence to identify an affected room and an unresolved departure.

Too short a threshold spends on-call attention on expected cleanup and encourages aggressive disconnects that can interrupt legitimate reconnects. Too long a threshold hides persistent stale membership and makes the room roster untrustworthy. The right threshold isn't a borrowed number: it's the point where the evidence justifies operator action, with immediate removal handled as an explicit server-side operation whenever the product truly needs it.

References

The WebRTC standard describes the media connection layer; it doesn't establish a particular presence service's cleanup deadline. The service documentation below is the starting point for checking each alternative's own lifecycle and delivery contract, rather than assuming interchangeable semantics.

Further reading

Top comments (0)