A collaborative app loses its connection. One person keeps typing; someone else, somewhere else, keeps editing the same document. Thirty seconds later the first machine comes back online. What should happen?
"Sync the changes" is the obvious answer, but it hides most of the hard parts. Does reconnecting mean the WebSocket reopened, or that WebRTC found a working route? Has every local change reached the other side and every remote change arrived here? Are the documents just connected, or actually the same again? Should an old cursor reappear? What if the user refreshed while offline, the original peer-to-peer route is gone, or two people changed the same thing during the outage? And at what exact point is it honest for the interface to say "Synced"?
These questions became concrete for me while building FeatherSpace, a local-first collaborative coding workspace using Yjs CRDTs, WebRTC, WebSocket signaling, TURN, browser persistence and offline-to-online recovery. Getting two browsers to edit the same state while both are online is the easy part. Reconnection is where the design shows what it actually guarantees. The main thing I learned is that reconnecting the network and reconnecting the state are different things. A connection can be healthy while the data is stale, a document can be in sync while presence is wrong, and a user can keep editing safely with no network at all.
What local-first changes
Most web apps treat the server as the authoritative copy of the data:
If the server is unreachable, most things stop, because the client is waiting on the system that owns the data. A local-first app flips that around: you edit a copy on your own device first, and syncing happens afterwards.
So an outage no longer means "editing unavailable"; it means "editing continues, sharing is delayed". Ink & Switch's essay Local-first software describes this model: data stays usable on the device, and independently changed copies (replicas) sync and merge when connectivity returns. That changes the recovery problem. The goal isn't to regain access to where the document lives, because it's already here. The goal is to reconcile replicas that may have kept changing on their own.
Connected isn't synced
Suppose the browser reports peerConnection.connectionState === "connected". Can the app show "Synced"? Not yet. The network layer has established that the peers can talk; it hasn't established that their documents match. I find it helpful to think in layers:
A failure in one layer doesn't destroy the layers above it. Wi-Fi can drop while the local document is perfectly fine. WebRTC can reconnect while the CRDT is still exchanging missing updates. The document can be in sync while stale presence still claims a disconnected collaborator is editing line 42. So internally the app needs more than online and offline; something like offline, connecting, connected, synchronising, synced and degraded. The UI can collapse those into one green dot, but the app itself needs to know which one it's really in.
Merging, not replacing
Here's an offline edit. Alice and Bob start with const retries = 3;. Their connection drops. Alice changes the 3 to a 5; Bob adds const timeout = 5000;. There are now two legitimate replicas changing at the same time:
A snapshot-based design would compare Alice's document with Bob's and pick a winner. A CRDT (conflict-free replicated data type) works differently: the data is represented so that updates made independently can later be combined in a deterministic way. The key property is convergence: replicas that receive the same set of updates end up with the same document. That's much stronger than "reconnect and download the latest version", which assumes one copy is authoritative because it's newest. Local-first apps can't assume that, because valid work may exist on both sides.
That's why this reconnect handler is dangerous:
async function reconnect() {
const remoteDocument = await fetchDocument();
editor.setValue(remoteDocument);
}
It's fine when the server owns the document. In a local-first app, it can destroy offline work. If the shared state was A B C, the local copy became A B C D offline, and the remote copy became A B C E, replacing local with remote loses D, and uploading local as authoritative loses E. What you want is a merge that gives A B C D E (assuming the edits are compatible). Reconnection should trigger reconciliation, not a reset, and CRDT systems exchange the missing updates rather than overwriting whichever snapshot they reach first. It also means local storage isn't a disposable cache: some of it may be work that exists nowhere else.
How a Yjs app fits together
A simple local-first Yjs setup looks like this:
import * as Y from "yjs";
import { IndexeddbPersistence } from "y-indexeddb";
import { WebrtcProvider } from "y-webrtc";
const roomId = "workspace-123";
const doc = new Y.Doc();
const persistence = new IndexeddbPersistence(roomId, doc);
const network = new WebrtcProvider(roomId, doc);
The interesting detail is that neither persistence nor networking owns the document; the Y.Doc does. IndexedDB feeds updates into it, peers feed updates into it, and the editor changes it. All three meet at the same shared model. So losing one doesn't lose the document. IndexedDB keeps state while there's no peer, WebRTC later fills in missing changes without becoming the authority on what the document is, and the editor keeps producing updates whether or not the network is healthy. There's no separate "offline document" and "online document" to reconcile.
Reconnection is a sequence of steps
A tempting implementation listens for the browser's online event and reconnects. That's a useful signal, but far from enough. The browser thinking the internet is back doesn't prove the signaling service is reachable, another peer is around, WebRTC negotiation succeeded, the CRDT finished exchanging state, or access is still valid. Recovery is really a pipeline:
Each step answers a different question. Network available means connectivity might exist. Signaling connected means the app can reach the service used to find and negotiate with peers. Transport connected means there's a working path. Synchronising means the CRDT is exchanging missing updates. Synced means the protocol has enough evidence to say it's finished. Only after that should presence be rebuilt for the new session.
Yjs's y-websocket provider makes this distinction too, with separate signals for the socket's connection status and for the document having synced. The exact API matters less than the idea: "connected" means communication is possible, while "synced" means the replication protocol believes the needed state has been exchanged. The UI shouldn't promise the second because it has evidence of the first.
type CollaborationState =
| "offline"
| "connecting"
| "connected"
| "synchronizing"
| "synced";
transport.on("connected", () => {
setStatus("connected");
});
provider.on("sync", (isSynced) => {
setStatus(isSynced ? "synced" : "synchronizing");
});
WebRTC adds another moving part. Peer-to-peer is usually drawn as two browsers with a line between them, but the real path looks more like this:
As MDN's introduction to WebRTC protocols explains, ICE looks for a workable path between peers, STUN helps each side discover its public address, and when NATs or firewalls block a direct connection, TURN relays the traffic. Yesterday's session might have used direct UDP and today's reconnect might go through a TURN relay. The document shouldn't care. The transport is plumbing; what matters is that missing updates eventually get exchanged. Keeping the two separate also means you can change transports later without changing what the document means.
Document state and presence
Collaborative apps carry two very different kinds of shared state. Durable state belongs to the document: code, text, board nodes, settings, files. Ephemeral state describes what someone is doing right now: cursor position, selection, active file, online status, colour, "is typing". They need different recovery rules. If Alice is gone for 45 minutes, her edits must survive; her cursor from 45 minutes ago shouldn't come back.
Yjs keeps presence separate from document data through its awareness feature, which also handles clients disappearing:
On reconnect, document state is merged and kept; presence is refreshed or rebuilt. Persisting presence as if it were durable leads to odd behaviour, like a collaborator who left yesterday still appearing on a particular line. That distinction belongs in the architecture rather than in UI cleanup code.
When convergence isn't enough
CRDTs solve a very hard class of problems, but not every product decision. Suppose Alice deletes a code block while Bob, offline, edits that same block. The CRDT will converge deterministically, but the product still has to decide what that means. Should Bob's edit bring the block back? Should the deletion win? Should Bob's text be kept somewhere, and should he be told?
Figma's post on how their multiplayer technology works shows the same gap with undo. Undo is clear for one person, but if others have edited the same objects since, what should undoing do, and what about redo? They settled on a guiding rule: if you undo a lot, copy something and redo back to the present, the document shouldn't change. Convergence means the replicas agree. It doesn't automatically mean the users agree with the result; the application still has to define that.
Starting up offline
Not every outage happens while the app is open. A user edits, the changes are saved locally, the laptop closes, and later the app is opened with no internet. Now startup is part of the correctness story. This is risky:
const doc = createEmptyDocument();
render(doc);
// Later...
const persisted = await loadFromIndexedDB();
replaceDocument(persisted);
The app briefly shows an empty document before local data loads, and depending on what else happens, that empty state might even trigger writes that compete with the saved work. It's safer to treat loading local data as part of being ready:
Yjs's guide to offline editing shows the IndexedDB provider emitting a synced event once local content has loaded. That small detail matters, because in a local-first app the local copy may be the only durable copy of recent work.
The infrastructure that's still there
Coming back online can also create a burst of work. After eight hours of offline editing, reconnecting means thousands of document updates, plus presence, peer discovery, signaling and transport negotiation. If many clients reconnect after the same outage, recovery traffic can far exceed normal collaboration traffic. It's the familiar backend pattern where everyone retries the moment an outage ends. Incremental sync, batching, compacting updates, adding jitter to reconnects, backpressure and large-document performance all matter here. Something that works beautifully with small, steady updates can behave very differently when hours of changes arrive at once, so reconnection is a load pattern, not just a UI state.
Peer-to-peer doesn't mean infrastructure-free either. You may still need signaling, authentication, authorization, peer discovery, TURN, session metadata, key exchange and monitoring. A pure mesh also has limits: three peers need three connections, but as a room grows, each participant connects to more peers and has to receive data from all of them. Cloudflare's post introducing their real-time communications platform describes both problems: reliable peer-to-peer connections are hard behind carrier-grade NATs, corporate NATs and firewalls, and in a mesh, participants' connections saturate quickly. Ink & Switch's PushPin paper also names NAT traversal reliability as an area that still needs work. P2P can be a great fit for a small coding room and a poor one for hundreds of participants, which is another reason to keep the document model separate from the transport: you might move from CRDT plus WebRTC to CRDT plus a WebSocket server, or a hybrid, without changing what the document means.
Access control matters after a partition too. Say a user is removed from a session while offline, then reconnects. Holding an old local copy shouldn't mean they can rejoin. Authorization still has to happen at the boundaries you control: signaling, TURN credentials, room discovery, server-side sync and key distribution. End-to-end encryption makes this more interesting, because a server can relay encrypted updates without reading them, but the app still needs rules for admitting new peers and handing out current keys after membership changes. There's also a limit local-first can't get around: revoking access stops future participation, but it can't erase a copy already stored on someone else's device.
Testing the transitions
The happy path says very little about whether reconnection is correct. These scenarios say much more:
| Scenario | Expected result |
|---|---|
| Peer disconnects while idle | Reconnects with no document change |
| Peer edits offline | Local edits survive |
| Both peers edit offline | Replicas converge after reconnect |
| Browser refreshes while offline | Local document reloads |
| Duplicate CRDT updates arrive | No duplicated content |
| Signaling reconnects slowly | Local editing stays usable |
| Direct WebRTC fails | TURN establishes connectivity |
| Peer reconnects with stale presence | Old awareness state disappears |
| Peer rejoins after a long absence | Missing document state syncs |
| Network repeatedly flaps | No lost edits or duplicated listeners |
| Two tabs open the same document | State stays consistent across tabs |
| Access revoked during partition | Reconnection policy is enforced |
That's much closer to the real surface of a collaborative system than opening two tabs and watching text appear in both. For FeatherSpace I added tests around joining, syncing, reconnecting, performance, memory and reliability, because the interesting failures happen during transitions rather than while the system sits in one state. Network conditions worth injecting include going offline, high latency, packet loss, short and long disconnects, rapid flapping, signaling failure and TURN-only connectivity. The question isn't "does it reconnect?" but "what still holds after it does?"
It also helps to measure recovery: reconnection attempts, time to transport recovery, time to sync, sync failures, how often TURN is used, peer counts, update volume and IndexedDB load time. Without that, the first sign of a broken sync system may be a user saying "my friend's code disappeared".
What correct reconnection means
The biggest shift for me was to stop drawing collaboration as two browsers with a line between them, and to see it as several cooperating parts:
The CRDT handles convergence. IndexedDB (or another local store) handles durability on the device. WebRTC or WebSockets carry updates. Signaling helps peers find each other, and STUN and TURN find a working path across real networks. Awareness represents what people are doing right now. The application decides what the shared state means to users. Once those jobs are separate, reconnection is much easier to reason about: instead of asking whether one big "collaboration system" is connected, you ask which guarantees each part currently provides and which are still being restored.
So correct reconnection isn't connectionState === "connected", navigator.onLine === true or a WebSocket opening. Those are useful evidence, but none of them is the definition. My working definition: after connectivity returns, local work survives; replicas exchange what they're missing and converge; repeated updates don't duplicate anything; presence is rebuilt rather than restored; access is checked again where it matters; and the app doesn't claim to be synced until it has evidence. That spans networking, storage, distributed systems, security and UX, which is why it deserves more thought than socket.on("connect", sync).
Key takeaways
- Network connection and state sync are separate. Track connecting, connected, synchronising and synced as different states, and only show "synced" when the protocol says so.
- On reconnect, merge replicas with a CRDT. Never replace local state with a remote snapshot, because local data may be the only copy of recent work.
- Load local persistence before rendering or connecting, so an empty document never competes with saved edits.
- Keep durable document state and ephemeral presence separate: merge the first, rebuild the second.
- Convergence isn't product correctness. Decide what concurrent deletes, edits and undo should mean for users.
- Plan for reconnect bursts, NAT and TURN, mesh limits and re-checking access, and test transitions like flapping networks and long partitions.
References
- Ink & Switch — Local-first software — the foundational essay on offline-capable replicas, CRDTs and data ownership.
- Ink & Switch — PushPin: Towards production-quality peer-to-peer collaboration — lessons from a real P2P app, including NAT traversal reliability.
- Figma — How Figma's multiplayer technology works — CRDT-inspired collaboration in production, including how they defined multiplayer undo.
- Yjs — Allowing offline editing — IndexedDB persistence and the
syncedevent for local content. - Yjs — y-websocket — separate signals for connection status and document sync.
- Yjs — Adding awareness — presence as ephemeral state, separate from the document.
- MDN — Introduction to WebRTC protocols — ICE, STUN, NAT and TURN.
- Cloudflare — Announcing our real-time communications platform — why P2P connectivity is hard behind NATs and why meshes saturate.
