Sub topic 10
Group Chat and Fan-Out Strategies
This chapter assumes you know the one-to-one message flow from earlier chapters: a client sends over a persistent connection, the chat server assigns a per-chat sequence number, stores the message, and delivers it to the recipient. It also assumes you understand acknowledgements and idempotent writes. Here we extend that flow to conversations with many members.
What changes with groups
In a one-to-one chat, one send produces one delivery. In a group chat, one send produces N deliveries, where N is the number of members minus the sender. Copying one message to many recipients is called fan-out.
Three things get harder:
- Write amplification. One message can trigger many writes, many network hops, and many push notifications.
- Ordering. All members must see the same order. This is why ordering belongs to the chat, not to each user.
- Uneven delivery. Some members are online, some are offline, and some are connected to different servers.
Fan-out on write versus fan-out on read
There are two basic strategies for getting a group message to members.
Fan-out on write copies the message into a per-recipient inbox when it is sent. Each user reads only their own inbox. Reads are cheap, but a send to a group of 500 members costs 500 inbox writes.
Fan-out on read stores the message once, in the chat's log. Each member reads the log of every chat they belong to and tracks how far they have read. Writes are cheap, but a client that is in many chats must query many logs to see what is new.
| Property | Fan-out on write | Fan-out on read |
|---|---|---|
| Writes per message | One per member | One |
| Storage | Grows with group size | Grows with message count only |
| Read cost | One inbox lookup | One lookup per chat |
| Cost of a large group | High at send time | Low at send time |
| Fits | Small groups, many reads | Large groups, rare reads |
What chat systems usually do
Most chat designs use a hybrid. The message is stored once, in the chat's log, keyed by chat ID and sequence number. This matches the storage model from the earlier chapters and avoids copying message bodies. What gets fanned out is a small delivery event: "chat c1 has a new message at seq 42."
So the system does two separate jobs:
- Durable write. Append the message to the chat log exactly once.
- Delivery. For each member, push the event to their live connection if they have one, or hand it to the push notification path if they do not.
Delivery to an offline member needs no per-user copy of the message. When that member reconnects, the client asks for messages after the last sequence number it has seen in each chat. Fan-out on read handles the catch-up.
Why not fan-out on write for everything? Messages are large compared with events, and groups can be big. Copying a 2 KB message into 500 inboxes uses about 1 MB for a single send. Copying a 40-byte event is far cheaper, and the event is disposable because the log is the source of truth.
Designing the server-side flow
Here is the flow for a group message sent to chat c1.
The sender's acknowledgement is returned after the durable write, not after delivery to everyone. Waiting for all members would make one slow or disconnected member delay the sender's confirmation.
The steps:
- The sender's chat server appends the message to the chat log. Idempotency on the sender's client message ID means a retry returns the same stored message.
- The server acknowledges the sender with the assigned sequence number.
- The server loads the member list and looks up where each member is connected, using the session registry (a map from user ID to connection server).
- Members on the same server get the message directly. Members on other servers get it through a message queue or a direct call to their server. Offline members go to push notifications.
Reusing the idempotent append
The server-side append from the delivery guarantees chapter works unchanged for groups, because the sequence counter belongs to the chat. This version also reports who should receive the message:
from collections import defaultdict
class GroupChatLog:
def __init__(self):
self.messages = defaultdict(list)
self.members = defaultdict(set)
self.seen = {}
def add_member(self, chat_id, user_id):
self.members[chat_id].add(user_id)
def append(self, chat_id, sender_id, client_msg_id, text):
if sender_id not in self.members[chat_id]:
raise PermissionError("sender is not a member")
key = (chat_id, sender_id, client_msg_id)
if key in self.seen:
return self.seen[key], False
seq = len(self.messages[chat_id]) + 1
msg = {
"chat_id": chat_id,
"seq": seq,
"sender_id": sender_id,
"client_msg_id": client_msg_id,
"text": text,
}
self.messages[chat_id].append(msg)
self.seen[key] = msg
return msg, True
def recipients(self, chat_id, sender_id):
return sorted(self.members[chat_id] - {sender_id})
log = GroupChatLog()
for user in ("alice", "bob", "carol"):
log.add_member("c1", user)
msg, created = log.append("c1", "alice", "m-1", "hello team")
retry, created_again = log.append("c1", "alice", "m-1", "hello team")
assert created and not created_again
assert msg is retry and msg["seq"] == 1
assert log.recipients("c1", "alice") == ["bob", "carol"]The second return value tells the caller whether this was a new message. Only a new message should trigger fan-out. Otherwise, a retried send would notify every member again.
Group size changes the design
Group size is the main input to the strategy choice.
- Small groups (up to roughly 100 members). Fan-out of delivery events at send time is cheap. Per-member state such as unread counts can be updated inline.
- Large groups (hundreds to thousands). Fan-out happens through a queue and is processed by workers, so the sender's request path stays short. Per-member updates can be batched.
- Very large channels (broadcast style). Skip eager delivery for offline members. Notify only connected members, and let everyone else pull on reconnect. Push notifications may be throttled or summarized, for example "20 new messages."
Many systems also cap group size, such as 256 or 1,000 members. A cap is a legitimate requirement decision, and it bounds the worst-case fan-out cost.
Edge cases and failure modes
- Membership changes. A member who leaves while a send is in flight might still be in the list that the server loaded. Decide whether delivery is based on membership at send time. Storing the membership version with the message makes this auditable. Never let a removed member read messages sent after removal.
- Partial delivery. Delivery to Bob may succeed while delivery to Carol fails. Because delivery events are only hints, a failed event is not a lost message. Carol's client will notice the gap in sequence numbers on its next sync and fetch the missing range.
- Duplicate events. A queue may deliver an event twice. Clients ignore any
(chat_id, seq)they already have. - Hot chats. One very active group can overload the single partition or server that owns its sequence counter. Mitigate by keeping the counter's work small (assign a number and append), and move everything else, such as push and unread counts, off the critical path.
- Read receipts. Per-member read receipts in a large group create write amplification in the other direction, with N members each sending an update. Store a single "last read seq" per member and limit receipt delivery to small groups.
- Slow consumers. A member on a bad connection can build a backlog on its connection server. Cap the buffer. When it overflows, drop the buffered events and let the client resync from its last sequence number.
Choosing a strategy
Use these criteria when deciding:
- Group size distribution. If nearly all groups are small, per-recipient work at send time is acceptable. If a few are huge, you need the queue-based or pull-based path for those.
- Read pattern. If users open many chats per session, a single inbox per user speeds up the chat list. A common compromise is a small per-user record per chat, holding the last sequence number and unread count, instead of copies of messages.
- Offline tolerance. If members are often offline for days, avoid per-user message copies, since they pile up.
- Consistency needs. If all members must see an identical order, keep one sequence counter per chat, as covered in the ordering chapter.
Exercise
A group of 1,000 members receives a message of 2 KB. Compare the bytes written under fan-out on write with copying the full message to each member's inbox, against storing it once and fanning out a 40-byte event to each member. Which approach would you pick for this group, and why?
Show answer
Copying the full message writes about 1,000 x 2 KB = 2 MB. Storing once and sending events writes 2 KB plus 1,000 x 40 bytes = about 42 KB, roughly 48 times less. Pick store-once with event fan-out. The events are disposable, and offline members catch up by fetching messages after their last seen sequence number, so no per-user copies are needed.
Exercise
Carol was offline when message seq 42 was delivered, and her client later receives an event for seq 45. What should her client do, and why does this work without a per-user inbox?
Show answer
The client sees that it holds up to seq 41 and has received seq 45, so seqs 42 to 44 are missing. It requests messages with seq greater than 41 from the chat log, up to the latest, and ignores duplicates by (chat_id, seq). This works because the log is the single source of truth and sequence numbers are per chat and contiguous.