Skip to content

Realtime sync: implement leader-election for DB saves #86

@th3fallen

Description

@th3fallen

Context

From PR #85 review — currently all connected clients independently auto-save the game to the database on a 60s debounce. With multiple users connected, this means redundant writes to Supabase.

Proposal

Implement a leader-election mechanism using Supabase's Realtime Presence API so that only the first/oldest connected client is responsible for saving to the database. This models the peer-to-peer connection as a coordinated primary/secondary election.

Considerations

  • Use Supabase Presence to track connected peers and determine the "leader" (e.g., lowest SENDER_ID or first to join)
  • Only the leader triggers saveRemoteGame on the auto-save debounce
  • If the leader disconnects, a new leader is elected and takes over save responsibility
  • Non-leader clients still broadcast patches via realtime — they just don't write to the DB
  • Edge case: if the leader crashes without a clean disconnect, presence should eventually time out and trigger re-election

Related

  • PR Add realtime sync #85 — realtime sync implementation
  • src/games/sync/useRealtimeGameSync.tsscheduleAutoSave() function

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions