Fix ghost participants accumulating in sessions#904
Conversation
When the backend restarts (HMR, deployment, crash), WebSocket connections drop but Redis session membership sets are never cleaned up. Each browser reconnect adds a new connection ID while old ones persist, causing inflated participant counts. This commit: - Adds a Lua script to atomically prune stale session members and re-elect leaders when needed - Adds dead instance discovery via heartbeat checking and batch cleanup of orphaned connections on startup and every 2 minutes - Fixes getSessionMemberCount/hasSessionMembers to filter out stale entries by checking connection hash existence - Adds TTL (2h) to instance connection sets for self-healing - Replaces per-connection board_session_clients rows with a per-user board_session_participants table (one row per authenticated user per session, permanent historical record) - Removes persistSessionLeave and persistLeaderChange Postgres writes (leader state is Redis-only) - Updates mySessions query to use distributed state for participant counts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Claude Review✅ Ready to merge - Minor issues noted below, but nothing blocking. Test Coverage
Documentation
Minor Notes
|
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 4f9f0c9769
ℹ️ About Codex in GitHub
Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you
- Open a pull request for review
- Mark a draft as ready
- Comment "@codex review".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
…cycle Instead of adding another setInterval in server.ts, piggyback the cleanup on the existing 30s heartbeat in DistributedStateManager. Runs every 4th heartbeat (~2 minutes), keeping the cleanup logic co-located with the state it manages. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Claude Review✅ Ready to merge - Minor issues noted below, but nothing blocking. Documentation
Test Coverage
Code ReviewThe implementation looks solid. The Lua scripts are well-designed for atomic operations, the periodic cleanup piggybacks efficiently on heartbeats, and the self-healing TTLs provide good defense-in-depth. |
- Pass authenticatedUserId to registerClient in WebSocket onConnect so client.userId is populated and persistSessionJoin actually inserts into board_session_participants for authenticated users - Refresh instance connection-set TTL on every heartbeat (not just at registration) so long-lived instances remain discoverable after a crash - Add tests for discoverDeadInstances, cleanupDeadInstanceConnections, cleanupStaleSessionMembers, and getSessionMemberCount stale filtering - Update websocket-implementation.md: document active dead instance cleanup, board_session_participants table, TTL annotations, and participant tracking architecture Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Claude Review✅ Ready to merge - Well-designed solution for ghost participant cleanup with comprehensive tests and updated documentation. No significant issues found. The implementation correctly:
|
Replace the unique index on (session_id, user_id) with a proper composite primary key for consistency with other tables. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Summary
boardsesh:session:SESSION_ID:members) are never cleaned up. Each browser reconnect adds a new connection ID while old ones persist, causing inflated participant counts (e.g., 28 members from 4 dead instances when only 2 browsers are connected).board_session_clientswithboard_session_participants: One row per authenticated user per session (permanent historical record) instead of per-connection rows that accumulate as ghosts. Leader state stays Redis-only.Changes
Part A: Redis Ghost Cleanup (
distributed-state.ts)PRUNE_STALE_SESSION_MEMBERS_SCRIPTLua script for atomic stale member removal + leader re-electiondiscoverDeadInstances(),cleanupDeadInstanceConnections(),cleanupStaleSessionMembers()methodsgetSessionMemberCount()to filter stale entries via pipeline EXISTS checks (was using raw SCARD)hasSessionMembers()to delegate to corrected count methodstart()Part B: Replace
board_session_clients(room-manager.ts, schema)board_session_participantstable with UNIQUE(session_id, user_id) — only for authenticated userspersistSessionJoin()to upsert into new table instead ofboard_session_clientspersistSessionLeave()(participants are permanent records)persistLeaderChange()(leader state is Redis-only)updateUsername()mySessionsquery to usedistributedState.getSessionMemberCount()board_session_clientstable is no longer written to (can be dropped in follow-up)Part C: Periodic Cleanup (
server.ts)Test plan
npm run typecheck:backendandnpm run typecheck:dbpassSCARD boardsesh:session:SESSION_ID:membersequals actual countboard_session_participantshas one row per authenticated userboard_session_clientsis no longer written to🤖 Generated with Claude Code