<?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 Kartikg on Medium]]></title>
        <description><![CDATA[Stories by Kartikg on Medium]]></description>
        <link>https://medium.com/@kartikg02013?source=rss-ab337050025e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*RlygrsfbQacR5nPK</url>
            <title>Stories by Kartikg on Medium</title>
            <link>https://medium.com/@kartikg02013?source=rss-ab337050025e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 03:36:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kartikg02013/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 Real-Time Systems with Cloudflare Durable Objects]]></title>
            <link>https://medium.com/@kartikg02013/building-real-time-systems-with-cloudflare-durable-objects-5e66a54e370f?source=rss-ab337050025e------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e66a54e370f</guid>
            <category><![CDATA[durable-objects]]></category>
            <category><![CDATA[websocket]]></category>
            <category><![CDATA[cloudflare]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[multiplayer-game]]></category>
            <dc:creator><![CDATA[Kartikg]]></dc:creator>
            <pubDate>Mon, 19 Oct 2026 18:31:01 GMT</pubDate>
            <atom:updated>2026-10-19T18:31:01.653Z</atom:updated>
            <content:encoded><![CDATA[<p>Real-time applications are often introduced as a WebSocket problem. Open a connection, broadcast messages, and the system is done.<br>That model works until multiple users can change the same state, clients disconnect, timers expire, or a client sends an invalid command. At that point, the hard problem is no longer message delivery. It is deciding who owns the truth.</p><p>In this article, I use <a href="https://github.com/Kartik213/GuessTogether"><strong>GuessTogether</strong></a>, a multiplayer guessing game, to explain how Cloudflare Durable Objects can provide that authority for real-time rooms.<br>The same ideas apply to multiplayer games, chat rooms, collaborative editors, live polls, presence systems, and shared dashboards.</p><h3>Try GuessTogether</h3><p>GuessTogether is the multiplayer guessing game I built to explore real-time coordination using Cloudflare Durable Objects.</p><ul><li><strong>Live demo:</strong> <a href="https://guesstogether.kartik2jan.workers.dev/">Try GuessTogether</a></li><li><strong>Source code:</strong> <a href="https://github.com/Kartik213">View the project on GitHub</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aeMdOblSVf1xn2DmNy84dQ.png" /></figure><blockquote><strong>The real problem is coordination<br></strong>- What happens if two players submit at the same time?<br>- Who decides when the timer ends?<br>- How do we prevent a client from submitting twice?<br>- How do we hide the answer until the round is complete?<br>- What happens when the host refreshes the browser?<br>- What happens when a player disconnects during a round?<br>- How does a new browser receive the current state after reconnecting?</blockquote><p>These are value ownership problems. A WebSocket only gives us a communication channel, but it does not decide which event/message is valid or which state is incorrect.</p><h3>A naive architecture</h3><p>A first attempt might look like this:</p><pre>Client A ─┐<br>Client B ─┼─&gt; Stateless API instances ─&gt; Shared database<br>Client C ─┘</pre><p>This can work, but real-time coordination adds infrastructure quickly:</p><ul><li>Concurrent mutations need transactions or locks.</li><li>Broadcasts need a pub/sub system.</li><li>Timers need a reliable server-side scheduler.</li><li>Reconnecting clients need a way to recover state.</li><li>Stale connections need to be removed safely.</li></ul><p>We can store the data in a database, but it does not automatically become the owner of an active real-time session. The application still needs a coordination model around it.</p><h3>The room-owner model</h3><p>GuessTogether uses a different partitioning strategy:</p><pre>Room AB12C ─&gt; Durable Object AB12C<br>Room XY789 ─&gt; Durable Object XY789<br>Room QP456 ─&gt; Durable Object QP456</pre><p>Each logical room has one owner. The owner validates commands, updates state, persists it, and broadcasts the new state to connected clients.</p><p>Cloudflare Durable Objects are a natural fit for this model because an object has a stable identity, can hold state, has storage, supports WebSockets, and can run scheduled alarms.</p><p>The room code becomes the partition key:</p><pre>const id = env.ROOMS.idFromName(roomCode);<br>const room = env.ROOMS.get(id);<br>return room.fetch(&quot;https://room/state&quot;);</pre><p>The same room code always maps to the same logical Durable Object. Different room codes map to different objects, so independent rooms can operate independently.</p><h3>The system architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*qeZfpVCz10_v__3aCUsZ2A.png" /><figcaption>Each layer with a clear responsibility</figcaption></figure><h3>React client</h3><p>The client:<br>- Renders server snapshots.<br>- Stores the player identity in localStorage.<br>- Sends commands over WebSockets.<br>- Manages UI state with Zustand.<br>- Uses TanStack Query for HTTP operations such as room creation.<br>- Reconnects when the socket closes.<br>- The client does not own authoritative scores, answers, timers, or host permissions.</p><h3>Cloudflare Worker</h3><p>The top-level Worker is intentionally small. It:<br>- Serves the React build through the assets binding.<br>- Creates random room codes.<br>- Routes room requests.<br>- Forwards WebSocket upgrades to the matching Durable Object.</p><p>It is a stateless edge entry point, not the owner of live room state.</p><h3>Room Durable Object</h3><p>The Durable Object owns:<br>- The room phase.<br>- The player list.<br>- The host ID.<br>- The current question.<br>- The round deadline.<br>- Submitted guesses.<br>- Scores.<br>- Connected Web-Sockets.<br>- Host migration and re-connection behavior.</p><h3>Durable Object Storage</h3><p>Storage allows the object to restore the room after a restart, hibernation, or period with no active connections.</p><h3>Designing the room state</h3><p>A simplified room state looks like this:</p><pre>type RoomState = {<br>  code: string;<br>  hostId: string;<br>  phase: &quot;lobby&quot; | &quot;active&quot; | &quot;results&quot; | &quot;final&quot;;<br>  players: Player[];<br>  round: number;<br>  questionId: string;<br>  roundEndsAt?: number;<br>  guesses: Record&lt;string, number&gt;;<br>};</pre><p>The internal state is not sent directly to clients. The Durable Object creates a phase-aware snapshot.</p><p>During an active round, a client receives something like:</p><pre>{<br>  phase: &quot;active&quot;,<br>  question: {<br>    prompt: &quot;How many ...?&quot;<br>  },<br>  roundEndsAt: 1760000000000<br>}</pre><p>It does not receive answer, after the round closes, the server can include the answer, submitted guesses, and round scores in the results snapshot.</p><p>This is an important security boundary. A client should receive only the subset of state that is valid for its current phase.</p><h3>Clients send commands and the server mutates the state</h3><p>The client-to-server protocol is command-based:</p><pre>type ClientCommand =<br>  | { type: &quot;join&quot;; playerId: string; name: string }<br>  | { type: &quot;submit_guess&quot;; value: number }<br>  | { type: &quot;start_game&quot; }<br>  | { type: &quot;next_round&quot; }<br>  | { type: &quot;leave&quot; };</pre><p>The server-to-client protocol contains events or snapshots:</p><pre>type ServerEvent =<br>  | { type: &quot;state&quot;; state: RoomSnapshot }<br>  | { type: &quot;error&quot;; message: string };</pre><p>The client does not send a new leaderboard and ask the server to accept it. It sends an action such as submit_guess, and the Durable Object decides whether that action is valid.</p><p>The complete synchronization flow is:</p><pre>Client sends command<br>    ↓<br>Durable Object validates command<br>    ↓<br>Object mutates authoritative state<br>    ↓<br>Object persists state<br>    ↓<br>Object broadcasts a new snapshot<br>    ↓<br>Clients replace their local view</pre><p>Clients synchronize through the room authority. They do not synchronize directly with each other.</p><h3>WebSocket</h3><p>A WebSocket provides a persistent, bidirectional connection:</p><pre>Browser ───────── WebSocket ───────── Durable Object</pre><p>That connection is useful for pushing updates without polling.<br>For GuessTogether, the WebSocket handler is responsible for parsing a message and passing it to the room command handler. The command handler checks the current phase, the player, host permissions, and whether the action has already happened.</p><h3>Authoritative scoring</h3><p>The browser never calculates the authoritative score. It may display a preview, but the Durable Object owns the result.</p><p>The server-side scoring process is:</p><ol><li>Collect valid guesses.</li><li>Calculate each distance from the answer.</li><li>Find the closest submitted guess.</li><li>Award the maximum score to the closest player.</li><li>Calculate relative scores for the remaining players.</li><li>Persist the updated totals.</li><li>Broadcast the results snapshot.</li></ol><p>A simplified version looks like this:</p><pre>const distances = guesses.map((guess) =&gt; ({<br>  playerId: guess.playerId,<br>  distance: Math.abs(guess.value - answer),<br>}));<br>const closestDistance = Math.min(<br>  ...distances.map((entry) =&gt; entry.distance),<br>);<br>for (const entry of distances) {<br>  const points =<br>    entry.distance === closestDistance<br>      ? MAX_ROUND_SCORE<br>      : calculateRelativeScore(entry.distance, closestDistance);<br>      players[entry.playerId].score += points;<br>}</pre><p>The server also enforces one submission per round:</p><pre>if (player.guess !== undefined) {<br>  throw new Error(&quot;Guess already submitted&quot;);<br>}</pre><p>This prevents duplicate submissions even if a user clicks twice or sends a custom WebSocket message.</p><h3>Timers are server-owned</h3><p>A browser countdown is only a visual aid. Browser timers can be throttled, paused, modified, or lost when a tab closes.</p><p>The Durable Object stores an absolute deadline and schedules an alarm:</p><pre>room.roundEndsAt = Date.now() + ROUND_DURATION_MS;<br>await this.state.storage.setAlarm(room.roundEndsAt);</pre><p>When the alarm runs, the object checks that the room is still active and that the deadline has passed. It then closes the round, calculates scores, and broadcasts results.<br>The client calculates the visible countdown from roundEndsAt, but it does not decide when the round ends.</p><p>This pattern is useful in few other places as well:<br>- Auction expiration.<br>- Poll closing.<br>- Reservation timeout.</p><h3>Reconnection</h3><p>A socket connection is temporary. A player identity is not.<br>The browser creates a stable local ID:</p><pre>const storedId = localStorage.getItem(&quot;guess-together-player-id&quot;);<br>const playerId = storedId ?? crypto.randomUUID();<br>localStorage.setItem(&quot;guess-together-player-id&quot;, playerId);</pre><p>When a player refreshes:<br>1. The browser keeps the same player ID.<br>2. The client opens a new WebSocket.<br>3. The Durable Object matches that ID to the existing player.<br>4. The old socket is replaced or marked disconnected.<br>5. The current snapshot is sent.<br>6. The player keeps their name, score, and host status.</p><p>Presence and identity are different concepts. A disconnected socket does not necessarily mean the user has left the room permanently.</p><h3>Host migration</h3><p>Immediate host migration creates bad UX during refreshes. The host may be disconnected for only a few seconds, that’s why we use a grace period:</p><pre>Host disconnects<br>    ↓<br>Start grace timer<br>    ↓<br>Host reconnects<br>    ├─ yes: preserve host<br>    └─ no: transfer host to first connected player</pre><p>The migration policy is server-side and deterministic. A client cannot claim host privileges by changing local state.</p><h3>Persistence and recovery</h3><p>The room keeps active data in memory for fast access and persists state after meaningful mutations.</p><pre>Memory                    Durable Object Storage<br>-------                   ----------------------<br>Fast reads                Recovery after restart<br>Socket handling          Room snapshot<br>Current command          Round deadline</pre><p>Persist values such as:<br>- Room phase.<br>- Players and scores.<br>- Host ID.<br>- Current round.<br>- Question selection.<br>- Guesses.<br>- Round deadline.</p><p>On construction, the Durable Object loads the stored room state. When a player reconnects, the object sends a fresh snapshot instead of relying on the client to reconstruct the game.</p><h3>Scaling by room</h3><p>The room code creates a natural scaling boundary:</p><pre>100 rooms × 8 players<br>= 100 independent coordination objects</pre><p>Advantages:<br>- One room’s updates do not lock another room.<br>- Broadcasts stay bounded to room members.<br>- State is naturally partitioned.<br>- One room’s failure does not corrupt another room.<br>- The room code is both a routing key and a storage key.</p><p>This does not mean a single Durable Object is infinitely scalable. One extremely large room can still become a bottleneck because its state transitions and broadcasts are coordinated through one object.<br>For GuessTogether, the room limit is small enough that one Durable Object per room is a natural design.</p><blockquote><strong><em>Want to explore further?</em></strong></blockquote><blockquote><em>Try the </em><a href="https://guesstogether.kartik2jan.workers.dev/"><strong><em>live demo</em></strong></a><em> or explore the source code on </em><a href="https://github.com/Kartik213/GuessTogether"><strong><em>GitHub</em></strong></a><em> to see how the room state, WebSocket communication, scoring, and reconnection logic work together.</em></blockquote><h3>References</h3><ul><li><a href="https://developers.cloudflare.com/workers/">Cloudflare Workers</a></li><li><a href="https://developers.cloudflare.com/durable-objects/">Cloudflare Durable Objects</a></li><li><a href="https://developers.cloudflare.com/workers/runtime-apis/websockets/">Cloudflare Workers WebSockets</a></li><li><a href="https://developers.cloudflare.com/workers/platform/limits/">Cloudflare Workers limits</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e66a54e370f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>