Skip to content

Lesson 5 of 9 · 23m

Fan-Out and Broker Design: Pub/Sub, Sharding, and Slow Consumers

How events move from one server to many, why broker semantics matter, and how to keep a slow room or client from poisoning the fleet.

Fan-out is easy in a demo and dangerous in production. Publishing one event to ten thousand sockets means ten thousand individual writes, each with its own memory pressure and failure mode. The broker moves bytes between servers; it does not absolve you from thinking about delivery.

Pick broker semantics deliberately

Redis pub/sub is simple and fast, but it is fire-and-forget: if a server is disconnected, events are gone. NATS core has similar at-most-once behavior. Kafka, NATS JetStream, and Redis Streams provide retention and consumer positions, at the cost of operational complexity. Retention is not the same thing as a correct resume protocol.

ephemeral presence/typing     -> fire-and-forget pub/sub is fine
chat messages / ledger events -> durable log or database-first design
cursor movement / game ticks  -> loss acceptable, coalesce aggressively

Database-first is often the right default

For business events, write the durable record first, then publish a notification:

1. INSERT message row in one transaction
2. COMMIT
3. publish { type:"chat.message.created", id:"..." }
4. realtime servers hydrate or forward the event

If step 3 fails, a relay process can scan committed rows and republish. If you publish before commit, clients can see states that never existed — the worst kind of realtime bug because it cannot be reconciled.

Shard by ownership, not convenience

Room-based workloads shard naturally by room or document. Use consistent hashing or explicit placement so all events for a room preserve order. If messages for the same room travel through different shards, ordering becomes a client-side reconstruction problem. Hot rooms still need room-specific batching, sampling, or delivery groups.

subject: realtime.room.{shard}.{room_id}
shard = crc32(room_id) % 64

Batch and coalesce at the edge

Sending 60 cursor events per second per user is almost never necessary. Coalesce by key and emit the latest state at 10-15 Hz. Batch independent events into one socket frame when latency allows.

const pending = new Map();
function coalesce(key, event) { pending.set(key, event); }
setInterval(() => {
  for (const [key, event] of pending) send(key, event);
  pending.clear();
}, 75);

This is the difference between a transport bill you can afford and one that grows linearly with enthusiasm.

Isolate failure domains

A slow consumer should not block publishing to everyone else. Per-connection outbound queues, per-room queues, and worker pools keep failures local. Global arrays plus synchronous writes are how one bad mobile network takes down a room.

Field notes

  • Measure broker publish latency and socket write latency separately. Averages hide which side is backing up.
  • Pub/sub broker reconnects can silently drop events. Emit sequence gaps so clients resynchronize.
  • Never let user-controlled room names become unbounded broker subjects without validation and normalization.
  • High fan-out rooms need different treatment from ordinary rooms. Detect them early instead of discovering them during a launch.

Was this lesson helpful?

Sign in to rate