P2P BROWSER SWARM · EPHEMERAL CLOUDFLARE DURABLE OBJECT SIGNALING

WebRTC Agent Swarm

Two browser peers negotiate a short-lived WebRTC handshake through a Cloudflare SQLite Durable Object, then synchronize an ordered LWW-Element-Set / G-Log CRDT task queue directly over RTCDataChannel, elect a single active coordinator with navigator.locks, and persist state locally in IndexedDB.

Problem & Hypothesis

Multi-tab and multi-peer tools typically route every mutation through a central server database even when browsers can connect directly. Using a Durable Object strictly for ephemeral SDP/ICE handshakes while syncing CRDT logs over RTCDataChannel + IndexedDB keeps application state off-server.

Confirm Signal

Peers converge on identical SHA-256 CRDT digests over RTCDataChannel with zero task bytes stored on SwarmSignaling (HTTP 422 rejects task keys on the signaling endpoint), while navigator.locks enforces single-leader coordination.

Falsify Signal

Restrictive NATs or firewalls block direct UDP peer connections frequently enough to require a TURN relay for consumer networks, pulling traffic back through relay infrastructure.

Run the Experiment

Verify P2P handshake setup, concurrent CRDT convergence, HTTP 422 signaling boundary enforcement, and Web Locks coordination.

1. Spawn Peer B & Connect P2P

Mounts /?peer=b&room=<room>&embed=1 in the paired frame, exchanges SDP and ICE via SwarmSignaling, and stops HTTP polling once the channel opens.

2. Concurrent CRDT Ops & Digest

Dispatches colliding Lamport-clock operations on Peer A and Peer B simultaneously over RTCDataChannel and verifies identical SHA-256 digests.

3. Web Locks & IndexedDB

Acquires navigator.locks.request("swarm-leader-…") with ifAvailable: true, tests contention on Peer B, and inspects swarm_crdt_db.

DO Server Tasks: 0 422 Guard: Not Probed Peer Convergence: Pending P2P

Pair a Second Browser Tab

Open this URL in another tab or window to join the same signaling room as peer-b:

LOCAL WORKBENCH

Peer A · Impolite Initiator

IDLE
CRDT Digest (SHA-256)
—
Lamport Clock / Ops
0 · 0 ops
Web Locks API
Unlocked
IndexedDB (swarm_crdt_db)
0 persisted
RTCDataChannel Frames
0 tx / 0 rx
Remote Reported Digest
—

Replicated LWW-Element-Set Tasks

0 tombstones
  • No active tasks in local CRDT log.
Live Wire Inspector — Ephemeral DO Signaling vs P2P RTCDataChannel Frames
DO HTTP Calls: 0 · RTCDataChannel Frames: 0 · Server Task Payloads: 0
Initializing WebRTC Agent Swarm workbench…
Canonical CRDT Log & SHA-256 Digest Input
{}
Web Locks API & IndexedDB (swarm_crdt_db) Telemetry
Live snapshot of browser-native navigator.locks.query() and swarm_crdt_db records.
Loading storage and lock telemetry…
WebRTC Agent Swarm Architecture Diagram Peer A and Peer B exchange ephemeral SDP offers, answers, and ICE candidates through the SwarmSignaling SQLite Durable Object, then open a direct peer-to-peer RTCDataChannel for CRDT task synchronization while coordinating via Web Locks and persisting to IndexedDB. SwarmSignaling Durable Object (SQLite · 120s TTL) POST /api/room/:id/signal · GET/DELETE /signals · 0 task payloads stored Signaling Plane: Ephemeral Relay Only SDP Offer + ICE SDP Answer + ICE Peer A (Host Workbench) RTCPeerConnection + crdt-log.js navigator.locks("swarm-leader-…") IndexedDB: swarm_crdt_db (peer-a) Peer B (Iframe or Tab 2) RTCPeerConnection + crdt-log.js navigator.locks("swarm-leader-…") IndexedDB: swarm_crdt_db (peer-b) RTCDataChannel("agent-crdt") Direct P2P · Server Off-Path
Figure 1: Signaling flows vertically through the ephemeral Durable Object during WebRTC setup; once open, CRDT operations flow horizontally over RTCDataChannel.
How This Is Set Up

Signaling Plane vs. Peer-to-Peer Data Plane

Instead of routing every task write through a central WebSocket server, task mutations stay in a deterministic LWW-Element-Set CRDT synced directly over RTCDataChannel, persisted locally in IndexedDB, and coordinated with navigator.locks. The Cloudflare Durable Object stores only 120-second SDP/ICE rows.

Server-centered sync (baseline)
// Central server WebSocket persists and fans out every task mutation
const ws = new WebSocket("wss://api.example.com/rooms/demo/tasks");
function enqueueTask(title, role) {
  // Every peer write traverses the central server even on one machine
  ws.send(JSON.stringify({ type: "task:create", title, role }));
}
ws.onmessage = (event) => {
  renderTasks(JSON.parse(event.data).tasks); // Server owns state & order
};
P2P CRDT + ephemeral signaling (this lab)
// public/app.js + public/lib/crdt-log.js
localState = appendOperation(localState, {
  id: opId,
  peerId: localPeerId,
  lamport: localState.clock + 1,
  op: "enqueue",
  payload: { title, role },
});
await persistLocalState(); // Writes swarm_crdt_db in IndexedDB
dataChannel.send(JSON.stringify({
  kind: "crdt:sync",
  peerId: localPeerId,
  state: localState,
  digest: computeLogDigest(localState),
}));
Page Markup, Signaling 422 Guard & Durable Object Wiring

Matches public/index.html, public/lib/signaling-guard.js, public/app.js, and src/worker.ts.

<!-- 1. Page HTML Setup (public/index.html) -->
<form id="task-form" class="task-form">
  <input id="task-title" type="text" required maxlength="120" autocomplete="off">
  <select id="task-role"><option value="planner">planner</option><option value="executor">executor</option></select>
  <button type="submit">Enqueue Op</button>
</form>
<ul id="task-list" class="task-list"></ul>
<div id="peer-b-container" class="iframe-wrap"></div>
<script type="module" src="/app.js"></script>

// 2. HTTP 422 Signaling Guard (public/lib/signaling-guard.js)
const ALLOWED_TYPES = new Set(["offer", "answer", "candidate", "bye"]);
const ALLOWED_TOP_KEYS = new Set(["fromPeer", "toPeer", "type", "sdp", "candidate", "reason"]);
const FORBIDDEN_DATA_KEYS = new Set(["tasks", "task", "taskId", "ops", "op", "crdt", "payload", "digest", "entries"]);
// validateSignalEnvelope(rawBody) rejects any FORBIDDEN_DATA_KEYS match with HTTP 422.

// 3. IndexedDB, Web Locks, RTCDataChannel & Durable Object (public/app.js + src/worker.ts)
const request = window.indexedDB.open("swarm_crdt_db", 1); // peer_logs & task_entries stores
navigator.locks.request(`swarm-leader-${currentRoomId}`, { ifAvailable: true }, async (lock) => {
  if (!lock) return; // Another peer holds the exclusive room leader lock
});
const pc = new RTCPeerConnection(getIceConfiguration());
const channel = pc.createDataChannel("agent-crdt", { ordered: true });
channel.onopen = () => {
  stopSignalPolling(); // Server is off the task path once RTCDataChannel opens
  channel.send(JSON.stringify({
    kind: "crdt:sync",
    peerId: localPeerId,
    state: localState,
    digest: computeLogDigest(localState),
  }));
};
// src/worker.ts SwarmSignaling Durable Object:
// SQLite table "signals" keeps SDP/ICE rows for 120_000 ms (alarm cleanup, serverTaskStorage: 0).
Worker Boundary & Commutative Merge Contract
// src/worker.ts — /api/room/:id/signal POST handler
const validated = validateSignalEnvelope(parsed.body);
if (!validated.ok) {
  return jsonResponse({ error: validated.error }, validated.status); // 422 on task/CRDT keys
}
const result = await stub.postSignal(roomId, validated.signal);
return jsonResponse(result, 201);

// public/app.js — Commutative LWW-Element-Set merge on RTCDataChannel message
localState = mergeCrdtStates(localState, incoming.state);
await persistLocalState();
const digest = computeLogDigest(localState); // FIPS 180-4 SHA-256 over canonical ops
What moves off-server

Task storage, continuous WebSocket fan-out for peer writes, and server-side state ordering.

What is enforced explicitly

HTTP 422 signaling validation (validateSignalEnvelope), 120s SQLite signal TTLs, SHA-256 CRDT digests, and Web Locks leader leases.

Platform limits tested

WebRTC still needs an out-of-band signaling relay for SDP/ICE discovery, symmetric NATs require TURN relays, and IndexedDB remains per-origin.