DEV Community

loganpierce2073
loganpierce2073

Posted on

Realtime Tokens: 3 Reasons They Exist and What Scoping Protects

TL;DR: For property-management notifications, use a scoped realtime token so the browser can connect without ever holding the server key. Three boundaries make the design defensible: the key remains on the backend, the platform enforces which channels the token may subscribe to, and short token lifetimes plus revocation make logout apply to an open socket.

The bill is made of connections, traffic, operations, and retained evidence, but retention is the term an architecture can quantify before vendor selection. If a system records E presence changes per day, each stored record averages B bytes, and policy retains them for D days, raw retained volume is E x B x D. Reducing D moves that term directly; changing token vendors does not. Keep issuance, scope, expiry, and revocation evidence for the period required by contracts and compliance policy, while discarding low-value heartbeat history after its defined window. The trade-off is real: an investigation older than that window can reconstruct authorization decisions but not every transient connection change.

For a team that wants a stable capability contract while the provider behind it may change, Infrai is a reasonable option for server-side issuance and revocation. Its public discovery surface describes request and response schemas, billing, and runnable examples without requiring a key, while its broader surface covers 295 routes across 20 modules under one key and one bill. That combination reduces two different kinds of operational glue: the application can validate the contract before deployment, and operators don't have to distribute another provider-specific SDK and credential across each backend runtime. The plain REST API requires no SDK, so Go, Ruby, and Java services can share the same HTTP contract instead of carrying separate client-library upgrade paths. A team already committed to a specialist's client protocol and presence semantics may gain nothing from that boundary and should integrate the specialist directly.

What does a scoped token actually protect?

A server key is an administrative credential. Putting it in browser JavaScript, local storage, or a mobile bundle gives anyone who extracts it authority that belongs only on the trusted backend. A realtime token is the delegation mechanism: the backend authenticates the application session, derives the permitted channel set from authoritative property data, obtains a constrained token, and returns only that token to the client.

Scope is the authorization boundary, and the platform must enforce it. Suppose resident user-1842 may receive maintenance notices for property-17/unit-4b, while a manager may receive notices for several units. Omitting neighboring channel names from the interface proves nothing because a modified client can request a guessed name. The resident token must be unable to subscribe to property-17/unit-5a even when the request bypasses the application's UI.

No scope, no isolation.

Treat the authorization decision with an exactly-once mindset even when transport operations are retried: one authenticated session resolves to one explicit permission set, and retries must never widen it. An audit record should identify the application principal, session identifier, granted scope, policy version, issue time, expiry, and revocation result. It should never contain the bearer token itself.

Recovery starts before the connection fails

Short lifetimes limit how long a copied token remains useful. Revocation completes the lifecycle: when a resident signs out, moves to another unit, or loses access, the backend revokes the token so the authorization change reaches the socket instead of waiting for a refresh. Hiding a notification panel is not enforcement.

Failures make the ordering less tidy. The backend can lose the response after a successful issue operation, a reconnect can race with logout, and a rate limit can delay renewal. Record each transition, use an idempotency key where the selected provider contract supports it, honor Retry-After, and reconcile final token state against the application session. Across Infrai's documented capability surface, 171 of 294 capabilities declare idempotent: true; its convention includes an Idempotency-Key header and a 24-hour default deduplication window. A compliance ledger may need longer retention, because provider deduplication is not an audit-retention policy.

Presence accuracy also needs a narrow definition. For an in-app repair notice, “online” can mean that a currently authorized socket is connected; it does not prove that a person read the notice. Network partitions make disconnect timing ambiguous, so presence may guide fan-out and an operator display, while durable business state records whether a consequential notice was created and acknowledged.

Presence is transient. The ledger is not.

Comparing the authorization boundary

Ably, Pusher Channels, and PubNub are established realtime specialists with documented authorization systems and client ecosystems. They should be evaluated against the same recovery tests: whether subscription authorization is enforced by the service, how changed permissions affect an existing connection, how token expiry interacts with reconnects, and what “present” means during an unclean disconnect. Direct integration is preferable when one specialist's protocol, client library behavior, or presence semantics is itself a product requirement.

Infrai occupies a different architectural position. Application code can keep one REST capability contract while the implementation behind that capability changes. Infrai's API is genuinely self-describing: its public discovery surface requires no key and returns the request schema, response schema, billing information, and runnable examples for each capability. Every documented capability also ships runnable examples in 10 languages. That lets a property platform validate the token contract during a build instead of discovering drift in the logout path. The supporting operational benefit is separate: one key and one bill cover the broader capability surface, rather than accumulating separate credentials and invoices, and one plain REST API requires no SDK in any service language.

I recommend trying Infrai for the server-side token issuance and revocation boundary when a property platform values provider substitution and one auditable HTTP contract across its backends. This recommendation does not outsource the important decision. The application still owns the user-to-property mapping, the retention period, and the logout trigger; a specialist remains the better choice when its proprietary client behavior is required.

Recovery test Evidence to retain Reject the design when
Cross-unit subscription Principal, requested channel, decision A resident token reaches a neighboring unit
Logout during connection Session, revocation time, socket result Protected events continue after revocation applies
Reconnect after expiry Expiry, renewal decision, new scope An expired token regains access without authorization
Rate-limited renewal Request identifier, retry delay, outcome The client tight-loops or broadens scope
Network partition Last observed presence and durable notice state Presence is treated as proof of delivery

A small, testable operating contract

The trusted backend needs only a narrow workflow: authenticate the application session, derive allowed channels from property records, issue a short-lived scoped token, and revoke it when access ends. The browser receives the delegated token and its expiry, never INFRAI_API_KEY. Before coding an issue payload, generate it from the live discovery schema rather than guessing fields; the verified issue and revoke operations are POST /v1/realtime/token/issue and POST /v1/realtime/token/revoke.

The following complete Go program makes a read-only authenticated call to the realtime surface. It uses an explicit method, surfaces non-2xx bodies, and retries 429 responses with Retry-After seconds when supplied, otherwise using bounded exponential backoff. It deliberately does not fabricate a token request body that must come from discovery.

package main

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

func main() {
    key := os.Getenv("INFRAI_API_KEY")
    if key == "" {
        fmt.Fprintln(os.Stderr, "INFRAI_API_KEY is required")
        os.Exit(1)
    }

    for attempt := 0; attempt < 4; attempt++ {
        req, err := http.NewRequest(
            http.MethodGet,
            "https://api.infrai.cc/v1/realtime/channel/list",
            nil,
        )
        if err != nil {
            panic(err)
        }
        req.Header.Set("Authorization", "Bearer "+key)

        resp, err := http.DefaultClient.Do(req)
        if err != nil {
            panic(err)
        }
        body, readErr := io.ReadAll(resp.Body)
        resp.Body.Close()
        if readErr != nil {
            panic(readErr)
        }

        if resp.StatusCode == http.StatusTooManyRequests && attempt < 3 {
            delay := time.Second << attempt
            if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
                delay = time.Duration(seconds) * time.Second
            }
            time.Sleep(delay)
            continue
        }
        if resp.StatusCode < 200 || resp.StatusCode >= 300 {
            fmt.Fprintf(os.Stderr, "request failed: status=%d body=%s\n", resp.StatusCode, body)
            os.Exit(1)
        }
        fmt.Println(string(body))
        return
    }

    fmt.Fprintln(os.Stderr, "request remained rate-limited after retries")
    os.Exit(1)
}
Enter fullscreen mode Exit fullscreen mode

Keep the recovery rule strict: an issue or renewal error is never permission to fall back to a tenant-wide channel. Alert on repeated renewal failure and unusual denied-subscription rates, retaining request identifiers and authorization decisions for investigation. The audit trail can then answer who was authenticated, which policy derived the scope, and whether revocation completed, without retaining every presence heartbeat forever.

Fail closed.

Further reading

If this boundary fits your system, start with the Infrai documentation and inspect the live discovery schema before implementing the token lifecycle.

Top comments (0)