skip to content

In a mobile live trivia-show app, how should the client resubscribe after a reconnect so it neither misses nor double-applies game events?

level: seniorimportance: must knowfreq 46%

answer

  1. a socket remembers nothing for you
  2. a number on every event
  3. resume after the last one applied
  4. too old means take a snapshot
  5. drop what you already have

basics

~20 s

Number every game event, keep the last sequence the client applied, and resubscribe with it so the server resends what came after. If that is too old, load a snapshot; drop events at or below the last applied number.

solid answer

~50 s

A socket carries no memory of what the client saw, so the server stamps each show event with an increasing sequence number and the client keeps `last_applied`. On reconnect it authenticates and subscribes with `after = last_applied`. The server either replays the events after that point from a bounded buffer, or answers that the cursor is too old; then the client loads a snapshot of the show (live question, deadline, score) that carries its own sequence and continues from there. Three client rules make it exact: drop any event at or below `last_applied`, apply the next one in order, and hold any event that skips ahead while it asks again for the gap. Subscribe before loading the snapshot so nothing falls between them. Replayed questions whose window has closed update history and score but are never shown as answerable.

code

pseudocode · 29 lines
pseudocode
on event(e):
    if e.seq <= last_applied:
        return                               # duplicate: replay overlap or a resend
    if e.seq > last_applied + 1:
        held.add(e)
        if not gap_request_in_flight:
            gap_request_in_flight = true
            request_events(after = last_applied)   # may answer 'too old'
        return
    apply(e)
    last_applied = e.seq
    drain_held()

on too_old():                                 # the server's buffer no longer holds the gap
    snap = load_snapshot(show_id)            # events keep arriving into held meanwhile
    replace_state(snap)
    last_applied = snap.seq
    held.remove_where(seq <= last_applied)
    drain_held()
    if not held.is_empty():
        request_events(after = last_applied)   # a gap after the snapshot: ask once more

function drain_held():
    while held.contains(last_applied + 1):
        next = held.take(last_applied + 1)
        apply(next)
        last_applied = next.seq
    if held.is_empty():
        gap_request_in_flight = false

go deeper

for a junior

Recall that every event carries a sequence number and the client resumes from the last one it applied, dropping anything it already has.

for a middle

Walk through the resubscribe: authenticate, subscribe after the cursor, replay or 'too old', then snapshot with its own sequence.

for a senior

Explain subscribe-before-snapshot, the gap rule with held events, and why a replayed closed question is history and never an open one.

for a principal

Decide which features justify server replay buffers and how long, versus snapshot-only recovery, and where each cursor must live.

## A socket remembers nothing for you When a phone reconnects its live socket, it gets a fresh connection with no history. Events the server sent while the old socket was dying are simply gone from the client's point of view, and events that were in flight may arrive twice: once late on the old socket and again in a replay. A server-sent events stream has resumption built in (the client waits the reconnection time, then sends the id of the last event it saw so the server can continue from there); a socket gives the application nothing of the kind. The app must carry its own **cursor**: a marker of how far through the stream it has got. Without one, the server cannot tell what to resend, and the client cannot tell a new event from a copy of one it already applied. ## The contract: a sequence number per show The server gives every event in a show's stream (question opened, tick, question closed, scores updated) a **sequence number** that increases by one. The client keeps one number: `last_applied`, the sequence of the last event it applied to its state. On reconnect: 1. **Authenticate** the new socket (refreshing the token first if it expired). 2. **Subscribe with the cursor**: `subscribe(show_id, after = last_applied)`. 3. **Receive either a replay or a 'too old' answer.** The server keeps only a bounded buffer of recent events; how it stores them is the server's design. If the cursor is inside the buffer, it resends everything after it and then continues live. 4. **If the cursor is too old**, the client loads a **snapshot** of the show: the live question, its deadline, the player's score and the round. The snapshot carries the sequence it reflects, and the client sets `last_applied` to that value. The order matters: the client subscribes first, buffers what arrives, then loads the snapshot and drops buffered events at or below the snapshot's sequence. Loading the snapshot first leaves a window in which an event can happen between the snapshot and the subscription and be lost. ## Three rules that make it exact - **Duplicate**: an event with `seq <= last_applied` is dropped. It is either the overlap between replay and the old socket, or a resend after an unacknowledged frame. - **Next**: an event with `seq == last_applied + 1` is applied, and `last_applied` moves forward. - **Gap**: an event with `seq > last_applied + 1` means something is missing. The client holds it, asks once for events after `last_applied` (or for a snapshot), and applies the held events in order when the gap is filled. | Arriving event | Client action | Why | |---|---|---| | `seq` 41, `last_applied` 42 | Drop | Already applied | | `seq` 43, `last_applied` 42 | Apply, cursor to 43 | Next in order | | `seq` 46, `last_applied` 43 | Hold, request after 43 | 44 and 45 are missing | | 'cursor too old' | Load snapshot, cursor to its sequence | Buffer no longer holds the gap | ## What the trivia game does with replayed events A replay can deliver 'question 7 opened' after question 7's window has already closed on the server. The client applies it to its state (question history, score, round count) but never shows it as answerable: the server's deadline decides, and the screen jumps to whatever question is live now. Because every event is applied at most once by sequence, a replayed 'score updated' cannot add points twice, which is exactly the bug a client without a cursor ships. The connection state stays visible ('Reconnecting...', then live) so the player knows why a question was skipped. ## Where the cursor lives For a live show, the cursor can live in memory: if the app is killed, the next launch loads a snapshot anyway. A feature whose missed events must survive a process restart would persist the cursor with the data it describes, written in the same transaction, so the two can never disagree. ## Common mistakes - Reconnecting without a cursor and hoping nothing happened. - Applying every event that arrives, so a replay doubles a score update. - Loading the snapshot before subscribing, leaving a gap between them. - Treating a replayed, already-closed question as still open for answers.

  • Why must the client subscribe before it loads the snapshot, not after?
    Between loading a snapshot and subscribing, the show keeps moving. An event created in that interval is in neither: the snapshot predates it and the subscription starts after it. Subscribing first and buffering means every event after the snapshot is either already buffered or arrives later, and anything at or below the snapshot's sequence is simply dropped.
  • How does a server-sent events stream differ from a socket when it resumes?
    Server-sent events define resumption: the client reconnects after a server-settable delay and sends the id of the last event it received, so the server can continue from there. A socket defines nothing of the kind; the application must carry its own sequence, send it when it resubscribes, and drop duplicates itself.

  • A new socket automatically receives the events the old one missed.
  • Applying every arriving event is safe because the server never resends.
  • Load the snapshot first, then subscribe; the order does not matter.
  • An event that skips ahead can be applied and the gap ignored.
  • A replayed question can still be answered because it arrived just now.