Short answer: treat channel deletion as a recorded state transition, not as a socket operation, and make every reconnect replay the same ordered event log. That decision keeps a multiplayer quiz game correct when a host closes a room while answers, timers, and reconnect requests are still in flight.
I build payment and ledger backends, so I am suspicious of the phrase “delete the room.” Deletion sounds like one write, but it actually crosses the room registry, presence state, answer submissions, timer workers, and the audit trail. A player can receive a final question after the host has ended the game; a reconnect can arrive after the delete request but before its broadcast; a retry can execute the same command twice. The failure is not cosmetic. It can change a score.
The invariant is a state transition, not a vanished row
Give each quiz channel a monotonic version and an explicit lifecycle: open, closing, closed. A delete request first appends ChannelClosing with an idempotency key, then rejects new writes whose observed version is older than the closing version. A separate transition appends ChannelClosed after the server has stopped accepting answers and timer jobs. The registry may eventually remove the room, but the event record remains long enough for reconciliation and support evidence.
The exact-once mindset matters here. Network delivery is at-least-once, and a WebRTC data channel can close while a message is buffered; the W3C recommendation describes connection and data-channel state, but it does not turn application messages into a transaction. Your application must attach ordering and replay semantics above the transport.
The boundary should be visible in one decision record:
Versions are cheap.
| Choice | Useful property | Failure it leaves you to handle | Fit for a quiz room |
|---|---|---|---|
| Hard delete plus broadcast | Small initial implementation | Lost terminal event, late writes, no audit evidence | Poor default |
| Tombstone with ordered log | Reconnect can backfill a final state; retries are deduplicated | Requires retention and compaction policy | Recommended |
| Per-room in-memory state only | Low latency in one process | Process loss erases truth; horizontal scaling races | Only for disposable prototypes |
| Database transaction plus outbox | Atomic state and durable publication | Outbox worker can lag and needs monitoring | Strong foundation |
There is a catch: a tombstone is not suitable when rooms contain regulated data that must be erased immediately. In that case, keep a minimal hashed audit receipt, apply the applicable retention rule, and make the deletion boundary explicit to compliance reviewers. The receipt should prove that a close command was accepted without preserving answer text, player identifiers, or network metadata beyond the approved window; otherwise an apparently careful audit trail becomes a second copy of the data that the erasure request was meant to remove. For a casual lobby with no durable score, an in-memory room can be a reasonable choice; stick with the simpler model when recovery has no user-visible consequence.
How should a multiplayer quiz game handle realtime channel deletion safely?
Start with a command whose result is stable under retries. The client sends a channel identifier, the last event version it has seen, and an idempotency key. The service locks the channel record, checks that the key has either been completed or is new, writes the lifecycle event and an outbox row in one transaction, and returns the resulting version. A second request with the same key returns that recorded result rather than creating another close event.
Here is the critical path in Go. The repository and outbox interfaces are intentionally generic; the important part is the transaction boundary and the version check.
package quiz
import "context"
type Channel struct {
ID string
Version int64
State string
}
type CloseCommand struct {
ChannelID string
Expected int64
IdempotencyKey string
}
type CloseResult struct {
Version int64
State string
}
type Store interface {
WithTx(ctx context.Context, fn func(Tx) error) error
}
type Tx interface {
LockChannel(ctx context.Context, id string) (Channel, error)
FindIdempotent(ctx context.Context, key string) (*CloseResult, error)
AppendEvent(ctx context.Context, id, kind, key string, version int64) error
SaveIdempotent(ctx context.Context, key string, result CloseResult) error
EnqueueOutbox(ctx context.Context, id string, version int64) error
}
func CloseChannel(ctx context.Context, store Store, cmd CloseCommand) (CloseResult, error) {
var result CloseResult
err := store.WithTx(ctx, func(tx Tx) error {
if prior, err := tx.FindIdempotent(ctx, cmd.IdempotencyKey); err != nil {
return err
} else if prior != nil {
result = *prior
return nil
}
ch, err := tx.LockChannel(ctx, cmd.ChannelID)
if err != nil {
return err
}
if ch.Version != cmd.Expected {
return ErrStaleVersion
}
if ch.State == "closed" || ch.State == "closing" {
result = CloseResult{Version: ch.Version, State: ch.State}
return tx.SaveIdempotent(ctx, cmd.IdempotencyKey, result)
}
result = CloseResult{Version: ch.Version + 1, State: "closing"}
if err := tx.AppendEvent(ctx, cmd.ChannelID, "ChannelClosing", cmd.IdempotencyKey, result.Version); err != nil {
return err
}
if err := tx.SaveIdempotent(ctx, cmd.IdempotencyKey, result); err != nil {
return err
}
return tx.EnqueueOutbox(ctx, cmd.ChannelID, result.Version)
})
return result, err
}
The outbox publisher sends ChannelClosing and later ChannelClosed to the realtime fan-out. It may send either event more than once. Consumers therefore store the last applied version and ignore an event that is not newer. That small rule prevents a delayed “question 7” update from resurrecting a room that is already closed.
I once started with a delete endpoint that returned success after removing the registry row. The first reconnect exposed the flaw: the client had no cursor and the server had no terminal evidence, so both sides guessed. The fix was not a longer timeout. It was a cursor-bearing snapshot plus an append-only transition. The timeout remained useful for user experience, but it stopped carrying correctness.
Reconnect and backfill are one protocol
On reconnect, a client presents its last applied version. The server responds with either the missing events or a snapshot followed by events after the snapshot version. If the cursor is older than the retention window, return a fresh snapshot with ChannelClosed when appropriate; do not silently claim that the client is current.
Presence should be derived from leases, not from the deletion event. A lease expiry removes a player from the active roster, while channel closure freezes the score and records why later answer submissions were rejected. These are different facts and deserve different event types. Audit records should include channel ID, actor, command key, prior version, resulting version, and a server timestamp; avoid putting answer text or personal data into a broadcast payload.
Three operational checks catch most production mistakes:
- Generate a property test that submits close twice, concurrently, and after a reconnect; the ledger must contain one logical transition.
- Inject publication delays and duplicate deliveries; every consumer must converge to the highest version.
- Reconcile the room registry against the event store, then alert when a closing room has no closed transition within the policy window.
Keep metrics by lifecycle transition, not only by HTTP status. Track stale-version rejections, outbox age, backfill length, and the count of answer commands rejected after ChannelClosing. A 200 response can still be a protocol failure if the corresponding event never becomes observable.
The rejected shortcut and its valid boundary
The tempting shortcut is to use a single broadcast such as room_deleted and let clients clear local state. It is acceptable for a transient spectator overlay where no score, timer, or audit record matters. It is unsafe for a scored quiz because broadcasts have no durable cursor, can arrive out of order, and cannot explain a disputed result weeks later.
Do not turn the event log into an infinite archive. Define a retention period, snapshot cadence, and erasure procedure before launch. Your mileage may vary with jurisdiction and game policy; I am not sure a single retention value can satisfy every deployment, which is precisely why the policy belongs in configuration and review rather than in a magic constant.
The selection rule is straightforward: use a durable tombstone, idempotent commands, and cursor-based backfill whenever a reconnect can affect correctness. Use ephemeral state only when losing the room is an acceptable outcome. That is a systems boundary, not a vendor preference.
Top comments (0)