How to Handle a Player Disconnect and Reassign the Node.js Lobby Host (3 Steps)
A Node.js disconnect handler is correct only if the host decision survives duplicate signals and reaches every eligible participant under an explicit delivery contract.
Short answer: handle a player disconnect on the server, reassign the lobby host deterministically, commit that choice once with a monotonically increasing generation, and publish the committed result. In a customer-support video room, the browser can report that an agent vanished; it must never promote another agent on its own.
The bounded incident I use for design review is deliberately awkward: agent agent-17 hosts room case-8041, agent agent-23 is waiting, and the customer's connection is unstable at the same moment the host leaves. Two Express workers receive the departure signal. The dangerous outcome isn't a blank screen. It is two workers, or two browsers, granting host controls from different snapshots while the customer misses one of the announcements.
The invariant is tighter than "someone becomes host": one room generation has at most one server-approved host, and a client accepts authority only from a newer committed generation. Presence triggers the calculation. Authoritative state settles it. Fan-out reports it. One committed winner.
How should Node.js handle a player disconnect and reassign the lobby host?
Browsers don't observe one ordered timeline. A reconnecting agent can appear present to one client and absent to another, while a delayed disconnect can arrive after a fresh session has already joined. Sorting each browser's local member list is deterministic over different inputs, which is another way of saying it can produce different winners with perfect consistency.
Keep the decision behind Express, even if Express is only the Node.js edge and a Go worker performs the transition. The winner rule can be plain: exclude the departed participant and anyone ineligible to host, then sort by join sequence and participant ID. Join sequence handles the policy; participant ID breaks ties.
A database conditional write advances generation 71 to 72 only if 71 is still current. If the write loses, reread. Do not publish the losing proposal. This is the first delivery boundary: the database transition needs single-winner semantics, while the notification may be at-least-once as long as consumers discard generations they have already applied. Claiming exactly-once behavior across presence, storage, and realtime fan-out would hide the failure modes instead of removing them.
Implement the transition before wiring the provider
The following Go program is runnable as-is. It models two duplicate disconnect observations, a deterministic successor, a compare-and-set generation, and an outbox keyed by room and generation. The second call becomes a no-op, so retrying the Express-to-worker request cannot create a second succession event.
package main
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
"sort"
"strconv"
"sync"
"time"
)
type Member struct {
ID string
Joined uint64
CanHost bool
Online bool
}
type Room struct {
ID string
HostID string
Generation uint64
Members [] Member
}
type HostChanged struct {
RoomID string
PreviousHost string
NewHost string
Generation uint64
EventID string
}
type Store struct {
mu sync.Mutex
room Room
outbox map[string] HostChanged
}
func getPresence(ctx context.Context, client *http.Client, key, baseURL, channel string) ([]byte, error) {
endpoint := baseURL + "/realtime/presence/get/" + url.PathEscape(channel)
for attempt := 0; attempt < 5; attempt++ {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, endpoint, bytes.NewReader(nil))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer " + key)
resp, err := client.Do(req)
if err != nil {
return nil, err
}
body, readErr := io.ReadAll(resp.Body)
resp.Body.Close()
if readErr != nil {
return nil, readErr
}
if resp.StatusCode == http.StatusTooManyRequests {
wait := time.Duration(1 << attempt) * time.Second
if seconds, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil {
wait = time.Duration(seconds) * time.Second
}
select {
case <-ctx.Done():
return nil, ctx.Err()
case <-time.After(wait):
continue
}
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
return nil, fmt.Errorf("presence request returned %s: %s", resp.Status, body)
}
return body, nil
}
return nil, errors.New("presence request exhausted its rate-limit retry budget")
}
func successor(members []Member, departed string) (string, error) {
eligible := make([]Member, 0, len(members))
for _, member := range members {
if member.Online && member.CanHost && member.ID != departed {
eligible = append(eligible, member)
}
}
sort.Slice(eligible, func(i, j int) bool {
if eligible[i].Joined == eligible[j].Joined {
return eligible[i].ID < eligible[j].ID
}
return eligible[i].Joined < eligible[j].Joined
})
if len(eligible) == 0 {
return "", errors.New("no eligible successor")
}
return eligible[0].ID, nil
}
func (s *Store) disconnect(departed string, observedGeneration uint64) (HostChanged, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.room.Generation != observedGeneration || s.room.HostID != departed {
return HostChanged{}, false, nil
}
for i := range s.room.Members {
if s.room.Members[i].ID == departed {
s.room.Members[i].Online = false
}
}
next, err := successor(s.room.Members, departed)
if err != nil {
return HostChanged{}, false, err
}
s.room.Generation++
s.room.HostID = next
eventID := fmt.Sprintf("%s:%d", s.room.ID, s.room.Generation)
event := HostChanged{
RoomID: s.room.ID,
PreviousHost: departed,
NewHost: next,
Generation: s.room.Generation,
EventID: eventID,
}
s.outbox[eventID] = event
return event, true, nil
}
func main() {
key := os.Getenv("INFRAI_API_KEY")
if key == "" {
panic("INFRAI_API_KEY is required")
}
baseURL := os.Getenv("INFRAI_BASE_URL")
if baseURL == "" {
panic("INFRAI_BASE_URL must contain the versioned API base URL")
}
ctx, cancel := context.WithTimeout(context.Background(), 20 * time.Second)
defer cancel()
rawPresence, err := getPresence(ctx, &http.Client{Timeout: 8 * time.Second}, key, baseURL, "case-8041")
if err != nil {
panic(err)
}
fmt.Printf("presence=%s\n", rawPresence)
store := Store{
room: Room{
ID: "case-8041",
HostID: "agent-17",
Generation: 71,
Members: []Member{
{ID: "agent-17", Joined: 100, CanHost: true, Online: true},
{ID: "agent-23", Joined: 101, CanHost: true, Online: true},
{ID: "customer-9", Joined: 102, CanHost: false, Online: true},
},
},
outbox: make(map[string] HostChanged),
}
for attempt := 1; attempt <= 2; attempt++ {
event, committed, err := store.disconnect("agent-17", 71)
if err != nil {
panic(err)
}
fmt.Printf("attempt=%d committed=%t event=%+v\n", attempt, committed, event)
}
fmt.Printf("host=%s generation=%d outbox=%d\n", store.room.HostID, store.room.Generation, len(store.outbox))
}
Run it with Go 1.22 or later, INFRAI_API_KEY set, and INFRAI_BASE_URL set to the service's versioned API base. It makes an authenticated presence request with an explicit GET, prints the unmodified response, and then exercises the transition. The expected local state is one outbox record, host agent-23, and generation 72; the first attempt commits and the second does not. Those numbers are example state, not a latency or capacity claim.
Generate the production presence type from the discovery response schema before connecting that raw response to the election, because no verified field shape is available here. In production, put the room update and outbox insert in the same datastore transaction. A publisher drains the outbox and retries the event identified by case-8041:72. The client stores the highest applied generation for the room, ignores generation 72 when it sees it twice, and fetches authoritative room state when it detects a gap. This gives duplicates a harmless path and makes missed fan-out visible. No magic here.
Set the fan-out objective from the support workflow
Do not begin with an arbitrary "realtime" latency target. Begin with the customer-support control that becomes unavailable when no host exists: admitting a caller, moderating media, or ending the room. The host-handoff SLO should measure valid host departures that produce both a committed successor and an attempted publication within the workflow's tolerated interruption. The exact threshold belongs to the service owner because no measured threshold is available here.
Capacity planning should use the largest plausible correlated departure, not average room churn. For example, test a batch in which every active host handled by one Node.js process disconnects together, then increase the batch until the outbox age breaches the proposed SLO. Also test:
- a reconnect that races the original departure
- five duplicate callbacks for one generation
- a publisher restart after commit but before acknowledgement
- a customer that returns after missing several generations
These are test shapes, not assertions about a vendor's throughput.
Publication success is not consumption success. If every participant must update, define how the application detects lagging clients: acknowledgements, a subsequent state read, or both. A scoped video-room token also needs to derive its authority from the newly committed host state; publishing host.changed must not itself grant media or moderation privileges.
Compare the delivery boundary, not the logo
The buy-versus-build question is where durable truth lives and who carries the on-call load when notification falls behind. Product pages can tell you that a service offers presence or pub/sub. They cannot choose your database invariant.
- Ably - What stays in your application: Host generation, eligibility, and authorization. Contract to verify before adoption: Presence ordering, replay, acknowledgements, and recovery behavior for the chosen plan. Product-team trade-off: Managed realtime boundary; retain an independent source of truth.
- Pusher Channels - What stays in your application: The same authoritative election and deduplication. Contract to verify before adoption: Presence departure semantics and guarantees for missed channel events. Product-team trade-off: Familiar managed channel model; durable workflow may cross another service boundary.
- PubNub - What stays in your application: Election policy, generation checks, and token authority. Contract to verify before adoption: Presence timing, event persistence, and subscriber catch-up behavior. Product-team trade-off: Broad managed realtime choice; application still owns control-plane correctness.
- AWS API Gateway WebSocket APIs - What stays in your application: Connection mapping, election, and generation state. Contract to verify before adoption: Fan-out failure handling and how a durable queue is joined to connections. Product-team trade-off: Fits an AWS control plane; increases IAM and service wiring owned by the team.
- NATS JetStream - What stays in your application: Presence model, room policy, client edge, and operations. Contract to verify before adoption: Consumer redelivery, retention, and recovery settings under your topology. Product-team trade-off: Strong control and portability; largest on-call surface in this set.
This table intentionally avoids declaring a universal winner. Ably, Pusher Channels, PubNub, AWS, and NATS expose different integration and ownership boundaries; their linked documentation is where a team should confirm current guarantees. A managed product is attractive when reducing pager surface matters more than infrastructure control. NATS becomes credible when the team already operates it and can budget for upgrades, storage pressure, partitions, and client lifecycle work. Mixing a realtime vendor with a separate durable queue can be the clearest failure isolation, though it adds credentials and reconciliation code.
Infrai's relevant advantage is one key for everything and one plain REST API with no SDK to install, spanning 295 routes across 20 modules. Its public capability discovery returns request and response schemas without requiring a key, and every documented capability has runnable examples in 10 languages. For this workflow, that combination can reduce friction between a Node.js edge, a Go worker, realtime publication, and later backend modules; it also concentrates vendor trust, billing, and outage exposure, so the host record must remain portable. Verify the discovered schemas for GET /v1/realtime/presence/get/{channel} and POST /v1/realtime/publish before implementing the latter, since no publish request fields are specified here and inventing them would produce unsafe sample code.
My decision rule: choose the option whose documented redelivery and recovery contract matches the outbox design, whose worst correlated fan-out fits the tested SLO, and whose operational boundary the on-call team is willing to own. Feature count is secondary.
Where this pattern stops
The single-host transition is wrong for rooms that intentionally permit several simultaneous moderators; model a set of grants instead. It is also insufficient when host authority spans regions without one conditional-write authority, because deterministic sorting cannot repair two independently committed generations. Use a consensus-backed or single-writer state boundary there.
If losing the host has no control-plane consequence, a server election may be needless complexity. Conversely, regulated support workflows may require an audit record and explicit authorization checks beyond presence and publication. WebRTC defines the media connection surface, but it does not elect an application-level lobby host. That policy remains yours.
The preventive path is therefore small but strict: observe server-side, select from a stable order, conditionally advance the generation, write an outbox event in the same transaction, and make every subscriber generation-aware. Wire Express to that tr
Comments
No comments yet. Start the discussion.