TL;DR: make the server the authority for lobby presence, give each room a short lease and monotonically increasing epoch, and choose the next host from a deterministic snapshot after a player disconnect. Do not promote the client that happened to emit a browser close event. In a logistics video room, a stale dispatcher must not receive a scoped token just because a delayed presence message arrived late.
The useful boundary is simple: an Express handler in a Node.js service can authenticate the request and enqueue the state transition, while the room coordinator owns membership, leases, host assignment, and token scope. WebRTC carries media; it does not decide who is still present or who may act as the lobby host. That distinction is easy to lose at 3 a.m., when a dashboard shows a green room and the page that fired was actually a stale worker.
The handoff can wait.
Presence is a state machine.
How should a Node.js lobby handle a player disconnect and reassign authority?
A browser disconnect is evidence, not truth. A tab can disappear without a clean close, a mobile network can change while the process remains alive, and a delayed heartbeat can arrive after a newer membership update. WebRTC exposes connection state through RTCPeerConnection, including states such as connected, disconnected, and failed, but those observations describe a peer connection, not the business fact that a dispatcher is eligible to lead a room. The W3C specification is the right reference for that transport state; the application still needs its own presence policy.
For a logistics room, I would record a member as an explicit tuple: stable member ID, join sequence, last accepted heartbeat, lease expiry, role, and the epoch under which that role was granted. The join sequence is not a timestamp. It is a server-issued ordering value, because wall clocks are poor arbiters when two workers are making decisions.
The first trap is treating disconnect as a command to promote someone. It is only a request to evaluate the room. The coordinator must re-read the current membership snapshot, confirm that the disconnected player's lease has expired or that a server-side close has been accepted, and then calculate succession from the remaining eligible members. If a heartbeat renews the lease between those steps, the promotion is discarded.
I initially treated a browser close event as the useful signal. It was the wrong abstraction: the event says that one connection changed, not that the player lost authority. A lease check and a committed version are slower by a small amount, but they answer the operational question correctly.
Why is deterministic succession safer than fast succession?
Because two correct workers can observe the same room at different moments. Worker A may process a failed peer connection first; worker B may process a timeout first. If both independently pick a replacement and issue authority, the room can have two hosts, two epochs, and two plausible audit trails. The fast result is the wrong result.
Use a compare-and-swap style transition on the room record. The transition succeeds only when the stored epoch and the member version still equal the values used to calculate the decision. On success, increment the epoch, assign the first eligible member in the deterministic ordering, and invalidate authority associated with the previous epoch. A lease prevents a dead process from owning the role forever; an epoch prevents its delayed messages from becoming valid again.
Here is the decision core in Go. It is deliberately independent of a realtime vendor and can sit behind an Express handler or a queue consumer. The storage call must be atomic in the backing store; a mutex in one process is not enough once the service has more than one worker. The trade-off is real: a single durable coordinator is easier to reason about, while a multi-worker design improves throughput but makes version conflicts and retries part of the normal path.
package lobby
import (
"sort"
"time"
)
type Member struct {
ID string
JoinOrder uint64
LeaseUntil time.Time
CanLead bool
}
type Room struct {
Epoch uint64
Version uint64
HostID string
Members []Member
}
// Reassign evaluates a snapshot. The repository must compare Version and Epoch
// in one atomic update before storing the returned room.
func Reassign(snapshot Room, now time.Time, expectedVersion, expectedEpoch uint64) (Room, bool) {
if snapshot.Version != expectedVersion || snapshot.Epoch != expectedEpoch {
return Room{}, false
}
candidates := make([]Member, 0, len(snapshot.Members))
for _, member := range snapshot.Members {
if member.CanLead && member.LeaseUntil.After(now) {
candidates = append(candidates, member)
}
}
sort.Slice(candidates, func(i, j int) bool {
if candidates[i].JoinOrder == candidates[j].JoinOrder {
return candidates[i].ID < candidates[j].ID
}
return candidates[i].JoinOrder < candidates[j].JoinOrder
})
updated := snapshot
updated.Epoch++
updated.Version++
updated.HostID = ""
if len(candidates) > 0 {
updated.HostID = candidates[0].ID
}
return updated, true
}
The empty-host case matters. A room with no eligible leader is a valid state and should cause a new join or an operator-visible condition, not a fabricated token for an expired member. That one branch is where many otherwise tidy handoff designs quietly reintroduce stale authority.
Do not optimize this branch away.
How should scoped room tokens follow the handoff?
Treat a token as a capability with a narrow subject and a room epoch. Its claims should identify the room, member, allowed role, expiration, and epoch. The token issuer checks the committed room record immediately before minting. It must reject a request whose member is absent, whose lease is expired, whose requested role is not granted, or whose epoch is stale.
This is also where the video-room setup belongs. A dispatcher can ask to create or join a room, but the server decides the room ID and membership scope. The client does not send a proposed host ID and receive a token by reflection. When the host changes, the next token uses the new epoch; existing tokens are accepted only according to the explicit grace policy, preferably one that cannot grant host-only actions after the transition.
Do not put succession in the browser. A client can render the current host quickly, but it cannot authorize the next host. The UI is a projection of the committed room state, and the projection may briefly lag. Presence accuracy means the authority path is correct, not that every screen changes in the same millisecond. This approach is a poor fit for a room that tolerates split-brain leadership and has no scoped actions; it adds coordination and durable state that such a room does not need.
What should the runbook verify before rollback?
Start with the page that fired. Check the room ID, member ID, observed epoch, committed epoch, lease deadline, and the worker that accepted the transition. A generic “peer disconnected” metric is not enough to tell whether the room lost its leader, whether a handoff committed, or whether a late event was correctly rejected.
The verification sequence is intentionally boring: inspect the committed room snapshot, confirm there is at most one host for the current epoch, confirm the replacement's lease is still valid, and mint a test-scoped token only through the normal authorization path. Then check that a message carrying the prior epoch cannot change host state. This tests the boundary that matters.
For deployment, make the coordinator transition idempotent. Retrying the same disconnect event should either observe the already committed epoch or fail its version check; it must not increment the epoch twice. Rollback should preserve the room record and epoch semantics across application versions. Rolling back code while restoring an older snapshot can make an old worker's messages look current, so the data contract needs a migration or a forward-compatible reader before traffic moves.
A small test matrix catches more than a happy-path browser test: clean close, silent lease expiry, delayed heartbeat, duplicate disconnect, simultaneous worker decisions, replacement joining during evaluation, and no eligible replacement. Include a clock-skew test by passing now into the decision function, as in the example, instead of hiding time inside it. That makes the dangerous boundary reproducible.
The operational rule is the same one I use for any alert that claims a service is healthy: ask what page fired, then ask what state was committed. For a logistics video room, a deterministic lease-and-epoch transition gives that question a useful answer.
References
- W3C, WebRTC 1.0: Real-Time Communication Between Browsers: https://www.w3.org/TR/webrtc/
- RFC 8445, Interactive Connectivity Establishment (ICE): A Protocol for Network Address Translator (NAT) Traversal: https://www.rfc-editor.org/rfc/rfc8445
- RFC 7519, JSON Web Token (JWT): https://www.rfc-editor.org/rfc/rfc7519
Top comments (1)
Separating transport connection state from business presence is the key line: an RTCPeerConnection that reports disconnected or failed says nothing by itself about whether that member is still eligible, and acting on that signal directly is what promotes a stale worker. The server-issued join sequence instead of a timestamp matters for the same reason; two members cannot be ordered by wall clock when heartbeats arrive out of order. This generalizes to multi-window desktop apps too: when a renderer closes unexpectedly, the main process should decide authority from its own membership snapshot and lease epoch, not trust the order in which close events happen to arrive.