DesignTheSystem/dev
System Design (HLD) 7 min read

Real-time fan-out with pub/sub

Deliver one message to many connected users within a second.

Long-lived connections

Chat and live comments keep a connection open (a WebSocket) so the server can push without being asked. Each connection lives on one server, so a message must reach whichever servers hold the receivers.

Pub/sub in the middle

Connection servers subscribe to the rooms their users are in. When a message is sent, it's published once to the room's channel, and the broker hands it to every subscribed server, which pushes it to its users.

send(room, text):
  store.append(room, text)        // keep history
  broker.publish("room:" + room, text)

on broker message for room:
  for conn in localConnections(room):
    conn.push(text)

Fan-out on write vs on read

A feed can be built when posts are written (push a copy to every follower's feed) or when it's read (gather posts from everyone you follow). Push is fast to read but costly for accounts with millions of followers; those are usually pulled at read time instead.

Key takeaways

  • WebSockets let servers push to users.
  • A broker carries each message to every server holding a receiver.
  • Push for normal accounts, pull for huge ones.

Try it in the simulator: Carry the message rate

Put this concept into practice on Chat App Message Broker:

  1. Run the starting design: one API server and one PostgreSQL. Watch both saturate under the message rate.
  2. Put a Load balancer in front of several API servers and store messages in Cassandra. Run again.
  3. Add Kafka with Workers writing to Cassandra, so bursts of messages queue instead of hitting the store.

What to watch: The simulator measures the message rate, not individual WebSocket connections. With API servers sharing the load and a store built for heavy writes, p99 stays under the 120 ms target; the queue adds headroom for bursts.

Check your understanding

Answer these questions interactively to test what you learned and track progress on your skill map:

  1. Why is a broker needed between chat servers?
  2. A celebrity with 50 million followers posts. Which feed strategy suits them?

Continue learning