<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sejin Jang on Medium]]></title>
        <description><![CDATA[Stories by Sejin Jang on Medium]]></description>
        <link>https://medium.com/@jace_2214?source=rss-536a1d59c725------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*MzqWAX1_HNDkWEaO</url>
            <title>Stories by Sejin Jang on Medium</title>
            <link>https://medium.com/@jace_2214?source=rss-536a1d59c725------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 09:57:13 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jace_2214/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Real-Time Collaborative Editor with CRDT and Durable Objects]]></title>
            <link>https://medium.com/toonsquare-tech/building-a-real-time-collaborative-editor-with-crdt-and-durable-objects-01fb69258197?source=rss-536a1d59c725------2</link>
            <guid isPermaLink="false">https://medium.com/p/01fb69258197</guid>
            <dc:creator><![CDATA[Sejin Jang]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 09:42:30 GMT</pubDate>
            <atom:updated>2026-03-03T10:02:11.610Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Collaboration Edit Screen Synchronized in Real Time" src="https://cdn-images-1.medium.com/max/700/1*5UxC5O-sbp4vBw463p1frA.gif" /><figcaption><em>Collaboration Edit Screen Synchronized in Real Time</em></figcaption></figure><p>When multiple users edit a single canvas simultaneously, how do you resolve data conflicts?</p><p>The Tooning team solved this problem by combining the CRDT-based <strong>Yjs</strong> library with <strong>Cloudflare Durable Objects</strong>. In this post, we share the technical decisions we made while designing and implementing our real-time collaborative editor, and the architecture that emerged as a result.</p><p>This article covers the differences between OT and CRDT, the role separation of WebSocket and WebRTC, the serverless architecture built on Cloudflare Durable Objects, and the storage strategies that differ between solo and collaborative editing modes.</p><h3>Architecture Overview at a Glance</h3><p>Before diving into the details, let’s start with a high-level view of Tooning’s collaboration system. We’ll unpack each component in the sections that follow.</p><figure><img alt="Overall Architecture Overview" src="https://cdn-images-1.medium.com/max/640/1*a-ruBey-grdN4UKoE9JEpw.png" /><figcaption><em>Overall Architecture Overview</em></figcaption></figure><p>On the client side, there’s an editor and a Yjs service layer. On the server side, Cloudflare Durable Objects handle the heavy lifting. Two communication paths exist: <strong>WebSocket</strong> for document data, and <strong>WebRTC</strong> for cursor data.</p><p>Let’s explore how we arrived at this architecture, step by step.</p><h3>1. Editor Structure: Canvas and Pages</h3><p>Tooning’s editor is structured with multiple <strong>Pages</strong> inside a single <strong>Canvas</strong>. Think of each page as a panel in a comic strip.</p><p>The first decision we had to make when designing the collaboration feature was: <strong>“At what granularity should we split the data?”</strong></p><h3>Why We Separated Document Objects</h3><p>Initially, we considered managing the entire canvas as a single document object. But we quickly identified two problems.</p><p><strong>The first problem was performance degradation from unnecessary synchronization.</strong> If the entire canvas is a single document, then while User A is editing Page 1, changes made by User B on Page 4 are transmitted in real time via WebSocket. But from User A’s perspective on Page 1, there’s absolutely no need to receive Page 4’s changes. In fact, continuously receiving irrelevant changes only degrades performance. By splitting documents per page, only changes for the currently viewed page are exchanged, eliminating this issue.</p><p><strong>The second problem was initial loading speed.</strong> When opening a 20-page canvas, if you need to download all 20 pages of data when you only need Page 1, the user experience suffers significantly.</p><p>So we separated document objects as follows:</p><figure><img alt="Y.Doc Separation Structure" src="https://cdn-images-1.medium.com/max/640/1*ZQcl9XU7GMa9CL7q9C0A-w.png" /><figcaption><em>Y.Doc Separation Structure</em></figcaption></figure><ul><li><strong>Canvas Y.Doc (1):</strong> Manages metadata such as page order, thumbnail images for each page, and canvas size/background color. It’s relatively lightweight.</li><li><strong>Page Y.Doc (N):</strong> Manages the property data of actual graphic objects (shapes, images, text, etc.) on each page. Only the page being edited needs to be loaded.</li></ul><p>As a result, a 4-page canvas operates with 5 independent document objects (1 canvas + 4 pages). When a user navigates to a specific page, only that page’s Y.Doc connects to the server, and the previous page’s connection is released — efficiently managing network resources.</p><h3>2. Conflict-Free Data Synchronization: CRDT and Yjs</h3><p>The hardest problem in a collaborative editor is: <strong>“What happens when two users modify the same thing at the same time?”</strong></p><p>There are two well-known approaches to solving this problem.</p><h3>OT vs CRDT</h3><figure><img alt="OT vs CRDT comparison" src="https://cdn-images-1.medium.com/max/640/1*1YQAFw4viZpZfSFvnOZ1Hg.png" /><figcaption><em>OT vs CRDT comparison</em></figcaption></figure><p><strong>OT (Operational Transformation)</strong> is the approach used by Google Docs. All editing operations are sent to a central server, which adjusts the order of operations and redistributes them to each client. It’s like a traffic officer directing vehicles at an intersection.</p><p><strong>CRDT (Conflict-free Replicated Data Type)</strong> is the approach used by Figma — and the one we chose. Each client maintains its own unique document object, and when a change occurs, only the change log is sent to other clients. This guarantees that all clients’ documents eventually converge to the same state. It’s like having a roundabout at every intersection — each vehicle yields and avoids collisions on its own.</p><h3>Why We Chose CRDT</h3><figure><img alt="Why We Chose CRDT" src="https://cdn-images-1.medium.com/max/640/1*1uY7vNExgVwnFEkmze1Cng.png" /><figcaption><em>Why We Chose CRDT</em></figcaption></figure><p>The decisive reasons for choosing CRDT were <strong>reduced server load</strong> and <strong>offline support</strong>.</p><p>With CRDT, the server doesn’t transform operations. It simply relays change logs from one client to the others (broadcast). The actual merging happens in each client’s browser, significantly reducing the server’s CPU burden.</p><p>Additionally, in the Private canvas mode (solo work mode) we’ll explore later, users can work locally without a server connection and seamlessly merge data when they come back online — a property CRDT guarantees by design.</p><h3>Do Conflicts Really Get Resolved?</h3><p>Consider a scenario where User A changes a shape to red while User B simultaneously changes the same shape to blue.</p><p>The CRDT algorithm combines the timestamp included in each change with a unique client ID to <strong>deterministically</strong> decide which value becomes the final result. The key insight is that this decision logic is identical across all clients. Regardless of the order in which change logs are received, the final result is always the same.</p><h3>Yjs: Our Practical Partner for CRDT Implementation</h3><p>Instead of implementing CRDT from scratch, we adopted <strong>Yjs</strong>, the most mature open-source CRDT implementation. Here’s why:</p><ul><li><strong>Rich data types:</strong> Yjs provides various CRDT types like Y.Map, Y.Array, and Y.Text, allowing us to apply the optimal type for each use case — Maps for graphic object properties, Arrays for layer ordering, and Text for text editing.</li><li><strong>Provider architecture:</strong> The network transport layer is pluggable. This let us flexibly combine WebSocket, WebRTC, and IndexedDB depending on the situation.</li><li><strong>Built-in UndoManager:</strong> Undo/Redo in a collaborative environment differs from regular undo — you need to undo only <em>your own</em> actions. Yjs’s UndoManager supports this out of the box.</li></ul><pre>// Example: Converting a Fabric.js object&#39;s properties to a Y.Map<br>function createYMapToObject(fabricObject: any): Y.Map&lt;any&gt; {<br>  const yMap = new Y.Map();<br>  yMap.set(&quot;type&quot;, fabricObject.type);<br>  yMap.set(&quot;left&quot;, fabricObject.left);<br>  yMap.set(&quot;top&quot;, fabricObject.top);<br>  yMap.set(&quot;scaleX&quot;, fabricObject.scaleX);<br>  yMap.set(&quot;fill&quot;, fabricObject.fill);<br>  // ... remaining properties<br>  return yMap;<br>}</pre><h3>3. Dual Protocol: WebSocket + WebRTC</h3><p>Once we decided <em>what</em> to synchronize with CRDT, we needed to decide <em>how</em> to transmit it.</p><p>Instead of sending all data through a single protocol, we chose a strategy of <strong>separating protocols based on the nature of the data</strong>.</p><figure><img alt="Dual Protocol Strategy" src="https://cdn-images-1.medium.com/max/640/1*5CUKh224irVkcmn8sOYCxg.png" /><figcaption><em>Dual Protocol Strategy</em></figcaption></figure><h3>WebSocket: The Lifeline of Document Data</h3><p>Editing data — shape positions, sizes, colors, text content — travels through WebSocket via the central server (Durable Objects).</p><p>This data cannot afford to lose a single bit. If part of a user’s 30-minute editing session vanishes, it’s catastrophic. TCP-based WebSocket guarantees data order and automatically retransmits lost packets.</p><p>Also, because data passes through the server, <strong>persistent storage becomes possible</strong>. The server receives all changes, saves the latest state to S3, and can immediately serve the most up-to-date document when a new user connects.</p><h3>WebRTC: The Highway for Cursors</h3><p>Mouse cursor position, on the other hand, is an entirely different kind of data.</p><p>Every time the mouse moves, dozens of coordinate updates occur per second. Sending all of this data to the server would cause traffic costs to skyrocket. But cursor data doesn’t need to be saved, and if a frame or two is dropped, users won’t even notice.</p><p>So cursor data is transmitted <strong>directly between clients (P2P) via WebRTC</strong>. Since it never touches the server, server costs are $0, and latency is minimized by eliminating the middleman.</p><h3>The Secret of Cursor Rendering: DOM Overlay</h3><p>There’s one more optimization worth sharing: <strong>how we render other users’ cursors on screen</strong>.</p><p>The intuitive approach is to draw cursors directly on the Canvas (Canvas 2D), but this would require re-rendering the entire canvas every time a cursor moves. Redrawing a canvas with dozens of complex graphic objects dozens of times per second is devastating for performance.</p><p>Instead, we place a <strong>separate DOM layer on top of the canvas</strong> and move cursors using CSS transform3d. Since transform3d leverages the browser&#39;s GPU acceleration, smooth cursor animations are possible completely independently of canvas re-rendering.</p><pre>// DOM-based cursor rendering (GPU-accelerated)<br>cursorElement.style.transform = `translate3d(${x}px, ${y}px, 0)`;<br>// → Smooth cursor movement without canvas re-rendering</pre><h3>4. Serverless Architecture: Cloudflare Durable Objects</h3><p>We said the server doesn’t “transform operations” in CRDT, but that doesn’t mean a server isn’t needed. The role of relaying change logs between clients and permanently storing document state still remains.</p><p>The traditional approach is to run a WebSocket server directly. But this approach came with two concerns:</p><ul><li><strong>Cost:</strong> The server must stay running even when nobody is editing.</li><li><strong>Scalability:</strong> Horizontal scaling is difficult as concurrent editing sessions grow, because WebSocket connections are stateful.</li></ul><p>We adopted <strong>Cloudflare Durable Objects</strong> to solve both problems simultaneously.</p><h3>What Are Durable Objects?</h3><p>In one sentence, Durable Objects are <strong>“document-dedicated servers that are automatically created when needed and automatically destroyed when not.”</strong></p><p>Think of it like a meeting room rental service. You get assigned a room when you need a meeting, do whatever you need inside (share documents, use the whiteboard), and return the room when you’re done. You’re never charged for empty rooms.</p><figure><img alt="Durable Objects Life Cycle" src="https://cdn-images-1.medium.com/max/640/1*STnt5j91V1I62iuQ8vw0Rg.png" /><figcaption><em>Durable Objects Life Cycle</em></figcaption></figure><p>Here’s how it works in detail:</p><ul><li><strong>💤 Idle:</strong> When nobody is editing a given canvas, its D.O. instance doesn’t exist. Idle server cost is $0.</li><li><strong>🟢 First Connect:</strong> When the first user opens a canvas, a D.O. instance is automatically created for that document ID. At this point, it loads existing document data from S3 to initialize the Y.Doc.</li><li><strong>🔄 Active:</strong> Multiple users edit simultaneously. The D.O. broadcasts change logs and periodically saves to S3. Usage-based billing applies here based on WebSocket message count and duration.</li><li><strong>💤 Shutdown (All Disconnected):</strong> When all users leave, the final state is saved to S3 and the D.O. instance is automatically destroyed.</li></ul><h3>Key Insight: “The Server is Also a Client”</h3><p>One of the most interesting design decisions is that <strong>the D.O. server itself operates as a Yjs client</strong>.</p><p>The D.O. also has a Y.Doc instance internally. When it receives change logs from all clients, it merges the document according to the CRDT algorithm. As a result, the D.O.’s Y.Doc always maintains the most up-to-date and complete document state.</p><p>This state is periodically saved (snapshotted) to S3, which means:</p><ul><li>A new user can immediately receive the latest document upon connecting</li><li>Even if the D.O. shuts down, data is safely preserved</li></ul><pre>// Inside Durable Objects: Y.Doc initialization process (simplified)<br>async function initializeDoc(roomType: string, roomId: number, doc: Y.Doc) {<br>  if (roomType === &quot;page&quot;) {<br>    // Load existing document snapshot from S3<br>    const existingData = await getObject(`editor/page/${roomId}`);<br>    if (existingData) {<br>      Y.applyUpdate(doc, existingData); // Restore existing state<br>    }<br>  } else if (roomType === &quot;canvas&quot;) {<br>    // Query page list from DB and set up Y.Doc<br>    const pages = await getPages(roomId);<br>    doc.transact(() =&gt; {<br>      const pageOrder = new Y.Array();<br>      pages.forEach((page) =&gt; pageOrder.push([page.id]));<br>      doc.getMap(&quot;pages&quot;).set(&quot;page_order&quot;, pageOrder);<br>    });<br>  }<br>}</pre><h3>Changes in Cost Structure</h3><p>Let’s compare the cost structures before and after adopting D.O.:</p><figure><img alt="Changes in Cost Structure" src="https://cdn-images-1.medium.com/max/640/1*bTge-xS2T21YY9Ebj_vkuw.png" /><figcaption><em>Changes in Cost Structure</em></figcaption></figure><p>The key is the <strong>“pay only for what you use”</strong> model. Traditional servers incur maintenance costs even during idle hours, but D.O. only charges for active sessions with actual WebSocket messages. If nobody edits in the middle of the night, the cost is $0.</p><h3>5. Storage Strategy: Public vs Private</h3><p>Tooning’s editor has two modes: <strong>Public canvas</strong> for collaborative work with invited users, and <strong>Private canvas</strong> for solo work.</p><p>These two modes have <em>fundamentally different</em> storage strategies.</p><figure><img alt="Public vs Private Storage Comparison" src="https://cdn-images-1.medium.com/max/640/1*sYyrRV6BeL1MO-c4eRC7_g.png" /><figcaption><em>Public vs Private Storage Comparison</em></figcaption></figure><h3>Public Canvas: Server Handles Storage</h3><p>In Public mode, the Durable Objects server detects Y.Doc changes and automatically saves them to S3.</p><p>However, saving to S3 on every single change would cause excessive costs. So we apply <strong>throttling</strong> to batch saves at regular intervals. Additionally, we compare with the previous save point and <strong>only save when actual changes exist</strong>.</p><pre>// Change detection: state vector comparison<br>const previousVector = lastSavedStateVector.get(roomKey);<br>const currentVector = Y.encodeStateVector(doc);<br><br>// Byte-level comparison to check for actual changes<br>if (previousVector.every((byte, i) =&gt; byte === currentVector[i])) {<br>  return; // No changes → skip save<br>}</pre><h3>Private Canvas: Local Storage Without a Server</h3><p>Connecting to a WebSocket server when working alone is an unnecessary cost. So in Private mode, <strong>no server connection is made at all</strong>.</p><p>Instead, the browser’s <strong>IndexedDB</strong> serves as the storage. The y-indexeddb library automatically records all Y.Doc changes to IndexedDB. This means your work persists through browser refreshes, and you can continue editing even with a completely disconnected network.</p><p>Additionally, since relying solely on IndexedDB means losing work if browser data is cleared, the <strong>client backs up to S3 every 30 seconds</strong>.</p><p>We also implemented cleanup logic that <strong>automatically deletes data not accessed for 30 days</strong> to prevent stale IndexedDB data from consuming browser storage. When storage usage exceeds 70%, the expiration threshold is shortened for more aggressive cleanup.</p><h3>Private ↔ Public Transition</h3><p>The most elegant part is the <strong>transition between modes</strong>. When switching from Private to Public, the Y.Doc instance stays the same — only the <strong>Provider is swapped</strong>.</p><pre>Before: Y.Doc ──→ IndexedDBProvider (local)<br>After:  Y.Doc ──→ WebSocketProvider (Durable Objects)<br>               └── Same Y.Doc instance</pre><p>Thanks to the core property of CRDT, changes accumulated locally and changes on the server <strong>merge automatically</strong>. The mode transition happens seamlessly — no conflict worries, no data loss concerns.</p><h3>Wrapping Up</h3><h3>Looking Back</h3><p>The biggest lesson from building a real-time collaborative editor was that <strong>“there is no single right answer for every problem.”</strong></p><ul><li>WebSocket was the right fit for document data; WebRTC was perfect for cursor data.</li><li>Durable Objects suited multi-user scenarios; IndexedDB was ideal for solo work.</li><li>Client-centric CRDT, rather than server-centric OT, matched our situation.</li></ul><p><strong>Accurately understanding the nature of the data and combining the optimal technology for each type</strong> was the key.</p><h3>The Hardest Part</h3><p>Harder than choosing technologies was the <strong>synchronization logic between the Fabric.js canvas and Yjs</strong>.</p><p>Converting Fabric.js objects to Y.Maps, and conversely reflecting Y.Map changes back to Fabric.js objects, surfaced countless edge cases — real-time text style synchronization, image filter serialization, coordinate transforms within group objects, and more. This topic alone could fill an entire blog post.</p><h3>References</h3><p>If you’d like to dive deeper into the technologies covered in this post:</p><ul><li><a href="https://docs.yjs.dev/">Yjs Official Docs</a> — The official guide for the CRDT implementation Yjs</li><li><a href="https://www.figma.com/blog/how-figmas-multiplayer-technology-works/">Figma’s Multiplayer Technology Blog</a> — Pioneers of real-time collaboration using CRDT</li><li><a href="https://developers.cloudflare.com/durable-objects/">Cloudflare Durable Objects Docs</a> — A new paradigm in serverless state management</li><li><a href="https://crdt.tech/">CRDT.tech</a> — Academic resources on CRDT</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=01fb69258197" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/building-a-real-time-collaborative-editor-with-crdt-and-durable-objects-01fb69258197">Building a Real-Time Collaborative Editor with CRDT and Durable Objects</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[CRDT와 Durable Objects로 구현한 실시간 협업 에디터]]></title>
            <link>https://medium.com/toonsquare-tech/crdt%EC%99%80-durable-objects%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%9C-%EC%8B%A4%EC%8B%9C%EA%B0%84-%ED%98%91%EC%97%85-%EC%97%90%EB%94%94%ED%84%B0-a394b5db4270?source=rss-536a1d59c725------2</link>
            <guid isPermaLink="false">https://medium.com/p/a394b5db4270</guid>
            <dc:creator><![CDATA[Sejin Jang]]></dc:creator>
            <pubDate>Tue, 03 Mar 2026 04:49:51 GMT</pubDate>
            <atom:updated>2026-03-03T10:00:35.657Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Collaboration Edit Screen Synchronized in Real Time" src="https://cdn-images-1.medium.com/max/700/1*5UxC5O-sbp4vBw463p1frA.gif" /><figcaption>Collaboration Edit Screen Synchronized in Real Time</figcaption></figure><p>여러 사용자가 동시에 하나의 캔버스를 편집할 때, 데이터 충돌은 어떻게 해결할 수 있을까요?</p><p>투닝 팀은 CRDT 기반의 Yjs 라이브러리와 Cloudflare Durable Objects를 결합하여 이 문제를 해결했습니다. 이 글에서는 실시간 협업 에디터를 설계하고 구현하면서 마주한 기술적 의사결정들과, 그 결과로 완성된 아키텍처를 공유합니다.</p><p>이 글은 OT와 CRDT의 차이, WebSocket과 WebRTC의 역할 분리, Cloudflare Durable Objects 기반 서버리스 아키텍처, 그리고 혼자 작업할 때와 함께 작업할 때 달라지는 저장 전략까지를 다룹니다.</p><h3>전체 아키텍처 한눈에 보기</h3><p>본격적인 이야기에 앞서, 투닝의 협업 시스템 전체 구조를 먼저 보여드리겠습니다. 각 구성 요소가 어떤 역할을 하는지는 이후 섹션에서 하나씩 풀어보겠습니다.</p><figure><img alt="Overall Architecture Overview" src="https://cdn-images-1.medium.com/max/640/1*XdIWX9b6C0B6rLQBN3DQGQ.png" /><figcaption>Overall Architecture Overview</figcaption></figure><p>클라이언트 사이드에는 에디터와 Yjs 서비스 레이어가 있고, 서버 사이드에는 Cloudflare Durable Objects가 있습니다. 그리고 두 개의 통신 경로가 존재합니다. <strong>문서 데이터</strong>를 위한 WebSocket과, <strong>커서 데이터</strong>를 위한 WebRTC입니다.</p><p>왜 이런 구조가 되었는지, 처음부터 차근차근 이야기해 보겠습니다.</p><h3>1. 에디터 구조: 캔버스와 페이지</h3><p>투닝 에디터는 하나의 <strong>캔버스(Canvas)</strong> 안에 여러 개의 **페이지(Page)**가 존재하는 구조입니다. 만화의 각 컷을 생각하시면 됩니다.</p><p>협업 기능을 설계할 때 가장 먼저 결정해야 했던 것은 <strong>“데이터를 어떤 단위로 나눌 것인가”</strong> 였습니다.</p><h3>왜 문서 객체를 분리했을까?</h3><p>처음에는 캔버스 전체를 하나의 문서 객체로 관리하는 방법을 고려했습니다. 하지만 곧 두 가지 문제를 발견했습니다.</p><p><strong>첫 번째 문제는 불필요한 동기화로 인한 성능 저하입니다.</strong> 캔버스 전체를 하나의 문서로 관리하면, 사용자 A가 1페이지를 보며 편집하는 동안 사용자 B가 4페이지에서 만든 변경점까지 WebSocket을 통해 실시간으로 전달됩니다. 하지만 1페이지를 편집 중인 사용자 A 입장에서는 4페이지의 변경점을 반영할 필요가 없으므로, 이 데이터를 받아보지 않아도 전혀 문제가 없습니다. 오히려 불필요한 변경점이 계속 수신되면서 성능 저하를 유발할 수 있습니다. 페이지 단위로 문서를 분리하면, 현재 보고 있는 페이지의 변경점만 주고받게 되어 이 문제가 해결됩니다.</p><p><strong>두 번째 문제는 초기 로딩 속도입니다.</strong> 20페이지짜리 캔버스를 열 때, 현재 보고 있는 1페이지의 데이터만 필요한데 20페이지 분량을 모두 내려받아야 한다면 사용자 경험이 크게 저하됩니다.</p><p>그래서 저희는 다음과 같이 문서 객체를 분리했습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*Jr6ye4uy_uT3ae-_i-9YSQ.png" /><figcaption>Y.Doc Separation Structure</figcaption></figure><ul><li><strong>캔버스 Y.Doc (1개)</strong>: 페이지 순서, 각 페이지의 썸네일 이미지, 캔버스 크기/배경색 등의 메타데이터를 관리합니다. 상대적으로 가볍습니다.</li><li><strong>페이지 Y.Doc (N개)</strong>: 각 페이지에 실제로 존재하는 그래픽 객체들(도형, 이미지, 텍스트 등)의 속성 데이터를 관리합니다. 편집 중인 페이지만 로드하면 됩니다.</li></ul><p>결과적으로, 4페이지 캔버스에서는 5개의 문서 객체(1 캔버스 + 4 페이지)가 독립적으로 운용됩니다. 사용자가 특정 페이지로 이동하면 해당 페이지의 Y.Doc만 서버에 연결하고, 이전 페이지의 연결은 해제하는 방식으로 네트워크 리소스도 효율적으로 관리합니다.</p><h3>2. 충돌 없는 데이터 동기화: CRDT와 Yjs</h3><p>협업 에디터에서 가장 어려운 문제는 <strong>“두 사용자가 동시에 같은 것을 수정하면 어떻게 되는가?”</strong> 입니다.</p><p>이 문제를 해결하는 두 가지 대표적인 접근법이 있습니다.</p><h3>OT vs CRDT</h3><figure><img alt="OT vs CRDT comparison" src="https://cdn-images-1.medium.com/max/640/1*eJRiSvrvp3lotDRDFShKKQ.png" /><figcaption>OT vs CRDT comparison</figcaption></figure><p>**OT(Operational Transformation)**는 구글 독스가 사용하는 방식입니다. 모든 편집 연산을 중앙 서버로 보내고, 서버가 연산의 순서를 조정한 뒤 다시 각 클라이언트에 배포합니다. 교통 경찰이 교차로에서 차량의 순서를 정해주는 것과 비슷합니다.</p><p>**CRDT(Conflict-free Replicated Data Type)**는 피그마가 사용하는 방식이며, 저희도 이 방식을 선택했습니다. 각 클라이언트가 자신만의 고유한 문서 객체를 보유하고 있고, 변경이 발생하면 변경 로그만 다른 클라이언트에게 보냅니다. 이를 통해 모든 클라이언트의 문서가 최종적으로 동일한 상태에 도달하는 것을 보장합니다. 교차로마다 회전교차로(로터리)가 있어서, 각 차량이 알아서 양보하며 충돌을 피하는 것과 비슷합니다.</p><h3>CRDT를 선택한 이유</h3><figure><img alt="Why We Chose CRDT" src="https://cdn-images-1.medium.com/max/640/1*FhbO1--x8Z2Zo-brH0A6fQ.png" /><figcaption>Why We Chose CRDT</figcaption></figure><p>저희가 CRDT를 선택한 결정적 이유는 <strong>서버 부하 절감</strong>과 <strong>오프라인 지원</strong>이었습니다.</p><p>CRDT에서는 서버가 연산을 변환하지 않습니다. 단순히 한 클라이언트가 보낸 변경 로그를 다른 클라이언트들에게 전달(브로드캐스트)하기만 하면 됩니다. 실제 병합은 각 클라이언트의 브라우저에서 일어나기 때문에, 서버의 CPU 부담이 크게 줄어듭니다.</p><p>또한, 나중에 살펴볼 Private 캔버스(혼자 작업 모드)에서는 서버 연결 없이 로컬에서만 작업하다가 나중에 온라인에 복귀해도 자연스럽게 데이터가 병합되는데, 이것은 CRDT가 설계적으로 보장하는 속성입니다.</p><h3>충돌은 정말로 해결될까?</h3><p>사용자 A가 도형을 빨간색으로, 사용자 B가 같은 도형을 파란색으로 동시에 바꾸는 상황을 생각해 보겠습니다.</p><p>CRDT 알고리즘은 각 변경에 포함된 <strong>타임스탬프</strong>와 <strong>클라이언트 고유 ID</strong>를 조합하여, 어떤 값을 최종 결과로 쓸지 **결정적(deterministic)**으로 판단합니다. 핵심은 이 판단 로직이 모든 클라이언트에서 동일하다는 점입니다. 변경 로그를 어떤 순서로 받든, 최종 결과는 항상 같습니다.</p><h3>Yjs: CRDT 구현의 실전 파트너</h3><p>저희는 CRDT를 직접 구현하는 대신, 가장 성숙한 오픈소스 구현체인 <strong>Yjs</strong>를 채택했습니다. Yjs를 선택한 이유는 다음과 같습니다.</p><ul><li><strong>풍부한 데이터 타입</strong>: Y.Map, Y.Array, Y.Text 등 다양한 CRDT 타입을 제공하여, 그래픽 객체의 속성(Map), 레이어 순서(Array), 텍스트 편집(Text) 각각에 최적의 타입을 적용할 수 있었습니다.</li><li><strong>Provider 아키텍처</strong>: 네트워크 전송 계층을 플러그인 형태로 교체할 수 있습니다. 덕분에 WebSocket, WebRTC, IndexedDB를 상황에 따라 유연하게 조합할 수 있었습니다.</li><li><strong>UndoManager 내장</strong>: 협업 환경에서의 Undo/Redo는 일반적인 Undo와 다릅니다. “내가 한 작업만” 되돌려야 하는데, Yjs의 UndoManager가 이를 기본 지원합니다.</li></ul><pre>// 예시: Fabric.js 객체의 속성을 Y.Map으로 변환<br>function createYMapToObject(fabricObject: any): Y.Map&lt;any&gt; {<br>  const yMap = new Y.Map();<br>  yMap.set(&quot;type&quot;, fabricObject.type);<br>  yMap.set(&quot;left&quot;, fabricObject.left);<br>  yMap.set(&quot;top&quot;, fabricObject.top);<br>  yMap.set(&quot;scaleX&quot;, fabricObject.scaleX);<br>  yMap.set(&quot;fill&quot;, fabricObject.fill);<br>  // ... 나머지 속성들<br>  return yMap;<br>}</pre><h3>3. 이중 프로토콜: WebSocket + WebRTC</h3><p>CRDT로 “무엇을” 동기화할지 결정했다면, 이제 “어떻게” 전송할지를 결정해야 합니다.</p><p>저희는 하나의 프로토콜로 모든 데이터를 보내는 대신, <strong>데이터의 성격에 따라 두 가지 프로토콜을 분리</strong>하는 전략을 택했습니다.</p><figure><img alt="Dual Protocol Strategy" src="https://cdn-images-1.medium.com/max/640/1*-67xgjJcUrpt_Yk67WGKFQ.png" /><figcaption>Dual Protocol Strategy</figcaption></figure><h3>WebSocket: 문서 데이터의 생명선</h3><p>도형의 위치, 크기, 색상, 텍스트 내용 등 <strong>편집 데이터</strong>는 WebSocket을 통해 중앙 서버(Durable Objects)를 경유합니다.</p><p>이 데이터는 한 비트도 잃어버려서는 안 됩니다. 사용자가 30분간 편집한 결과의 일부가 사라진다면 치명적이기 때문입니다. TCP 기반의 WebSocket은 데이터 순서를 보장하고, 중간에 패킷이 유실되면 자동으로 재전송합니다.</p><p>또한, 서버를 경유하기 때문에 <strong>영구 저장이 가능</strong>합니다. 서버가 모든 변경을 받아서 최신 상태를 S3에 저장해두면, 나중에 새로운 사용자가 접속했을 때 즉시 최신 문서를 제공할 수 있습니다.</p><h3>WebRTC: 커서의 고속도로</h3><p>반면, <strong>마우스 커서 위치</strong>는 전혀 다른 성격의 데이터입니다.</p><p>마우스가 움직일 때마다 초당 수십 번의 좌표 업데이트가 발생합니다. 이 데이터를 매번 서버로 보내면 서버 트래픽 비용이 기하급수적으로 증가합니다. 그런데 커서 데이터는 저장할 필요도 없고, 중간에 한두 프레임이 빠져도 사용자가 체감하지 못합니다.</p><p>그래서 커서 데이터는 <strong>WebRTC를 통해 클라이언트 간 직접(P2P) 전송</strong>합니다. 서버를 전혀 거치지 않으므로 서버 비용이 0원이고, 중간 경유지가 없기 때문에 지연 시간도 최소화됩니다.</p><h3>커서 렌더링의 비밀: DOM 오버레이</h3><p>한 가지 더 공유하고 싶은 최적화가 있습니다. 다른 사용자의 커서를 화면에 어떻게 그리느냐의 문제입니다.</p><p>직관적으로는 캔버스(Canvas 2D)에 커서를 직접 그리는 방법을 떠올리지만, 이 방식은 커서가 움직일 때마다 <strong>캔버스 전체를 다시 렌더링</strong>해야 합니다. 수십 개의 복잡한 그래픽 객체가 있는 캔버스를 초당 수십 번 다시 그리는 것은 성능에 치명적입니다.</p><p>저희는 캔버스 위에 <strong>DOM 레이어를 별도로 올리고</strong>, CSS transform3d로 커서를 이동시킵니다. transform3d는 브라우저의 GPU 가속을 활용하기 때문에, 캔버스의 다시 그리기와 완전히 독립적으로 부드러운 애니메이션이 가능합니다.</p><pre>// DOM 기반 커서 렌더링 (GPU 가속)<br>cursorElement.style.transform = `translate3d(${x}px, ${y}px, 0)`;<br>// → 캔버스 재렌더링 없이 커서만 부드럽게 이동</pre><h3>4. 서버리스 아키텍처: Cloudflare Durable Objects</h3><p>CRDT에서 서버는 “연산 변환”을 하지 않는다고 했지만, 그렇다고 서버가 필요 없는 것은 아닙니다. 클라이언트 간 변경 로그를 중계하고, 문서 상태를 영구 저장하는 역할이 여전히 필요합니다.</p><p>전통적인 방식은 WebSocket 서버를 직접 운영하는 것입니다. 하지만 이 방식에는 두 가지 고민이 있었습니다.</p><ol><li><strong>비용</strong>: 아무도 편집하지 않는 시간에도 서버가 켜져 있어야 합니다.</li><li><strong>확장성</strong>: 동시 편집 세션이 늘어날 때 수평 확장(Scale-out)이 어렵습니다. WebSocket은 상태를 가지고 있기 때문입니다.</li></ol><p>저희는 <strong>Cloudflare Durable Objects</strong>를 도입하여 이 두 가지를 동시에 해결했습니다.</p><h3>Durable Objects란?</h3><p>Durable Objects를 한마디로 설명하면, <strong>“필요할 때 자동으로 생성되고, 필요 없으면 자동으로 사라지는 문서 전용 서버”</strong> 입니다.</p><p>사무실 대여 서비스에 비유할 수 있습니다. 회의가 필요할 때 방을 배정받고, 회의실 안에서 필요한 작업(문서 공유, 화이트보드 사용)을 자유롭게 합니다. 회의가 끝나면 방을 반납합니다. 빈 회의실에 대해서는 비용이 발생하지 않습니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*WENL5fFfDGZ0VIBSyn_b9Q.png" /><figcaption>Durable Objects Life Cycle</figcaption></figure><p>구체적으로 보면:</p><ul><li><strong>💤 대기 (Idle)</strong>: 아무도 해당 캔버스를 편집하지 않으면, D.O. 인스턴스는 존재하지 않습니다. 유휴 서버 비용이 0원입니다.</li><li><strong>🟢 생성 (First Connect)</strong>: 첫 번째 사용자가 캔버스에 접속하면, 해당 문서 ID에 대한 D.O. 인스턴스가 자동으로 생성됩니다. 이때 S3에서 기존 문서 데이터를 로드하여 Y.Doc을 초기화합니다.</li><li><strong>🔄 활성 (Active)</strong>: 여러 사용자가 동시에 편집합니다. D.O.는 변경 로그를 브로드캐스트하고, 주기적으로 S3에 저장합니다. 이 구간에서 WebSocket 메시지 수에 따른 종량제 과금이 발생합니다.</li><li><strong>💤 종료 (All Disconnected)</strong>: 모든 사용자가 떠나면, 최종 상태를 S3에 저장한 후 D.O. 인스턴스가 자동으로 소멸됩니다.</li></ul><h3>핵심 인사이트: “서버도 하나의 클라이언트”</h3><p>가장 흥미로운 설계 결정 중 하나는, <strong>D.O. 서버 자체도 하나의 Yjs 클라이언트로 동작한다</strong>는 점입니다.</p><p>D.O. 내부에도 Y.Doc 인스턴스가 있습니다. 모든 클라이언트의 변경 로그를 수신하면, CRDT 알고리즘에 따라 자체적으로 문서를 병합합니다. 그래서 D.O.의 Y.Doc에는 항상 <strong>가장 최신이자 가장 완전한 문서 상태</strong>가 유지됩니다.</p><p>이 상태를 S3에 주기적으로 저장(스냅샷)하기 때문에:</p><ul><li>새 사용자가 접속하면 즉시 최신 문서를 제공할 수 있고</li><li>D.O.가 종료되더라도 데이터는 안전하게 보존됩니다</li></ul><pre>// Durable Objects 내부: Y.Doc 초기화 과정 (간략화)<br>async function initializeDoc(roomType: string, roomId: number, doc: Y.Doc) {<br>  if (roomType === &quot;page&quot;) {<br>    // S3에서 기존 문서 스냅샷 로드<br>    const existingData = await getObject(`editor/page/${roomId}`);<br>    if (existingData) {<br>      Y.applyUpdate(doc, existingData); // 기존 상태 복원<br>    }<br>  } else if (roomType === &quot;canvas&quot;) {<br>    // DB에서 페이지 목록 조회 후 Y.Doc에 세팅<br>    const pages = await getPages(roomId);<br>    doc.transact(() =&gt; {<br>      const pageOrder = new Y.Array();<br>      pages.forEach((page) =&gt; pageOrder.push([page.id]));<br>      doc.getMap(&quot;pages&quot;).set(&quot;page_order&quot;, pageOrder);<br>    });<br>  }<br>}</pre><h3>비용 구조의 변화</h3><p>D.O. 도입 전후의 비용 구조를 비교하면:</p><figure><img alt="Changes in Cost Structure" src="https://cdn-images-1.medium.com/max/640/1*QerIfdzOzI_3YJsuikBnyw.png" /><figcaption>Changes in Cost Structure</figcaption></figure><p>핵심은 <strong>“쓴 만큼만 내는 종량제”</strong> 구조라는 점입니다. 전통적 서버는 사용하지 않는 시간에도 서버 유지비가 발생하지만, D.O.는 실제로 WebSocket 메시지를 주고받는 활성 세션에 대해서만 비용이 발생합니다. 새벽 시간에 아무도 편집하지 않으면 비용도 0원입니다.</p><h3>5. 저장 전략: Public vs Private</h3><p>투닝 에디터에는 두 가지 모드가 있습니다. 다른 사용자를 초대하여 함께 작업하는 <strong>Public 캔버스</strong>와, 혼자 작업하는 <strong>Private 캔버스</strong>입니다.</p><p>이 두 모드는 저장 전략이 근본적으로 다릅니다.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*348GMJD41II2xQEYmxuGHw.png" /><figcaption>Public vs Private Storage Comparison</figcaption></figure><h3>Public 캔버스: 서버가 저장을 담당</h3><p>Public 모드에서는 Durable Objects 서버가 Y.Doc의 변경을 감지하여 <strong>자동으로 S3에 저장</strong>합니다.</p><p>다만, 매번 변경이 일어날 때마다 S3에 저장하면 비용이 과다하게 발생합니다. 그래서 <strong>throttle</strong>을 적용하여 일정 간격으로 모아서 저장합니다. 또한, 이전 저장 시점과 비교하여 <strong>실제로 변경이 있을 때만</strong> 저장을 수행합니다.</p><pre>// 변경점 감지: state vector 비교<br>const previousVector = lastSavedStateVector.get(roomKey);<br>const currentVector = Y.encodeStateVector(doc);<br><br>// 바이트 단위로 비교하여 실제 변경 여부 확인<br>if (previousVector.every((byte, i) =&gt; byte === currentVector[i])) {<br>  return; // 변경 없음 → 저장 안 함<br>}</pre><h3>Private 캔버스: 서버 없이 로컬 저장</h3><p>혼자 작업하는데 WebSocket 서버에 연결하는 것은 불필요한 비용입니다. 그래서 Private 모드에서는 <strong>서버 연결 자체를 하지 않습니다.</strong></p><p>대신, 브라우저의 <strong>IndexedDB</strong>를 저장소로 사용합니다. y-indexeddb 라이브러리가 Y.Doc의 모든 변경을 자동으로 IndexedDB에 기록합니다. 덕분에 브라우저를 새로고침해도 작업 내용이 유지되고, 네트워크가 완전히 끊겨도 문제없이 편집을 이어갈 수 있습니다.</p><p>추가로, IndexedDB에만 의존하면 브라우저 데이터가 삭제될 때 작업물을 잃을 수 있으므로, <strong>클라이언트가 30초 간격으로 S3에 백업</strong>합니다.</p><p>또한, 오래된 IndexedDB 데이터가 브라우저 용량을 차지하는 것을 방지하기 위해, <strong>30일 동안 접근하지 않은 데이터는 자동 삭제</strong>하는 정리 로직도 구현했습니다. 스토리지 사용량이 70%를 초과하면 만료 기준을 단축하여 더 적극적으로 정리합니다.</p><h3>Private ↔ Public 전환</h3><p>가장 우아한 부분은 두 모드 간 전환입니다. Private에서 Public으로 전환할 때, <strong>Y.Doc 인스턴스는 그대로 유지하고 Provider만 교체</strong>합니다.</p><pre>전환 전: Y.Doc ──→ IndexedDBProvider (로컬)<br>전환 후: Y.Doc ──→ WebSocketProvider (Durable Objects)<br>              └── 동일한 Y.Doc 인스턴스</pre><p>CRDT의 핵심 속성 덕분에, 로컬에서 쌓인 변경과 서버의 변경은 자동으로 병합됩니다. 충돌 걱정 없이, 데이터 손실 걱정 없이, 매끄럽게 모드 전환이 이루어집니다.</p><h3>마무리하며</h3><h3>돌아보며</h3><p>실시간 협업 에디터를 구현하면서 가장 크게 느낀 점은, <strong>“모든 문제에 하나의 정답은 없다”</strong> 는 것이었습니다.</p><ul><li>문서 데이터에는 <strong>WebSocket</strong>이, 커서 데이터에는 <strong>WebRTC</strong>가 적합했습니다.</li><li>다중 사용자 환경에는 <strong>Durable Objects</strong>가, 혼자 작업하는 환경에는 <strong>IndexedDB</strong>가 적합했습니다.</li><li>서버 중심의 <strong>OT</strong> 대신, 클라이언트 중심의 <strong>CRDT</strong>가 우리 상황에 맞았습니다.</li></ul><p>데이터의 성격을 정확히 파악하고, 각 성격에 맞는 최적의 기술을 조합하는 것이 핵심이었습니다.</p><h3>가장 어려웠던 것</h3><p>기술 선택보다 더 어려웠던 것은 <strong>Fabric.js 캔버스와 Yjs 사이의 동기화 로직</strong>이었습니다.</p><p>Fabric.js 객체를 Y.Map으로 변환하고, 반대로 Y.Map의 변경을 Fabric.js 객체에 반영하는 과정에서 수많은 엣지 케이스를 만났습니다. 텍스트 스타일의 실시간 동기화, 이미지 필터의 직렬화, 그룹 객체 내부의 좌표 변환 등 — 이 부분만으로도 하나의 블로그 글을 쓸 수 있을 정도입니다.</p><h3>참고 자료</h3><p>이 글에서 다룬 기술들에 대해 더 깊이 알고 싶으시다면:</p><ul><li><a href="https://docs.yjs.dev/"><strong>Yjs 공식 문서</strong></a> — CRDT 구현체 Yjs의 공식 가이드</li><li><a href="https://www.figma.com/blog/how-figmas-multiplayer-technology-works/"><strong>Figma의 멀티플레이어 기술 블로그</strong></a> — CRDT를 활용한 실시간 협업의 선구자</li><li><a href="https://developers.cloudflare.com/durable-objects/"><strong>Cloudflare Durable Objects Docs</strong></a> — 서버리스 상태 관리의 새로운 패러다임</li><li><a href="https://crdt.tech/"><strong>CRDT.tech</strong></a> — CRDT에 대한 학술적 자료 모음</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a394b5db4270" width="1" height="1" alt=""><hr><p><a href="https://medium.com/toonsquare-tech/crdt%EC%99%80-durable-objects%EB%A1%9C-%EA%B5%AC%ED%98%84%ED%95%9C-%EC%8B%A4%EC%8B%9C%EA%B0%84-%ED%98%91%EC%97%85-%EC%97%90%EB%94%94%ED%84%B0-a394b5db4270">CRDT와 Durable Objects로 구현한 실시간 협업 에디터</a> was originally published in <a href="https://medium.com/toonsquare-tech">toonsquare.tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>