Scoping chat and estimating connections
Turn a one-line chat brief into scoped requirements, then estimate peak connections, messages, deliveries, receipts, heartbeats, storage and gateway servers with a script you run, and find which limit sizes the gateway tier.
Contentsand lesson path
On this page
- The problem
- Step 1: scope the features, because each one has a cost
- Step 2: write the assumptions down
- Step 3: the expected case by hand
- Step 4: run all three cases
- Step 5: read the breakdown and the what-ifs
- Check your understanding
- Apply it
- Review prompt
Lessons of Chat System Design
- Scoping chat and estimating connections Worked example · 20 min
- Real-time transports and connection gateways Concept · 20 min
- Ordering, receipts and retries Worked example · 25 min
- Message storage, presence and multi-device sync Concept · 25 min
- Chat design check Knowledge check · 6 questions
What you will learn
- Choose a real-time transport (WebSocket, server-sent events, long polling) and design a connection gateway tier that scales to millions of concurrent connections.
Prerequisites: Messaging & Event Streaming
01. The problem
Suppose you join a team that must design the messaging service of a made-up regional social app, which we will call Relay. The brief fits in one line: people chat one to one and in groups, on phones and laptops, and messages show up at once. The plan for the end of year one is 20 million daily active users (DAU: people who open the app at least once that day).
An HTTP API is sized from requests per second; a chat service is sized differently. Every online device keeps one connection open for minutes or hours, and every message turns into several pieces of work: a copy for each recipient device, receipts flowing back, and a push notification for each recipient who is offline. Before we pick a transport or a database, we want five numbers: peak concurrent connections, messages per second, deliveries per second after group fan-out, storage per day, and the number of gateway servers, the machines that hold the open connections. As in the photo-sharing estimate, every number comes from a written assumption and a script you can run.
02. Step 1: scope the features, because each one has a cost
Start with what the product must do and, just as important, what it will not do in version one. A short list keeps the estimate honest, because each feature adds a specific load:
- One-to-one and group chats, with groups capped at 256 members. Groups multiply deliveries: one message to a group of 12 becomes 11 deliveries.
- Delivered and read receipts, the ticks under a message. Each recipient sends events back, so receipts can outnumber the messages themselves.
- Presence, the online dot. It needs periodic heartbeats (small frames that prove a connection is alive) and pushes to people who can see the dot; lesson 4 prices that.
- History on every device a user signs in on. Each connected device is one more connection, and a message must also reach the sender's other devices.
- Push notifications for recipients with no live connection, through Apple's or Google's push service.
Non-goals for version one: voice and video calls, message search, broadcast channels with thousands of members, and end-to-end encryption (lesson 4 points to it). The non-functional targets are also ours, set for this exercise. When both people are online, a message reaches the other screen within 500 ms at the 99th percentile. Every device shows a conversation in the same order. A message the server has acknowledged is first stored on several machines, so the failure of one server does not lose it. For scale, Slack's engineering team wrote in 2023 that its system delivers messages across the world in 500 ms; our target covers a single region.
03. Step 2: write the assumptions down
Each row is one input, with values for a light (best), expected and heavy (worst) case where we are unsure, and its basis. A row marked guess is a candidate for measurement in a beta.
Input best expected worst basis
daily active users 12 M 20 M 30 M forecast
hours a day a user is connected 1.5 3 6 guess
devices connected at once, per user 1.1 1.3 1.6 guess
busiest hour / average hour 2 2.5 3 guess
messages sent per user per day 25 40 80 guess
share of messages sent to groups 0.3 guess
recipients of a group message 11 guess
recipients connected when it lands 30% 40% 50% guess
receipts per recipient 2 (delivered and read) feature
heartbeat interval 30 s design
bytes stored per message 300 schema sketch
copies kept by our database 3 replication
connections one gateway holds 100,000 placeholder
frames per second one gateway handles 40,000 placeholder
gateway utilisation planned at peak 60% headroomThree rows need a word. Hours connected per day decides concurrency through Little's law, from the scalability lesson: the average number of users connected at once equals the rate at which they arrive times how long each one stays, which over a day is DAU × hours ÷ 24. The value depends on the platform mix. Android's Doze mode suspends network access for apps while the phone is idle, and Android's documentation recommends Firebase Cloud Messaging for real-time messages instead of a connection the app holds itself. So phones tend to hold a connection mainly while the app is in use, at least on Android, while a laptop client can stay connected for a whole working day. That is why the range runs from 1.5 to 6 hours.
Devices per connected user turns users into sockets: 1.3 means that three in ten connected users have a second device online at the same time. What one gateway can hold is a placeholder in two rows. An idle connection mostly costs memory (kernel buffers, TLS state, session data), while a busy one costs CPU for every frame, so the two limits are separate. Both depend on the runtime, the TLS library, kernel settings and the message mix, so they must come from a load test on your own stack. The model also leaves out attachments, edits, reactions, typing indicators and retries; each would add a row.
04. Step 3: the expected case by hand
Users connected, average 20 M x 3 h / 24 h = 2.5 M
Users connected, peak 2.5 M x 2.5 = 6.25 M
Connections, peak 6.25 M users x 1.3 devices ~ 8.1 M
Messages, peak 20 M x 40 / 86,400 s x 2.5 ~ 23,000/s
Recipients per message 0.7 x 1 + 0.3 x 11 = 4.0
Live deliveries, peak 23,000 x 4.0 x 0.4 x 1.3 + echo ~ 55,000/s
Heartbeat frames 8.1 M / 30 s x 2 (ping and pong) ~ 540,000/s
Storage per day 800 M messages x 300 B x 3 copies = 720 GBEcho is the copy each message sends to the sender's other connected devices, so that the laptop shows what the phone just sent: with 1.3 devices per user, that is 0.3 copies per message on average. Heartbeat frames count one ping and one pong per connection every 30 seconds; RFC 6455 §5.5.2 says that an endpoint receiving a Ping must answer with a Pong. Even at this rough level one line stands out: heartbeats are about ten times the live message deliveries.
05. Step 4: run all three cases
A script repeats the arithmetic for every case and for the what-if questions. Save it as chat_estimate.py; it needs only Python 3.12 and its standard library.
"""Back-of-the-envelope estimate for a chat service (Python 3.12, standard library)."""
import math
DAY_S = 86_400 # seconds in a day
GB, TB = 10**9, 10**12 # decimal units for storage
# Every input is an assumption for a made-up app. Units are in the names.
EXPECTED = {
"dau": 20_000_000, # daily active users
"connected_h": 3.0, # hours a day a user has at least one live connection
"devices": 1.3, # devices connected at once, per connected user
"peak_factor": 2.5, # busiest hour divided by the average hour
"msgs_per_user": 40, # messages sent per user per day
"group_share": 0.3, # share of messages sent to a group
"group_recipients": 11, # average recipients of a group message
"online_share": 0.4, # share of recipients connected when a message lands
"receipts": 2, # a delivered and a read receipt per recipient
"heartbeat_s": 30, # one ping and one pong per connection per interval
"stored_bytes": 300, # one stored message: text, ids and metadata
"replicas": 3, # copies kept by a database we run ourselves
"node_conns": 100_000, # connections one gateway holds: load-test it
"node_frames": 40_000, # frames per second one gateway handles: load-test it
"target_util": 0.6, # plan to run gateways at 60% of capacity at peak
}
SCENARIOS = {
"best": EXPECTED | {"dau": 12_000_000, "connected_h": 1.5, "devices": 1.1,
"peak_factor": 2.0, "msgs_per_user": 25, "online_share": 0.3},
"expected": EXPECTED,
"worst": EXPECTED | {"dau": 30_000_000, "connected_h": 6.0, "devices": 1.6,
"peak_factor": 3.0, "msgs_per_user": 80, "online_share": 0.5},
}
def estimate(a: dict) -> dict:
users_avg = a["dau"] * a["connected_h"] / 24 # Little's law: L = lambda x W
users_peak = min(a["dau"], users_avg * a["peak_factor"])
conns = users_peak * a["devices"]
sends = a["dau"] * a["msgs_per_user"] / DAY_S * a["peak_factor"]
recips = (1 - a["group_share"]) * 1 + a["group_share"] * a["group_recipients"]
live = sends * recips * a["online_share"] * a["devices"] # recipients' devices
echo = sends * (a["devices"] - 1) # copies to the sender's other devices
receipts = sends * recips * a["receipts"]
frames = {
"heartbeats": conns / a["heartbeat_s"] * 2,
"receipts in and out": receipts * 2, # from a recipient, on to the sender
"deliveries out": live + echo,
"sends in": sends,
}
total = sum(frames.values())
stored = a["dau"] * a["msgs_per_user"] * a["stored_bytes"] * a["replicas"]
return {
"users_peak": users_peak, "conns": conns, "sends": sends, "recips": recips,
"live": live + echo, "push": sends * recips * (1 - a["online_share"]),
"receipts": receipts, "frames": frames, "total": total,
"gb_day": stored / GB, "tb_year": stored * 365 / TB,
"by_conns": math.ceil(conns / (a["node_conns"] * a["target_util"])),
"by_frames": math.ceil(total / (a["node_frames"] * a["target_util"])),
}
ROWS = [
("connected users, peak", "users", "users_peak", ",.0f"),
("connections, peak", "sockets", "conns", ",.0f"),
("messages sent, peak", "msg/s", "sends", ",.0f"),
("recipients per message", "users", "recips", ".1f"),
("deliveries to live devices, peak", "frames/s", "live", ",.0f"),
("push notifications, peak", "pushes/s", "push", ",.0f"),
("receipts, peak", "events/s", "receipts", ",.0f"),
("gateway frames in and out, peak", "frames/s", "total", ",.0f"),
("stored per day, all replicas", "GB", "gb_day", ",.0f"),
("stored per year, all replicas", "TB", "tb_year", ",.0f"),
("gateways needed for connections", "nodes", "by_conns", ",d"),
("gateways needed for frames", "nodes", "by_frames", ",d"),
]
if __name__ == "__main__":
res = {name: estimate(a) for name, a in SCENARIOS.items()}
print(f"{'quantity (unit)':<44}" + "".join(f"{n:>12}" for n in res))
for label, unit, key, fmt in ROWS:
cells = "".join(f"{format(r[key], fmt):>12}" for r in res.values())
print(f"{label + ' (' + unit + ')':<44}{cells}")
e = res["expected"]
print("\nGateway frames at peak, expected case")
for kind, n in e["frames"].items():
print(f" {kind:<22}{n:>12,.0f} frames/s {n / e['total']:>6.0%}")
print("\nGateways needed (for connections / for frames) when one input changes")
changes = [
("no change", {}),
("heartbeat every 10 s", {"heartbeat_s": 10}),
("groups reach 40 recipients", {"group_recipients": 40}),
("receipts batched 4 into 1", {"receipts": 0.5}),
("connected hours doubled", {"connected_h": 6.0}),
]
for label, change in changes:
r = estimate(EXPECTED | change)
print(f" {label:<28}{r['by_conns']:>6,d} / {r['by_frames']:,d}")
lost = math.ceil(e["by_conns"] / 3) # the largest of three zones fails
load = e["conns"] / (e["by_conns"] - lost)
share = load / EXPECTED["node_conns"]
print(f"\nZone of {lost} gateways down: {e['by_conns'] - lost} left,"
f" {load:,.0f} connections each ({share:.0%} of capacity)")
limit = e["total"] / (e["by_conns"] * EXPECTED["target_util"])
print(f"Frames would bind if one gateway handled under {limit:,.0f} frames/s")python3.12 chat_estimate.pyquantity (unit) best expected worst
connected users, peak (users) 1,500,000 6,250,000 22,500,000
connections, peak (sockets) 1,650,000 8,125,000 36,000,000
messages sent, peak (msg/s) 6,944 23,148 83,333
recipients per message (users) 4.0 4.0 4.0
deliveries to live devices, peak (frames/s) 9,861 55,093 316,667
push notifications, peak (pushes/s) 19,444 55,556 166,667
receipts, peak (events/s) 55,556 185,185 666,667
gateway frames in and out, peak (frames/s) 237,917 990,278 4,133,333
stored per day, all replicas (GB) 270 720 2,160
stored per year, all replicas (TB) 99 263 788
gateways needed for connections (nodes) 28 136 600
gateways needed for frames (nodes) 10 42 173
Gateway frames at peak, expected case
heartbeats 541,667 frames/s 55%
receipts in and out 370,370 frames/s 37%
deliveries out 55,093 frames/s 6%
sends in 23,148 frames/s 2%
Gateways needed (for connections / for frames) when one input changes
no change 136 / 42
heartbeat every 10 s 136 / 87
groups reach 40 recipients 136 / 80
receipts batched 4 into 1 136 / 30
connected hours doubled 271 / 64
Zone of 46 gateways down: 90 left, 90,278 connections each (90% of capacity)
Frames would bind if one gateway handled under 12,136 frames/sThe connection count spans 1.65 to 36 million, a 22-fold range, because three uncertain inputs multiply. Even so, some decisions hold in every case. Every case needs dozens to hundreds of gateway servers, so the service needs a way to find which server holds a given user's connection; that is lesson 2. With these placeholder capacities, connections, not frames, set the gateway count in every case; frames would bind only if one gateway handled under about 12,100 frames per second. And at 270 GB to 2.2 TB of new data a day, counting the copies, a 10 TB disk would fill in 5 to 37 days, which shapes the storage design of lesson 4.
06. Step 5: read the breakdown and the what-ifs
The breakdown shows where gateway work goes. Heartbeats are 55% of all frames and receipts 37%; the messages people actually read are under a tenth. The receipt line is an upper bound, because it sends one event per receipt. Lesson 3 replaces them with marks such as read up to message 41, so that one event covers many messages.
The what-if rows answer the question if this input changes, what moves, and why? A 10-second heartbeat doubles the frame-based count from 42 to 87 gateways but leaves 136 unchanged, because the connections are the same. Groups that reach 40 recipients push the frame count to 80, still below 136. Doubling the hours connected doubles the connection-based count to 271. So the input to measure first in a beta is hours connected per user, split by platform: it is the least certain input, and it moves the number that decides the size of the tier.
The last line plans for failure. Suppose the 136 gateways are spread over three availability zones (separate data centres in one region) and the largest zone, 46 gateways, fails. The 90 survivors must then hold 8.1 million connections, about 90,300 each, or 90% of the assumed capacity. Planning to run at 60% at peak makes that survivable. And those 2.7 million clients do not come back politely: they reconnect at once, the reconnect storm of lesson 2.
07. Check your understanding
08. Apply it
Write the estimate section of this skill's practice design doc: a chat service with 50 million daily users and groups of up to 500 members. Copy chat_estimate.py and change the inputs: DAU, a group share and group size that fit your product (say why), and your own best and worst cases for hours connected and devices per user. Then report:
- peak connections, the gateways needed for connections and for frames, and which limit binds;
- the zone-loss line, and the utilisation target that keeps it below 100%;
- storage per day and per year, with the copies counted;
- the one input you would measure first in a beta, and how you would measure it.
09. Review prompt
Without looking back, answer in your own words:
- Why is the number of daily active users not the number of connections, and which inputs turn one into the other?
- Why can heartbeats outnumber message deliveries, and which change to the design would alter that?
- How do you decide whether connections or frames set the size of the gateway tier?
- What happens to the surviving gateways when one zone of three fails, and why does a 60% utilisation target help?
References
Your progress
Reading state
Sign in to save that you finished reading this lesson.
Prove this skill
6 questions · about 5 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.