Building a Paper Clone with Durable Actors.

Multiplayer AI is hard. Hosting millions of memory intensive canvases is also hard. Durable Actors make both easy.

What we are building

Paper design is the first breakthrough Multiplayer AI app.

It's awesome, you import designs you like, then connect via MCP and can work mostly from where your agent is.

Building a product like this has a few challenges. Namely, those canvases can get pretty big and clip 200MB.

Let's go through how you can build a similar app using Durable Actors as the backing store for the canvases.

This tutorial will include:

  • Multiplayer
  • MCP support
  • Real-time updates

Paper canvas with several frames open: a mobile issues list, a Q1 launch plan, and a marketing page

You can find the complete GitHub project here.

The Build

This is a very simple MVP with just the bare-bones features of a multiplayer design tool. Here are the core dependencies:

  • WorkOS: User + team management + MCP Auth. Makes this project so simple it's crazy.
  • Prisma: DB management (yes, we still use postgres for keeping track of which teams own which canvases)
  • Durable Actors (duh): Host + serves the canvases to the users

How it all fits together

  • Frontend renders the canvas. It calls the backend once to open a canvas, then talks to the actor over a WebSocket.
  • Backend checks who you are (WorkOS) and whether your team owns the canvas (Postgres), then hands back a signed WebSocket URL.
  • MCP server is a route in the same backend. Agents call its tools, and the tools call the actor's methods over RPC.
  • Postgres stores who can open which canvas. Nothing else.
  • The actor owns the canvas itself: frames, presence, cursors, and the WebSocket.

A change from the browser. Each tab calls the REST API once to get a WebSocket URL, then talks to the actor directly. Your save goes over your socket into SQLite, and out over your teammate's.

A change from an agent. The agent calls an MCP tool, and the tool calls the actor's saveFrame over RPC. It lands in the same SQLite and goes out to every open tab.

Browsers use the WebSocket because they need a live, two-way stream. The MCP server uses RPC because a tool call is one request and one answer. Both end up in the same actor, so an agent's edit reaches every open tab through the same broadcast.

The DB Schema

Alright you ready for this? Here is the entire prisma schema

prisma
/// The id doubles as the Canvas actor id; frames live in the actor.
model Canvas {
  id             String         @id @default(cuid())
  name           String
  /// WorkOS organization (team) that owns the canvas. Null until its creator gets a team.
  organizationId String?
  createdAt      DateTime       @default(now())
  updatedAt      DateTime       @updatedAt
  members        CanvasMember[]

  @@index([organizationId])
}

model CanvasMember {
  canvas    Canvas   @relation(fields: [canvasId], references: [id], onDelete: Cascade)
  canvasId  String
  /// WorkOS user id
  userId    String
  createdAt DateTime @default(now())

  @@id([canvasId, userId])
  @@index([userId])
}

Thanks to WorkOS, we don't need to handle any user/team management. Simply reference the userId + the organizationId.

The Canvas table hold references to Canvas instances. The instances actually live in Durable Actors (will get to that later).

The CanvasMember table simply tracks who has access to what. When a request comes in for a user to see a Canvas, we can quickly verify if they have access.

Durable Actors + WorkOS keep the DB schema extremely lean and simple to reason about. Notice there is no JSONB field here either. Postgres is operating at maximum efficiency.

The Actor

Let's get to the fun part. The Durable Actor is handling storing the canvas, tracking presence (who is looking at the canvas), mouse tracking, and real time updates.

Here is the full implementation (Leaving the explanation within the comments):

typescript
// This is the representation of a Design Canvas. Each Canvas consists of a list of frames.
export class Canvas extends Actor<CanvasMetadata, CanvasIncoming, CanvasOutgoing> {
    @Ephemeral
    #orm = drizzle(this.db, { schema })

    // A little cache for every frame. Useful for websockets updates pre save (ex: dragging, only save on drop)
    @Ephemeral
    #frames = new Map<string, Frame>()

    constructor(context: ActorContext) {
        super(context)
        migrate(this.db, migrations)
        for (const frame of this.db.exec<Frame>("SELECT id, html, x, y, width, height FROM frames")) {
            this.#frames.set(frame.id, frame)
        }
    }

    // This supports getting every canvas of the frame.
    async getCanvas(): Promise<CanvasData> {
        return { frames: [...this.#frames.values()] }
    }
    
    // fetch a single frame. 
    async getFrame(id: string): Promise<Frame | null> {
        return this.#frames.get(id) ?? null
    }

    // Saves a specific frame
    async saveFrame(frame: Frame): Promise<void> {
        this.#frames.set(frame.id, frame)
        await this.#orm.insert(schema.frames).values(frame).onConflictDoUpdate({ target: schema.frames.id, set: frame })
        this.broadcast({ type: "frame", frame })
    }

    async deleteFrame(id: string): Promise<void> {
        this.#frames.delete(id)
        await this.#orm.delete(schema.frames).where(eq(schema.frames.id, id))
        this.broadcast({ type: "frameDeleted", id })
    }

    // Durable Actors gives you a web-socket server for free. OnConnect is called every-time a client connects to this exact instance.
    async onConnect(socket: CanvasSocket): Promise<void> {
        const peers = await this.#peers()
        socket.send({ type: "canvas", ...(await this.getCanvas()), peers, selfId: socket.id }) // Send to the client who just connected the current state of the canvas
        this.broadcast({ type: "presence", peers }, { except: socket }) // Tell everyone else who is connected that someone new just joined.
    }

    async onDisconnect(): Promise<void> {
        this.broadcast({ type: "presence", peers: await this.#peers() })
    }

    // Presence comes straight from the live connections, so it can't drift even if an onDisconnect is missed
    async #peers(): Promise<Peer[]> {
        return (await this.getConnections()).map((socket) => ({ id: socket.id, ...socket.metadata }))
    }

    // Handle the incoming websocket messages
    async onMessage(socket: CanvasSocket, message: CanvasIncoming): Promise<void> {
        const parsed = canvasClientMessageSchema.safeParse(message)
        if (!parsed.success) return
        switch (parsed.data.type) {
            case "saveFrame":
                return this.saveFrame(parsed.data.frame)
            case "moveFrame": {
                const { id, x, y } = parsed.data
                const frame = this.#frames.get(id)
                if (!frame) return
                this.#frames.set(id, { ...frame, x, y })
                return this.broadcast({ type: "frameMoved", id, x, y }, { except: socket })
            }
            case "deleteFrame":
                return this.deleteFrame(parsed.data.id)
            case "cursor":
                return this.broadcast({ type: "cursor", peerId: socket.id, position: parsed.data.position }, { except: socket })
        }
    }
}

How the MCP Server works

The browser connects to the Actor directly via websocket connection.

The MCP on the other hand, connects through another mechanism: The RPC connection.

Durable Actors Expose two key ways to communicate to it. The Websocket API, where everything goes through onMessage, and the RPC endpoints.

You don't need to think about the RPC endpoints! Every public method on the method automatically creates the RPC API. It's even type safe.

By simply running terse actor generate in the backend folder, you can now do:

typescript
import { actors } from "../generated/index.js";
// ^^ Type-safe generated client

server.registerTool(
    "get_frame",
    {
      description: "Gets a frame, including its HTML.",
      inputSchema: { canvasId: z.string(), frameId: z.string() },
      outputSchema: frameSchema,
      annotations: { readOnlyHint: true },
    },
    async ({ canvasId, frameId }) => {
      const canvas = await findCanvas(canvasId, organizationId);
      if (!canvas) return failure("Canvas not found.");

      // Access the canvas by id, and then the frame within it.
      // This code is in the express app process. Terse provides the plumbing to hit the actor for you!
      const frame = await actors.Canvas.get(canvas.id).getFrame(frameId);

      return frame ? result(frame) : failure("Frame not found.");
    },
  );

MCP support was trivial thanks to this powerful primitives. WorkOS handles the MCP auth, and the generated client does the heavy plumbing to the actor.

What are we storing and where?

Holds Survives a restart Speed
Postgres Which team owns which canvas Yes Network round trip, shared by every canvas
Actor SQLite (this.db) The canvas's frames Yes Local disk, single-digit ms
@Ephemeral field The #frames cache, the ORM handle No, rebuilt from SQLite on wake Plain memory, no I/O

Dragging vs. saving

One neat optimization is that we don't save on "bursty" loads such as dragging. If we were to save on every drag tick, you risk clogging up the Actor.

Instead, we just save on drag ended. This allows your teammates to see the drag in real-time, but it's only durably saved on drag end.

This is a great use case for the Ephemeral field in the Actor!

  • moveFrame fires many times a second while you drag. It updates #frames in memory and tells everyone else. No database write.
  • saveFrame fires once, on drop. It updates memory, writes one row to SQLite, then tells every tab.

The tradeoff is that a drag only lives in memory until the drop. If the actor crashes and restarts mid-drag, the frame snaps back to its last saved position. This is an extremely rare edge case and worth keeping the actor available.

Why don't we just store everything in Postgres?

This is a solution that can work at a small scale. However, some critical issues show up once many people start using your app.

Postgres hates JSONB.

1 writer: p50 1 writer: p95 8 writers: p50 8 writers: p95
Simple transaction row 0.5 ms 0.9 ms 4.2 ms 18 ms
1MB JSONB 50 ms 69 ms 487 ms 651 ms
How much slower ~100× ~75× ~115× ~35×

Writing 1MB of JSONB is 100x slower than a normal row. It also consumes a ton of CPU due to TOAST. Once your CPU is at full usage, your latency will skyrocket as tasks need to queue for an available core.

The only options at scale are sharding + scaling things up + adding read only caches. Very Painful.

Also, if we use the traditional 3-tier web app, we would be forced to implement socket logic here for the real-time updates. Although Socket.io is great, managing websockets is always painful, especially at scale.

Why use Durable Actors?

Instead of reading/writing to a central Database, Durable Actors gives each canvas its own private SQLite database. This prevents having one central choke-point for every canvas.

SQLite is also just faster at this. The database runs right next to the actor's code, so there's no network round trip, and a 1MB read, update and write lands in single-digit milliseconds:

Read, update, write back Postgres (default) SQLite (synchronous=NORMAL) SQLite (synchronous=FULL)
Simple row, p50 0.53 ms 0.012 ms 0.12 ms
1MB JSON, edited in app, p50 44 ms 7.3 ms 6.6 ms
1MB JSON, json_set in database, p50 31 ms 2.8 ms 3.3 ms
1MB JSON vs. simple row ~83× ~600× ~57×

In addition, each actor has it's own WebSocket server. Since each actor is specific to a canvas, there is no room logic to maintain.

This removes all of the pressure on your database + you no longer have to deal with websocket logic or worry about scaling the WebSocket server.

TaggedCoding agentsTypeScriptStatic typingDeveloper productivity

Build your first Durable Actor

One command installs the Terse CLI and walks you through a working actor.

bunx terse-cli@latest install
Read the docs