Reconcile real-time updates and conflicts
Reconcile confirmed records by revision
A real-time stream reports changes made elsewhere. WebSocket is bidirectional; server-sent events (SSE) carry server-to-client events over HTTP, while writes use a separate request. Neither gives the application exactly-once processing by itself. A reconnect may require replay from a cursor or a fresh snapshot. Define a protocol before connecting the UI: this fictional repair board has one record, normalized by ID, and a global contiguous integer revision for the subscribed dataset. Real APIs may use opaque cursors, per-entity versions or filtered streams instead.
export const initialBoard = {revision: 0, byId: {r1: {id: 'r1', title: 'Lamp', done: false}}, stale: false};export function applyEvent(state, event) { if (!Number.isSafeInteger(event.revision) || event.revision < 1 || event.id !== 'r1' || typeof event.done !== 'boolean') { throw new TypeError('Invalid event'); } if (state.stale || event.revision <= state.revision) return state; if (event.revision !== state.revision + 1) return {...state, stale: true}; return {...state, revision: event.revision, byId: {...state.byId, [event.id]: {...state.byId[event.id], done: event.done}}};}export function saveIfCurrent(state, edit) { if (edit.id !== 'r1' || typeof edit.done !== 'boolean' || !Number.isSafeInteger(edit.baseRevision)) throw new TypeError('Invalid edit'); if (state.stale || edit.baseRevision !== state.revision) return {status: 'conflict', state}; return {status: 'saved', state: applyEvent(state, {id: edit.id, done: edit.done, revision: state.revision + 1})};}An event at revision 1 updates the lamp and advances the cursor. A repeated revision 1 is ignored; revision 3 arriving when revision 1 is current marks the snapshot stale. Later events are ignored until an authoritative replacement is obtained. This does not claim that all protocols deliver events in this order; the contiguous revision rule is part of this fixture. Validation covers the single known record and boolean field, not arbitrary schemas. Normalized records reduce duplicated entity data; arrays of IDs can define independent views.
Use a base revision to detect conflicting edits
import React, {useState} from 'react';import {initialBoard, applyEvent, saveIfCurrent} from './board.mjs';export default function ConflictDemo() { const [board, setBoard] = useState(initialBoard); const [draft, setDraft] = useState<{id: string; done: boolean; baseRevision: number} | null>(null); const [message, setMessage] = useState('No draft'); return <section><h2>Lamp repair</h2><p>Confirmed: {board.byId.r1.done ? 'Done' : 'Open'} (revision {board.revision})</p> <button onClick={() => {setDraft({id: 'r1', done: !board.byId.r1.done, baseRevision: board.revision}); setMessage('Local draft created');}}>Draft opposite status</button> <button onClick={() => setBoard(b => applyEvent(b, {id: 'r1', done: !b.byId.r1.done, revision: b.revision + 1}))}>Simulate remote edit</button> {draft && <p>Draft: {draft.done ? 'Done' : 'Open'} (base {draft.baseRevision})</p>} <button disabled={!draft} onClick={() => { if (!draft) return; const result = saveIfCurrent(board, draft); setMessage(result.status === 'saved' ? 'Saved in simulation' : 'Conflict: review confirmed value and create a new draft'); if (result.status === 'saved') {setBoard(result.state); setDraft(null);} }}>Save draft</button> <button disabled={!draft} onClick={() => {setDraft(null); setMessage('Draft discarded');}}>Discard draft</button> <p role="status">{message}</p></section>;}Create a draft at revision 0, simulate a remote edit, then save. The draft stays visible and the confirmed revision remains 1. In production the revision check and mutation must be atomic on the server and authorized independently. HTTP conditional writes may use a strong ETag and If-Match, with a failed precondition represented by 412. A conflict is not automatically a transient failure: present both values and allow a deliberate rebase or discard. Even an optimistic UI needs a confirmed base, a pending overlay and reconciliation. Avoid restoring an entire stale snapshot over a newer edit.
Keep undo scoped to unsent changes
export function edit(history, value) { if (history.present === value) return history; return {past: [...history.past, history.present].slice(-10), present: value, future: []};}export function undo(history) { if (!history.past.length) return history; return {past: history.past.slice(0, -1), present: history.past.at(-1), future: [history.present, ...history.future]};}export function redo(history) { if (!history.future.length) return history; return {past: [...history.past, history.present].slice(-10), present: history.future[0], future: history.future.slice(1)};}The history contains only local string drafts; a new edit clears redo. Undo of a confirmed server change instead requires a new authorized compensating command based on the latest revision. Do not silently roll back somebody else’s edit. useReducer is sufficient for local workflows; Redux or Zustand may own shared client workflows; a query cache owns remote snapshots, while a state-machine library can represent complex parallel flows. Do not keep multiple independent authoritative copies. Practice: deliver revision 2 before revision 1 and explain why a fresh snapshot is required.