DEV Community

EphraimPierce7934
EphraimPierce7934

Posted on

Device Notifications: Realtime Recovery or Polling Every 30 Seconds for Freshness

A disconnected dashboard has already spent part of its freshness budget before its next request starts. TL;DR: use polling every 30 seconds for e-commerce device status notifications when that delay is acceptable, and choose realtime when seeing the change immediately determines what the operator can do. Either choice needs an explicit recovery policy; opening a connection does not establish that missed updates will reach the screen.

For an ordinary notification bell, measure the harm from waiting before adding a socket. Chat, presence, and collaboration have a different requirement: a 30 second delay breaks the interaction. A warehouse device dashboard can fall on either side, depending on whether it summarizes recent activity or directs an operator's next action.

Should device notifications use realtime or polling every 30 seconds?

Consider a bounded production design exercise, rather than an incident report: an e-commerce operations dashboard shows the latest status of packing-station devices, loses connectivity, and returns after several status changes. The design question is whether the operator needs the current state or every transition that occurred while disconnected. Those are different acceptance criteria.

For this exercise, I would accept a fresh snapshot for a status summary and require a retained history for a workflow that must explain each transition. This is a proposed decision rule, not a claim about an existing deployment. A final state of online can make the summary correct while concealing an offline interval that an investigation needs to see.

Snapshots erase transitions. A status screen and an audit trail have different jobs, and the distinction survives every transport change.

The invariant is that the dashboard must not present an older device revision as its current state after reconnecting. If history matters too, state recovery alone cannot satisfy the requirement. Define where transitions are retained, how the client identifies its last applied position, and what happens when that position is outside the retention window before choosing a transport. Do not infer those properties from a publish operation or a successful connection.

This distinction changes the original polling question. A notification bell that tolerates half a minute can fetch current state periodically without maintaining a persistent subscription, a subscription token, or reconnect state. Its requests may still require authentication, and a failed request still needs handling. A dashboard that must reconstruct every device transition needs a history contract with either transport. Polling does not automatically provide one. Neither does push.

A 30 second interval is not a freshness SLO

A useful proposed SLO would measure elapsed time from a device state becoming available to the dashboard displaying it, with an explicit target and evaluation window. The polling interval is only one contributor: request duration, processing, rendering, and disconnected time also consume the budget. Calling a 30 second timer a 30 second delivery guarantee leaves no room for those contributors.

As a planning example, assume 900 active dashboards, each making one snapshot request every 30 seconds. That is an average of 30 requests per second before retries, additional tabs, or synchronized reconnects. These are hypothetical inputs and arithmetic, not observed traffic. A restart that aligns all clients can concentrate those requests, so capacity planning must account for bursts as well as the average. Stagger client schedules and bound retries.

Measure the tail. Don't size the recovery path from the steady-state average.

For realtime, perform the same exercise with concurrent connections, subscription fan-out, and recovery reads after an interruption. Moving the steady-state delivery path onto sockets does not eliminate the work needed to rebuild a screen. In particular, a reconnect wave can require snapshots at the same time that the service resumes live delivery, making the recovery path a separate capacity concern.

The platform roadmap should therefore budget for both steady operation and recovery. If a bell tolerates the wait, polling avoids persistent connection management and is the simpler default. If stale device status sends an operator to the wrong station, define the tighter freshness objective first and evaluate realtime against it. There is no measured latency or availability result here that would justify declaring a provider the winner. In the packing-station exercise, the crucial review is what happens between the initial snapshot request and the moment live updates become visible: if an update is accepted and then an older snapshot overwrites it, a connected dashboard can still be wrong, while a lost update between reading the snapshot and subscribing can leave the screen stale until another change happens. Establish overlap or a documented recovery position, define the revision comparison, and include this interval in the acceptance test instead of treating connection establishment as the end of recovery.

Buy versus build depends on the recovery contract

The following comparison separates delivery products from the application policy that decides whether recovered state is correct. Vendor documentation belongs in the review, but the acceptance test belongs to the team operating the dashboard.

Option What the team buys or builds Fit for this dashboard Trade-off to resolve
Application-owned HTTP polling Build periodic reads against the application's current-state store A notification bell or device summary that tolerates the interval The team owns read capacity, request failures, and any transition history
Ably Buy managed realtime messaging, with documented connection recovery and message history concepts Evaluate when reconnect continuity is central to the workflow Check recovery conditions and history configuration against the required interruption window; integration adopts provider-specific semantics
Pusher Channels Buy managed channel-based event delivery Evaluate for live updates when the application can supply its recovery snapshot Decide how missed application state is retrieved and reconciled; channel delivery alone is not the application's historical record
PubNub Buy managed publish/subscribe with documented Message Persistence capabilities Evaluate when retained messages are part of the backfill design Review persistence configuration and retrieval semantics alongside the application's ordering and retention needs

Infrai is worth evaluating when one key and one bill across backend services simplify credential inventory and invoice reconciliation, and its unified REST API covers 295 routes across 20 modules, so a Go worker can use plain HTTP with no SDK required rather than adopting a separate SDK for each adjacent backend integration. Those verified integration advantages do not establish a reconnect or backfill guarantee; require that guarantee to be demonstrated for the intended workflow.

Managed delivery transfers some operational work to a provider while leaving application correctness with the team. Application-owned polling keeps the delivery model small, but its reads still need an operated backend. Compare on-call responsibility, recovery semantics, and the effort to replace a provider's client behavior; a feature checkbox is too coarse to make that decision.

The buy-versus-build boundary should follow the data model. If the application already owns an authoritative device snapshot, it can use that snapshot to restore a summary screen across delivery choices. If the application requires a complete event history, select and operate that history deliberately rather than treating a live channel as an implicit archive.

Keep recovery from overwriting a newer device update

Here is a runnable Go example that first reads the service discovery contract over HTTP, then exercises the preventative merge path locally. Configure INFRAI_BASE_URL with the service's HTTPS API base ending in /v1 and INFRAI_API_KEY with a server-side key. Discovery is public; the example uses the standard Bearer authentication convention so the request pattern remains explicit. Keep the key on the server.

The device IDs and revisions below are illustrative application data, not provider request fields. The local contract assumes one authoritative, monotonically increasing revision per device, an authoritative snapshot covering the requested devices, and live updates buffered while that snapshot is obtained.

The example deliberately models an update that overlaps the snapshot. Blindly assigning the snapshot afterward would move the displayed state backward. The merge rejects that regression and tolerates duplicate delivery without requiring a transport-specific SDK.

package main

import (
    "fmt"
    "io"
    "net/http"
    "net/url"
    "os"
    "sort"
    "strconv"
    "strings"
    "time"
)

func inspectContract() error {
    base := strings.TrimRight(os.Getenv("INFRAI_BASE_URL"), "/")
    key := os.Getenv("INFRAI_API_KEY")
    parsed, err := url.Parse(base)
    if err != nil || parsed.Scheme != "https" || parsed.Host == "" ||
        parsed.Path != "/v1" || parsed.RawQuery != "" ||
        parsed.Fragment != "" || parsed.User != nil || key == "" {
        return fmt.Errorf("set an HTTPS API base ending in /v1 and a server-side key")
    }
    client := &http.Client{
        Timeout: 10 * time.Second,
        CheckRedirect: func(_ *http.Request, _ []*http.Request) error {
            return http.ErrUseLastResponse
        },
    }
    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(http.MethodGet, base+"/discovery", nil)
        if err != nil {
            return err
        }
        req.Header.Set("Authorization", "Bearer "+key)
        resp, err := client.Do(req)
        if err != nil {
            return err
        }
        body, readErr := io.ReadAll(io.LimitReader(resp.Body, 8<<20))
        resp.Body.Close()
        if readErr != nil {
            return readErr
        }
        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second * time.Duration(1<<attempt)
            retryAfter := resp.Header.Get("Retry-After")
            if seconds, err := strconv.Atoi(retryAfter); err == nil && seconds >= 0 {
                if wait := time.Duration(seconds) * time.Second; wait > delay {
                    delay = wait
                }
            } else if date, err := http.ParseTime(retryAfter); err == nil {
                if wait := time.Until(date); wait > delay {
                    delay = wait
                }
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            return fmt.Errorf("discovery HTTP %d: %s", resp.StatusCode, body)
        }
        fmt.Println(string(body))
        return nil
    }
    return fmt.Errorf("discovery retry budget exhausted")
}

type DeviceState struct {
    ID       string
    Revision uint64
    Status   string
}

func apply(states map[string]DeviceState, update DeviceState) {
    current, exists := states[update.ID]
    if !exists || update.Revision > current.Revision {
        states[update.ID] = update
    }
}

func main() {
    if err := inspectContract(); err != nil {
        fmt.Fprintln(os.Stderr, err)
        os.Exit(1)
    }
    displayed := map[string]DeviceState{
        "packing-17": {ID: "packing-17", Revision: 40, Status: "online"},
    }
    snapshot := []DeviceState{
        {ID: "packing-17", Revision: 42, Status: "offline"},
        {ID: "packing-18", Revision: 7, Status: "online"},
    }
    buffered := []DeviceState{
        {ID: "packing-17", Revision: 43, Status: "online"},
        {ID: "packing-17", Revision: 42, Status: "offline"},
        {ID: "packing-17", Revision: 43, Status: "online"},
    }

    // A live update can arrive before snapshot processing finishes.
    apply(displayed, buffered[0])
    for _, state := range snapshot {
        apply(displayed, state)
    }
    for _, state := range buffered {
        apply(displayed, state)
    }

    recovered := displayed["packing-17"]
    if recovered.Revision != 43 || recovered.Status != "online" {
        panic("recovery regressed the displayed device state")
    }
    ids := make([]string, 0, len(displayed))
    for id := range displayed {
        ids = append(ids, id)
    }
    sort.Strings(ids)
    for _, id := range ids {
        state := displayed[id]
        fmt.Printf("%s revision=%d status=%s\n", id, state.Revision, state.Status)
    }
}
Enter fullscreen mode Exit fullscreen mode

Save it as main.go and run it with the Go toolchain after setting the environment variables. The read-only discovery request prints the contract for review, handles HTTP errors, and retries rate limits with exponential backoff while respecting Retry-After. It makes no write that would need an idempotency key. The device recovery check remains in memory; it does not establish a subscription or retrieve history. A production implementation must also bound the recovery buffer and restart recovery if that buffer overflows, since silently dropping buffered updates would invalidate the assumed coverage.

The boundary matters. This code is suitable for latest-state display under its stated revision contract; it cannot reconstruct the duration of the offline interval, handle deletion without a tombstone policy, or resolve competing writers whose revisions are incomparable. Equal revisions must identify the same state. If those assumptions do not hold, fix the application contract before reusing the merge.

For a history-dependent workflow, accept recovery only after the required transition range is accounted for, and make incomplete recovery visible to the operator. For a summary dashboard, accept recovery after a fresh snapshot and overlapping updates have been reconciled. Then test interrupted recovery, duplicate updates, stale snapshots, and recovery load against the chosen SLO. The recommendation remains narrow: keep 30 second polling when the wait is acceptable; add realtime when the delay itself changes the product's usefulness.

References

The provider references below describe delivery and recovery concepts to inspect during selection. They are not evidence of measured performance in this dashboard. The WebSocket standard defines the transport; WebRTC concerns a different browser communication API and does not establish notification backfill semantics.

Sources

Top comments (0)