Video in progress

For a channel or group chat with 200,000 members, which do you choose: fan-out on write or fan-out on read?

In small groups, fan-out on write (writing to each member's inbox) is simple and reads are fast. In large channels the write cost explodes, so for those the message is stored once and members get it at read time. In practice a hybrid is used.

📖 Answer

Fan-out on write: when a message arrives, a copy is written to each member's personal inbox, then pushed to the online members. The upside is that each user's stream is ready, and on reconnect one query returns "my new messages". In a 10-person group that's 10 writes per message, which is cheap.

In a channel with 200,000 members, though, one message is 200,000 writes. At 50 messages a day that's 10 million writes for one channel alone, and most of them nobody will read.

Fan-out on read: the message is written once to the channel's stream. For each member only the "last read seq" is stored. When the client opens the channel, it asks "give me those with seq > X". Writes are cheap, reads are a bit more expensive but work well with a cache, since everyone reads the same latest messages.

Real-time push has a similar split. In a small group, a personal message to each member's gateway. In a large channel, the gateways know the "channel subscription": each gateway subscribes to the channel once, receives the message once, and distributes it locally to its own subscribers. Not 200,000 pushes, but 40 messages to 40 gateways.

I set the hybrid threshold by member count, say 1000. Smaller than that, on write; larger, on read. A group that crosses the threshold is migrated in one direction.

What gets forgotten is the unread count (unread badge). In the on-read model, computing it requires latestSeq - lastReadSeq for each channel. If a user is in 300 channels, that's fetching 300 values. The usual solution is to store it as a separate, cached counter and allow it to lag.

And when one popular message arrives in a large channel, all devices ask "load the new message" at the same moment. So it's better to send the message itself in the push, not just a signal.