In this lesson · topic 2 of 7
Topic 2
Requirements, numbers, API and data model
4 min read
Requirements
One-to-one and group chat. Messages show in the order the conversation had them. A message sent while the recipient is offline is there when they return. The sender sees sent, delivered and read marks. Other users can see who is online. History is kept and can be searched later.
State what you leave out. Media files, end-to-end encryption and push notifications to phones that have the app closed are each a lesson of their own.
Back of the envelope
These are assumptions for the exercise.
- 20 million daily users and 40 messages sent per user per day. That is 800 million messages a day, or about 9,300 a second.
- 5 million users connected at peak. A gateway server can hold about 100,000 idle connections if memory is the limit, so you need about 50 gateways plus spare capacity.
- A keepalive every 30 seconds on 5 million connections is about 170,000 small messages a second. This is the cost of presence.
- Messages of about 200 bytes make about 160 gigabytes a day. Storage grows for years, so plan to partition it.
The protocol and the API
Clients keep a persistent connection to a gateway. A WebSocket is a common choice, because it starts as an ordinary web request and then carries messages both ways. RFC 6455 defines it. Over the connection, the client sends send with a conversation id, a client-made message id and the text. The server sends message events.
For history and sync, use plain request calls: GET /conversations/{id}/messages?after=<seq> returns the messages after a sequence number.
The data model
- Messages, keyed by conversation id and then sequence number. A query for “after sequence N” is a range scan on one partition. See partitioning.
- Conversations: members and the latest sequence number.
- Per-user state: the last sequence number each user has read in each conversation. A read receipt is a write to this row.
- A session table, held in memory: which gateway each online user is connected to.