Catalog My learning Blog
Full-Stack Developer Course: React, .NET and SQL Server · Phase 13 · Lesson 130 · 8 min read

Design a Collaborative Editor with CRDTs and SignalR

On this page
  1. Learning Objective
  2. Concept Explanation
  3. Worked Example: A SignalR Hub That Authorizes Every Update, and a React Yjs Binding
  4. Real-World Examples
  5. Review Questions & Answers

Learning Objective

Explain how operational transformation and CRDTs let many people edit one document concurrently, design a relay and persistence architecture with SignalR and Yjs, store updates with snapshots and compaction, and enforce authorization, size limits and safe rendering for collaborative content.

Concept Explanation

A collaborative editor lets several people change the same document at once, sees each other's cursors, and keeps working offline. The core difficulty is that two users can edit the same place at nearly the same instant, based on different versions of the document, and everyone must end up with the identical result without losing anyone's intent. Naive approaches fail: locking the document blocks people, and last write wins throws away work. There are two established solutions. Operational transformation, used by Google Docs, has a central server that transforms each operation against those that happened concurrently, so that applying them in any arrival order converges. It is powerful and notoriously hard to implement correctly. Conflict-free replicated data types, CRDTs, design the data structure so that concurrent edits merge automatically and identically regardless of order, with no central transformation, which makes offline editing and peer-to-peer designs natural at the cost of extra metadata. Libraries such as Yjs and Automerge implement CRDTs, and Figma has described a server-authoritative design inspired by CRDT ideas.

For a full-stack product, the practical architecture is a relay. Each client holds a local Yjs document. Local edits produce small binary updates that are sent to the server over a WebSocket connection, and the server, using SignalR, forwards each update to the other clients in that document's group and appends it to storage. A newly joining client receives the stored state, a snapshot plus the updates after it, and then live updates. Presence information such as cursors and who is online is ephemeral and uses a separate lightweight channel that is not persisted. Because a CRDT merges anything it receives, the server does not need to understand the document, which keeps it simple, but it also means the server must enforce the rules around it.

Storage grows if you keep every update, so periodically compact: a worker loads the updates for a document, merges them into a single snapshot, stores it, and deletes the older updates. Deleted content in a CRDT leaves small markers called tombstones, so very long-lived documents grow and benefit from compaction and, where supported, garbage collection. Scaling out follows a simple rule: all clients editing one document should connect to the same server instance, or instances must share updates through a backplane such as Redis or Azure SignalR Service, and documents can be partitioned across servers by identifier.

Security is where a relay design can go wrong. A CRDT applies whatever valid update it receives, so the server must decide who may send updates. Authorize when a connection joins a document, with a role such as viewer, commenter, or editor from the same permission model as the rest of the application, and enforce it on every update message, so a viewer's client cannot push edits by calling the hub directly. Check the permission again periodically or on change, because a user whose access is revoked must be removed from the group promptly. Limit update sizes and rates per connection, since a malicious client can send enormous or endless updates, and cap the document size. Never trust the content itself: rich text in a shared document is user-supplied HTML-like content, so render it through a sanitizing, schema-based renderer and never as raw HTML, otherwise collaborative editing becomes a stored cross-site scripting delivery system that spreads to every participant. Log who changed what where auditing is required, which is possible if updates are attributed to the authenticated connection.

ConcernChoiceNotes
ConvergenceCRDT (Yjs) or OTCRDT suits offline and simpler servers, OT needs a central transformer
TransportSignalR over WebSockets, group per documentBackplane for multiple instances
PersistenceAppend updates, periodic snapshot and compactionBounds storage and load time
Presence and cursorsEphemeral channel, not storedCheap, but do not leak who else is in private documents
Access controlRole per user per document, checked on join and every updateThe relay must enforce, since CRDTs accept any update
Content safetySchema-based rendering, sanitize, size and rate limitsPrevents stored XSS and abuse

Worked Example: A SignalR Hub That Authorizes Every Update, and a React Yjs Binding

The hub joins with a permission check, validates and stores updates, and the React code connects a Yjs document to the hub.

C#
[Authorize]
public sealed class DocHub(AppDb db, IDocPermissions perms, IDocStore store, IRateLimiter limiter) : Hub
{
    private const int MaxUpdateBytes = 256 * 1024;

    // Join: check the user's role for this document, then send the current state (snapshot plus later updates).
    public async Task<byte[]> Join(Guid docId)
    {
        var role = await perms.GetRoleAsync(docId, Context.User!.GetUserId());          // same permission model as the REST API
        if (role == DocRole.None) throw new HubException("Not found.");                  // do not reveal existence

        Context.Items[$"role:{docId}"] = role;
        await Groups.AddToGroupAsync(Context.ConnectionId, $"doc:{docId}");
        return await store.LoadMergedStateAsync(docId);                                  // binary Yjs state
    }

    // Every update is authorized, size limited, rate limited, stored, then relayed. A viewer cannot write by calling the hub.
    public async Task SendUpdate(Guid docId, byte[] update)
    {
        if (Context.Items[$"role:{docId}"] is not DocRole role || role < DocRole.Editor) throw new HubException("Read only.");
        if (update.Length is 0 or > MaxUpdateBytes) throw new HubException("Update rejected.");
        if (!await limiter.AllowAsync($"docupdate:{Context.ConnectionId}", max: 50, per: TimeSpan.FromSeconds(1))) throw new HubException("Too many updates.");

        await store.AppendUpdateAsync(docId, update, Context.User!.GetUserId());          // attributed for audit
        await Clients.OthersInGroup($"doc:{docId}").SendAsync("Update", docId, update);
    }

    // Presence is ephemeral and only relayed to people already in the group, and only for allowed roles.
    public Task SendCursor(Guid docId, CursorState cursor) =>
        Clients.OthersInGroup($"doc:{docId}").SendAsync("Cursor", docId, Context.User!.GetDisplayName(), cursor);
}
C#
// When a permission is removed, the user is dropped from the group and their connections are told, without waiting for a reconnect.
public async Task OnAccessRevokedAsync(Guid docId, string userId)
{
    foreach (var connectionId in connectionTracker.ConnectionsOf(userId, docId))
        await hub.Groups.RemoveFromGroupAsync(connectionId, $"doc:{docId}");
    await hub.Clients.User(userId).SendAsync("AccessRevoked", docId);
}

// Compaction: merge updates into a snapshot in a background job so loading stays fast and storage bounded.
public async Task CompactAsync(Guid docId, CancellationToken ct)
{
    var (snapshot, lastUpdateId) = await store.LoadSnapshotAndUpdatesAsync(docId, ct);
    var merged = YDoc.MergeUpdates(snapshot, /* updates */);                              // binding to a Yjs implementation
    await store.SaveSnapshotAndTrimAsync(docId, merged, lastUpdateId, ct);                 // atomically: new snapshot, delete older updates
}
TypeScript
// React: bind a Y.Doc to the hub. Local edits go out, remote updates are applied without echoing back.
import * as Y from 'yjs';

export function useCollaborativeDoc(docId: string, connection: HubConnection) {
  const [doc] = useState(() => new Y.Doc());
  const [ready, setReady] = useState(false);

  useEffect(() => {
    const onLocalUpdate = (update: Uint8Array, origin: unknown) => {
      if (origin !== 'remote') connection.send('SendUpdate', docId, Array.from(update));   // do not resend what we just received
    };
    doc.on('update', onLocalUpdate);
    connection.on('Update', (id: string, update: number[]) => { if (id === docId) Y.applyUpdate(doc, new Uint8Array(update), 'remote'); });
    connection.on('AccessRevoked', (id: string) => { if (id === docId) window.location.assign('/documents'); });

    connection.invoke<number[]>('Join', docId).then((state) => { Y.applyUpdate(doc, new Uint8Array(state), 'remote'); setReady(true); });

    return () => { doc.off('update', onLocalUpdate); connection.off('Update'); connection.off('AccessRevoked'); doc.destroy(); };   // cleanup on unmount
  }, [docId, connection, doc]);

  return { doc, ready };
}

// Render shared rich text through a schema-based editor that ignores anything outside the allowed nodes and marks,
// never by assigning document content to innerHTML.

The check in SendUpdate is the line that matters. Without it, a client that is only allowed to view could still modify the document, because the CRDT would happily merge the update.

Editor A joins a document and the hub checks its role and returns the merged state. Each update is checked for edit rights, size and rate, appended to storage with the author, and relayed to the group. A viewer that calls the hub directly is rejected, since a CRDT would merge anything it received.
Editor A joins a document and the hub checks its role and returns the merged state. Each update is checked for edit rights, size and rate, appended to storage with the author, and relayed to the group. A viewer that calls the hub directly is rejected, since a CRDT would merge anything it received.

Real-World Examples

  • Google Docs uses operational transformation, a technique with roots in research from the late 1980s and in the Jupiter system, and Google carried the approach through Google Wave into Docs. Its central server transformation model is a reason that implementations are usually done by specialists rather than rebuilt from scratch.
  • Figma's 2019 engineering article on its multiplayer technology explained that it did not use operational transformation, and chose a design inspired by CRDTs but simplified by having a central server as the authority for ordering. It shows that a hybrid can be the practical answer when a server already exists to coordinate and to enforce permissions.
Key TakeawaysA collaborative editor needs a convergence technique, and a CRDT library such as Yjs makes building one practical. Pair it with a SignalR relay that broadcasts binary updates, persists them with snapshots and compaction, and keeps presence ephemeral. Because a CRDT accepts any update, the server must authorize every update by role, revoke access promptly, limit size and rate, and render content through a schema-based sanitizer to prevent stored cross-site scripting.

Review Questions & Answers

They let multiple users edit the same document concurrently from different versions and still converge to the same result without losing intent. Locking blocks people and last write wins discards edits, which is why a merge technique is needed.

A CRDT merges whatever valid update it receives, so nothing in the data structure stops a read-only user from sending edits. The hub must check the user's role on each update message and not only when they join.

Keeping every update makes storage and load time grow without limit. Periodically merging updates into a snapshot and deleting older ones keeps documents fast to open and storage bounded.

Content written by one participant is displayed to all the others, so unsanitized markup becomes stored cross-site scripting that spreads through the document. Rendering through a schema-based editor that allows only known nodes prevents it.