← Back to Blog⚙️ Engineering · 7 min read

How Real-Time Sync Works Under the Hood

A technical deep-dive into the CRDTs, Yjs, Firebase, and WebSocket stack that makes ShareCode's collaboration feel instant.

Ever wondered how two people can type in the same document without overwriting each other? Here is a detailed look at the technology behind ShareCode's collaboration engine.

⚠️The Problem: Concurrent Edits

When two users type at the same position at the same time, a naive system would either lose one edit or create a conflict. Traditional Operational Transformation (OT) solves this with a central server that sequences operations — but OT is complex, fragile, and difficult to scale.

ShareCode takes a different approach using CRDTs (Conflict-Free Replicated Data Types), which guarantee convergence without any central arbitration.

🧬CRDTs and Yjs

ShareCode uses Yjs, a high-performance CRDT library written in JavaScript. Every character you type is assigned a unique, sortable ID based on a logical clock. When two users type at the same position, Yjs deterministically resolves the order — no server round-trip needed.

The key insight: CRDTs are mathematically guaranteed to converge. As long as all edits eventually reach all participants, every copy will be identical — regardless of arrival order. This is called strong eventual consistency.

🔥Firebase as the Persistence Layer

Each code space is backed by a Firestore document. The Yjs state is periodically snapshotted and saved, so even if everyone disconnects, the document is fully recoverable. Firebase Auth ensures only the owner can lock or delete a document.

This architecture means ShareCode does not need a custom backend server for storage. Firebase handles persistence, authentication, and security — letting the team focus on the editing experience.

Low-Latency Propagation

Edits travel from your browser to other participants via WebSocket-style connections managed by Yjs providers. In most scenarios, the round-trip is under 100 milliseconds — fast enough to feel instant. The protocol is binary-encoded and highly compressed.

Yjs also supports offline editing. If a participant loses their connection, they continue typing locally. When the connection resumes, Yjs merges the offline edits automatically — no data loss, no conflicts.

👁️Cursor Awareness

Beyond text synchronization, ShareCode syncs cursor positions and selections across users. You can see exactly where your collaborator is editing, turning the shared editor into something closer to a Google Docs experience for code.

Cursor awareness is implemented through the Yjs awareness protocol, which piggybacks on the same connection. It adds negligible overhead but dramatically improves the experience.

Why This Architecture Works

The combination of CRDTs + Firebase gives ShareCode two important properties: resilience (offline edits merge without conflicts) and simplicity (no self-hosted infrastructure required). The entire system runs in the browser with Firebase as the only backend dependency.

This means ShareCode can scale to thousands of concurrent code spaces without complex server orchestration. The CRDT model ensures correctness at the mathematical level — not just the implementation level.

Operational Transformation vs. CRDTs: A Deeper Look

Google Docs uses Operational Transformation (OT), which was pioneered in the late 1980s and later refined by the Jupiter collaboration system at Xerox PARC. OT works by transforming each incoming operation against every concurrent operation so the final result is the same on every client. This requires a central server that defines a total order of operations, making it inherently centralized.

CRDTs, on the other hand, assign each operation a unique identifier using a combination of client IDs and logical clocks. Because these identifiers are globally unique and sortable, every client can independently determine the final document state without communicating with a server. This makes CRDTs ideal for peer-to-peer architectures, offline-first applications, and systems where low latency is critical.

The trade-off is memory: CRDTs store tombstones (markers for deleted characters) to maintain consistency. Yjs mitigates this with aggressive garbage collection — tombstones are periodically cleaned up when all clients have acknowledged the deletion. In practice, a typical ShareCode session uses only a few kilobytes of CRDT metadata, even after hours of editing.

WebSocket Connections and Signaling

ShareCode uses a lightweight signaling server built on Socket.io to establish connections between participants. When you open a code space, your browser connects to the signaling server and joins a room identified by the document's unique URL. The signaling server does not process or store document content — it simply relays binary-encoded Yjs updates between connected clients.

This design means the signaling server is stateless and horizontally scalable. If one server goes down, clients automatically reconnect and resync through Yjs's built-in state vector exchange. The state vector tells each client exactly which updates the other client has already seen, so only missing updates are transmitted — minimizing bandwidth usage.

The WebSocket protocol used by Socket.io supports binary frames, which Yjs leverages to send compact, Uint8Array-encoded updates. A typical keystroke generates an update of just 20–50 bytes, making the protocol extremely lightweight even on slow mobile connections.

Security and Access Control

Real-time collaboration introduces unique security challenges. ShareCode addresses these at multiple layers:

  • Authentication: Firebase Auth verifies user identity before granting access to any code space. Anonymous users can join shared spaces but cannot create or delete documents.
  • Authorization: Firestore security rules ensure that only the document owner can modify permissions, lock the code space, or delete it. Collaborators have write access to the document content but not to its metadata.
  • Transport encryption: All WebSocket connections use TLS (wss://), and Firestore connections are encrypted by default. Document content is never transmitted in plaintext.
  • Input validation: Yjs validates the structure of every incoming update at the CRDT level. Malformed updates are rejected before they can corrupt the document state.

This layered approach ensures that even if a malicious client attempts to send corrupted data, the CRDT layer will reject it, and Firestore rules will prevent unauthorized metadata changes.

Performance Optimizations

Keeping collaborative editing smooth at scale requires several optimizations beyond the base CRDT protocol:

  • Update batching: Instead of sending one WebSocket message per keystroke, Yjs batches updates within a short window (typically 50–100ms). This reduces the total number of network round-trips by 10–20x during fast typing sessions.
  • Lazy loading: When you open a code space, Yjs does not replay the entire edit history. Instead, it loads a compressed snapshot of the current state and applies only the updates that occurred since the snapshot was saved. This keeps initial load times under one second even for documents with thousands of edits.
  • Selective awareness: Cursor and selection data is sent at a lower frequency than text edits (roughly 10 times per second) to avoid overwhelming the network while still providing a smooth visual experience.
  • Garbage collection: Yjs periodically compresses its internal data structures, removing metadata for operations that all clients have already processed. This prevents memory usage from growing unbounded during long sessions.
  • Binary encoding: All Yjs updates are encoded as Uint8Arrays using a custom binary format that is significantly smaller than equivalent JSON representations — typically 3–5x more compact.

How ShareCode Compares to Other Collaboration Stacks

Different collaborative editors use different approaches. Here is how the major architectures compare:

FeatureShareCode (Yjs CRDT)Google Docs (OT)VS Code Live Share
Conflict resolutionAutomatic (CRDT)Server-sequenced (OT)Host-authoritative
Offline supportYes — auto merge on reconnectLimitedNo
Server dependencyStateless relay onlyCentral server requiredHost machine required
Setup requiredNone — browser onlyNone — browser onlyVS Code extension + sign-in
Latency<100ms typical<200ms typicalVaries by host connection

ShareCode's CRDT-based approach offers the best combination of simplicity, offline resilience, and low latency. Because there is no central server processing operations, the system scales horizontally — adding more users to a code space does not increase server load, only network traffic between peers.

Frequently Asked Questions

What happens if two people type at the exact same position at the exact same time?

Yjs assigns each character a globally unique identifier based on the client ID and a logical clock. When two characters land at the same position, Yjs uses a deterministic tie-breaking rule (comparing client IDs) to decide the order. Both clients independently arrive at the same result without any communication — this is mathematically guaranteed by the CRDT specification.

Does ShareCode store my code on a server?

Yes. Document state is periodically snapshotted and saved to Firebase Firestore so your code persists even if all participants disconnect. The signaling server that relays real-time updates is stateless and does not store any document content.

How many people can collaborate on a single code space?

There is no hard limit enforced by the CRDT layer. In practice, Yjs performs well with up to 20–30 simultaneous editors. Beyond that, network bandwidth becomes the bottleneck rather than the CRDT algorithm itself. For most pair programming and interview use cases, 2–5 participants is the sweet spot.

Can I use ShareCode offline?

You can continue editing if your connection drops temporarily. Yjs buffers your changes locally and automatically merges them when the connection resumes. However, you need an initial connection to load the code space and authenticate.

Is the WebSocket connection encrypted?

Yes. All connections use TLS encryption (wss:// for WebSockets, https:// for Firestore). Your code is never transmitted in plaintext over the network.

Experience real-time sync yourself

Open a code space and invite a collaborator. See the magic in action. Free forever.

Try ShareCode Free →