Guides Gossip networks

How gossip networks let peer-to-peer rooms scale

A full mesh works well for four players and poorly for forty. As a WebRTC room grows, connection count and upload bandwidth scale with every participant. This guide covers how a gossip overlay bounds per-browser connections and how Trystero’s experimental scale() plugin builds one without changing your room code.

Why full meshes stop scaling

Suppose you build a shared 128×128 pixel canvas where anyone with the room link can paint. Without a server, every browser opens a direct WebRTC connection to every other browser. For a 4-player lobby or a small jam session, a full mesh is ideal: one hop between every pair of peers and no routing layer.

With N peers, each browser holds N − 1 connections and the room holds N(N − 1) / 2 in total:

Peers in the room Connections per browser Connections across the room
436
8728
2019190
4039780
60591,770

At 40 peers, every pixel edit is uploaded 39 separate times from the sender’s browser, a phone on spotty Wi-Fi maintains 39 DTLS sessions, and a newcomer completes 39 handshakes before seeing the room. Long before bandwidth runs out, connection management taxes CPU and local sockets.

How the gossip overlay works

In a gossip overlay, each peer maintains a bounded number of direct WebRTC connections (its degree) instead of connecting to everyone. Messages travel hop by hop: each peer forwards unseen packets to its neighbors and drops duplicates. In an expander graph, hop distance to the farthest peer grows with log N rather than N—doubling the room adds roughly one hop while connections per browser stay flat.

Passing Trystero’s experimental scale() plugin switches a room from a full mesh to a multi-hop overlay once membership crosses the direct-neighbor threshold:

import {joinRoom, scale} from 'trystero'

// Full mesh up to 7 peers; multi-hop gossip above that
const room = joinRoom({appId: 'plaza.example.com', use: [scale()]}, 'wall-7')
  • Small rooms stay a full mesh. With maxDirectPeers + 1 or fewer peers (7 at the default maxDirectPeers: 6), everyone connects directly with zero routing overhead.
  • Larger rooms form a multi-ring expander. Above that threshold, peers arrange themselves across floor(maxDirectPeers / 2) rings (3 by default). Each ring is a Hamiltonian cycle visiting every peer once in a deterministic, room-salted shuffle, so peers compute identical rings without coordinating. Stacking three differently shuffled rings gives each peer two neighbors per ring, a symmetric target degree of at most maxDirectPeers, and O(log N) diameter. Neighbor counts can briefly exceed the target while joins settle.
  • Routes require two-sided confirmation. Peers advertise signed link-state descriptors (180 s TTL, refreshed by heartbeats and verified traffic, with a 1.2 s churn grace window). Routing tables compute shortest paths exclusively over edges confirmed by both endpoints, bounded by a hop ceiling derived from the verified roster size so stale or fabricated nodes do not linger in peer lists.

maxDirectPeers accepts values from 4 to 32, trading per-browser connections against hop count:

const room = joinRoom(
  {
    appId: 'plaza.example.com',
    maxUsers: 60, // advisory cap on room membership
    use: [
      scale({
        maxDirectPeers: 8 // direct WebRTC neighbors per peer (4..32, default 6)
      })
    ]
  },
  'wall-7'
)

maxDirectPeers only bounds direct WebRTC neighbors; pass maxUsers on joinRoom for an advisory cap on total room membership.

Security across untrusted hops

In a full mesh, every packet travels over a direct DTLS session to its recipient. In a gossip overlay, a message to a peer three hops away passes through two other browsers first. Here is what intermediate peers can and cannot do:

  • No forgery. Every peer generates ephemeral ECDSA P-256 signing keys. Link descriptors, leave notices, broadcasts, and unicast headers are signed and bound to appId, roomId, and a per-origin monotonic sequence counter.
  • No replay. Sliding replay-window deduplication and 60-second freshness bounds reject re-injected packets. room.getTopology().stats tracks invalid signatures in signatureFailures and already-seen copies in duplicatesDropped.
  • End-to-end encrypted unicast. Broadcasts are addressed to the entire room anyway, while targeted messages (any send or request with a target) are encrypted end-to-end between sender and recipient using ECDH P-256 and AES-256-GCM (12-byte IV, canonical header as AAD). Intermediate hops only see ciphertext.
  • Packet dropping on modified clients. Because peers forward traffic cooperatively, a participant running a modified client can drop packets routed through them or open extra tabs up to the per-user and room limits. For rooms with untrusted participants, set a password to restrict entry and load roles() so admins can call room.ban()—honest neighbors check ban records before forwarding, cutting banned peers off at the edge.

Direct promotion for media and large transfers

Multi-hop forwarding suits small control messages and state updates, not live video or a 100 MB file—routing bulk traffic through bystanders would consume their upload bandwidth and add latency to every frame. scale() routes traffic by payload size:

  • Messages, RPC requests, and state updates up to 16 KiB travel over the gossip overlay.
  • addStream, replaceTrack, and chunked binary transfers larger than 16 KiB promote the target peer to a direct 1-hop WebRTC connection on demand. Active media streams pin that direct link open.

Media therefore scales as a 1-to-N star per broadcaster: one presenter streaming to 20 viewers opens 20 direct connections, temporarily exceeding maxDirectPeers. That fits a presentation or town hall, not 40 simultaneous webcams. Because direct promotion can fail on restrictive NATs without TURN, await room.addStream(...) and await action.send(...) to catch errors.

On a shared pixel canvas, individual pixel edits route over the gossip overlay, while a PNG board snapshot larger than 16 KiB sent to a late joiner promotes a direct connection automatically.

Room API compatibility and topology inspection

Room primitives work identically with or without scale() in use: makeUserState, makeState, makeAction, onUserJoin, onUserLeave, getUsers(), ping, and roles() behave the same whether a peer is one hop away or three.

import {joinRoom, scale} from 'trystero'

const room = joinRoom({appId: 'plaza.example.com', use: [scale()]}, 'wall-7')

const brush = room.makeUserState('brush', {name: 'Anon', color: '#f0f'})
brush.set({name: 'Oedipa', color: '#0ff'})

// Payloads <= 16 KiB route over the gossip overlay
const paint = room.makeAction('paint')

paint.onMessage(({x, y, color}, {userId}) => {
  setPixel(x, y, color)
  showActivity(userId, brush.get(userId).name)
})

canvas.addEventListener('pointerdown', e => {
  const {x, y} = toGrid(e)
  const {color} = brush.get()
  setPixel(x, y, color)
  paint.send({x, y, color})
})

room.onUserJoin(({userId}) => console.log(userId, 'joined'))

Loading scale() adds hop metadata to room.getPeers() (direct: true, hops: 1 for a WebRTC neighbor; connection: null with hops >= 2 for peers reached through the overlay) and exposes room.getTopology() for local routing diagnostics:

await room.ready

const {peerId, directPeerIds, roomPeerIds, routes, stats} = room.getTopology()

console.log(
  peerId,
  'has',
  directPeerIds.length,
  'direct neighbors of',
  roomPeerIds.length,
  'remote peers'
)

for (const [id, {nextHop, hops}] of Object.entries(routes)) {
  console.log(id, 'is', hops, 'hop(s) away via', nextHop)
}

console.log(stats)
// {messagesSent, messagesReceived, messagesForwarded, duplicatesDropped, signatureFailures}

// Hop distance is also exposed on getPeers()
for (const {userId, direct, hops} of Object.values(room.getPeers())) {
  console.log(userId, direct ? 'direct' : hops + ' hops')
}

Each peer only tracks its own direct links. To render the full room graph, query reachable peers for their neighbor lists and union the edges:

// Each peer only sees its own direct links, so query all remote peers for theirs
const neighbors = room.makeAction('neighbors', {kind: 'request'})
neighbors.onRequest(() => room.getTopology().directPeerIds)

async function snapshotGraph() {
  const {peerId, directPeerIds, roomPeerIds} = room.getTopology()
  const results = await neighbors.requestMany(null, {
    targets: roomPeerIds,
    timeoutMs: 3000
  })

  const edges = new Set()
  const link = (a, b) => edges.add([a, b].sort().join('|'))

  directPeerIds.forEach(id => link(peerId, id))
  for (const r of results) {
    if (r.status === 'fulfilled') r.value.forEach(id => link(r.peerId, id))
  }

  return [...edges].map(e => e.split('|'))
}

When not to use scale()

  • Small rooms. With 7 or fewer peers at the default setting, scale() stays in full-mesh mode and only adds bundle weight. Apps that omit it tree-shake the routing engine out.
  • Latency-critical action games. Fast-paced games need 1-hop links between every pair of players; multi-hop routes add latency, especially if an intermediate peer is on congested Wi-Fi. Cap the lobby with maxUsers instead.
  • Many-to-many video calls. Media streams promote direct links and bypass the overlay, so scale() does not reduce connection count when everyone turns on a camera.
  • Strict production SLAs. scale() is experimental, built for cooperative rooms with dozens of peers, and tested up to 48 concurrent browser instances and 250+ simulated peers.