Case study: design a chat system
A senior-level walkthrough of a messenger: connections as the unit of capacity, one writer per conversation, idempotent sends and gap repair, receipts as watermarks, group fan-out by size, reconnect storms and storage, with tested C#.
Case studyApplied33 min readUpdated
- 1 architecture diagram
- 2 sequence flows
- 4 data models
- 2 API designs
- 10 code samples
- 8 interviewer follow-ups
- 1 decision checkpoint
- 1 capacity calculator
- 3 self-checks
On this page17 sectionsHLDLLDSenior depth
Read first: A framework for system design interviews, Load balancing, Replication and sharding, Queues and asynchronous work, Consistency and availability
- Treat connections, not requests, as the unit of capacity, and size the gateway tier and its keepalive traffic.
- Give every conversation one writer that assigns a sequence, and make sends idempotent with a client message ID.
- Repair loss, duplication and reordering on the client with a sequence number and a sync from the last one seen.
- Model receipts as per-member watermarks that merge with max, and choose fan-out by group size.
- Prevent reconnect storms with jitter and server-chosen return times, and answer the senior follow-ups.
9 code samples (284 lines), collapsed so the explanation stays in focus.
A chat system looks like a small web app with a socket. It is not. The unit of capacity is a connection, not a request: hundreds of millions of long-lived, mostly idle connections, each of which must receive a message within a second of it being sent, survive networks that drop, duplicate and reorder packets, and come back all at once when a server restarts. This lesson designs it the way a senior round would: the high-level design (HLD) first, then the low-level design (LLD) with tested C#, then the follow-ups an interviewer uses to push.
It builds on replication and sharding, queues and consistency, and its fan-out question is the mirror image of the news feed.
Spend the first minutes on questions. Each answer changes the design.
| Ask | Why it matters |
|---|---|
| One-to-one only, or groups? How large can a group be? | A group of five and a channel of fifty thousand are different designs: per-recipient delivery against per-gateway delivery |
| What must be ordered? | Within a conversation, everyone sees the same order. A global order is neither needed nor affordable, and timestamps from different devices cannot provide even the per-conversation one (see time, clocks and ordering) |
| What do "sent", "delivered" and "read" promise? | Receipts are a feature with real storage and fan-out cost, so decide how exact they must be |
| More than one device per user? | Each device needs its own cursor, and reading on one device must clear the others |
| What happens when the recipient is offline, and how long do we keep messages? | The log doubles as the mailbox, and retention sets the storage bill |
| Is it end-to-end encrypted? | The server then handles ciphertext only: no server-side search or content moderation, and every device has its own keys |
| Media, voice and video calls? | Media goes through object storage and a CDN, calls through separate signalling and media servers. Scope them out |
| Presence and typing indicators? | Cheap to ask for and expensive to build |
Functional: send and receive messages in one-to-one and group conversations, see history, receive messages sent while offline, see delivered and read state, use several devices. Non-functional: a message reaches an online recipient in well under a second, no message is lost once acknowledged, every member sees the same order, no duplicates, the service survives a deploy or a zone failure without an outage, and storage grows linearly. Out of scope: calls, media processing and search.
State assumptions out loud; they are illustrative and the interviewer may change them.
users: 500M daily users, 40 messages sent per user per day
messages: 500M x 40 = 20B a day = ~230,000/s, ~700,000/s at peak (x3)
connections: 40% of daily users online at peak = 200M concurrent
per gateway: 250,000 connections (about 20 KB of state each = 5 GB)
gateways: 200M / 250,000 = 800; with headroom, ~1,000
keepalives: 200M connections / 30 s = ~6.7M pings/s
storage: ~200 B per message x 20B = ~4 TB a day, ~1.5 PB a yearFour conclusions:
- The gateway tier is stateful and sized by connections and memory, not by requests. A tuned server can hold millions of connections (WhatsApp described about two million on one server in 2012), so 250,000 is conservative. What really limits the number is blast radius: the more connections a server holds, the bigger the reconnect storm when it dies or is restarted.
- Keepalives dominate the packet rate. 6.7 million pings a second against 230,000 messages a second is about 29 to 1. The interval trades battery, idle timeouts in NAT gateways and load balancers (which can drop a quiet connection after a few minutes), and how fast a dead connection is noticed.
- Phones restrict network use in the background. The operating system suspends or throttles an app that is not on screen, so those users are reached through the platform's push service (APNs, FCM), which is a hint to reconnect and sync, not the delivery path. The "concurrent" figure is mostly the foreground population plus desktop and web.
- Storage is append-only and read mostly from the newest end: 4 TB a day, a petabyte-scale year, so time bucketing and a retention policy are part of the design from day one.
Try other assumptions. The calculator counts messages and storage; the connection maths above (connections, gateways, keepalives) is separate, because here connections, not requests, are the unit of capacity.
Try it · capacity estimatorChat messages and storage
The live protocol is a handful of frames over one WebSocket per device. Everything that is not real-time (history, catch-up, the fallback when sockets are blocked) is plain HTTP.
| Frame | Direction | Carries | Meaning |
|---|---|---|---|
send | client to server | conversation, client_msg_id, body | Add this message to the conversation. The client chose the ID, so it can retry |
ack | server to client | client_msg_id, seq | Stored durably at this position. Safe to stop retrying |
message | server to client | conversation, seq, sender, body | A new message. The device applies messages in seq order |
receipt | both | conversation, delivered or read, up to seq | A watermark: everything up to this sequence has been delivered, or read |
sync | client to server | conversation, after_seq | I may have missed messages: send what follows this sequence |
ping and pong | both | nothing | Keepalive, and how a dead connection is noticed |
- auth
- bearer token
- query
- after_seq (catch up) or before_seq (scroll back), limit (default 50)
- note
- the same call serves reconnect catch-up, a second device's first sync, and scrolling back through history
- 200returns { "messages": [...], "last_seq": 4182 }
- auth
- bearer token
- idempotency
- client_msg_id in the body, a retry with the same ID returns the same message
- body
- { "client_msg_id": "…", "body": "…" }
- note
- the fallback for networks that block WebSockets
- 201stored, returns { "seq": 4183 }
Messages are read as "the newest page of this conversation", so the partition key is the conversation plus a time bucket, and the clustering key is the sequence. Receipts are two numbers per member rather than a row per message.
conversation_idbigint
with bucket, the partition key
PKSHARD KEYbucketint
a time window, so one partition cannot grow without bound
PKSHARD KEYseqbigint
clustering key, newest first inside a bucket
PKsender_idbigint
client_msg_iduuid
lets the writer recognise a retry
bodyblob
ciphertext in an end-to-end encrypted system
created_attimestamptz
"The latest 50 messages" reads one partition. Retention drops whole buckets.
conversation_idbigint
PKSHARD KEYkindsmallint
direct, group or channel
last_seqbigint
highest sequence assigned; a new owner continues from it
owner_epochbigint
bumped when ownership moves; the log rejects older epochs
last_bucketint
where the newest messages live, so a quiet chat does not scan empty buckets
conversation_idbigint
PKSHARD KEYuser_idbigint
PKdelivered_seqbigint
watermark: everything up to here reached one of the user's devices
read_seqbigint
watermark: everything up to here has been read
user_idbigint
PKSHARD KEYdevice_idtext
PKgatewaytext
which gateway holds this device's connection now
expires_attimestamptz
refreshed by heartbeats, so a crashed gateway's entries expire on their own
Read it as a log with a front door. A gateway terminates the connection and forwards send to the conversation's owner. The owner appends to the durable log, acknowledges, and hands the stored message to delivery, which finds each recipient's gateways in the session registry and pushes to them. Anyone who is not connected is woken by the platform push service (sending those pushes reliably is the job of a notification service) and catches up by syncing from the last sequence they hold. The log is the source of truth, and the live connection is only a faster way to read it.
Everyone in a conversation must see the same order, and the order must survive retries, failovers and partitions. There are only a few ways to decide it. Before the table, pick one.
Decision checkpoint · pick one
Two people in a group chat send a message at the same instant, and their messages reach two different servers. Everyone must see the same order, now and after a reload. How do you decide the order?
Commit to an answer first. The reasoning for every option appears after you pick.
| Approach | How the order is decided | Weakness |
|---|---|---|
| Client timestamps | The sender's clock | Clocks disagree, and a client can lie |
| Server timestamps | Whichever server received it first | Two servers, two clocks; ties; skew between data centres |
| A counter in the database row | last_seq + 1 in a transaction | Fine at moderate scale; a hot row for a huge group; slow across regions |
| One owner per conversation | The owner increments a counter backed by a replicated log | Failover must guarantee that two owners never both write |
| Per-sender sequences merged later | Vector clocks, or a graph of events | Needed when there is no single owner (peer-to-peer, federated systems such as Matrix); much harder to display and to reason about |
Choose the owner. Place each conversation on a sequencer node by consistent hashing of its ID. The owner holds the next sequence number and a window of recent client message IDs in memory, backed by a replicated log, and acknowledges only after the write is durable. Two properties must hold.
- An idempotent append. If the ack is lost, the client retries with the same
client_msg_id. The log recognises it and returns the sequence it already assigned. The dedupe record must be written atomically with the message, and kept longer than any client will keep retrying. - Fencing. An owner can lose ownership without knowing it: a long garbage-collection pause, a network partition. A lease alone does not help, because the paused node wakes up believing it still holds it. The fix is the fencing token from Kleppmann's essay on distributed locks. Every change of owner bumps an epoch, every append carries the epoch, and the log rejects any append from an epoch older than one it has seen. The zombie's write fails instead of creating a second message with the same sequence.
C# · Message, AppendResult, ConversationLog
using System;
using System.Collections.Generic;
using System.Linq;
public readonly record struct Message(string ConversationId, long Seq, string Sender, string ClientMsgId, string Body);
public readonly record struct AppendResult(bool Accepted, long Seq, bool Duplicate);
public sealed class ConversationLog
{
private readonly string _id;
private readonly List<Message> _messages = new List<Message>(); // index = seq - 1
private readonly Dictionary<string, long> _seqOf = new Dictionary<string, long>(); // "sender/clientMsgId" -> seq
private long _epoch; // the highest owner epoch that has written
public ConversationLog(string id) { _id = id; }
public long LastSeq => _messages.Count;
public AppendResult Append(long ownerEpoch, string sender, string clientMsgId, string body)
{
if (ownerEpoch < _epoch) return new AppendResult(false, 0, false); // a former owner is fenced off
_epoch = ownerEpoch;
string key = sender + "/" + clientMsgId;
if (_seqOf.TryGetValue(key, out long existing)) return new AppendResult(true, existing, true); // a retry
long seq = _messages.Count + 1; // in production: written atomically with the dedupe key
_messages.Add(new Message(_id, seq, sender, clientMsgId, body));
_seqOf[key] = seq;
return new AppendResult(true, seq, false);
}
public Message Get(long seq) => _messages[(int)seq - 1];
/// <summary>Messages after `afterSeq`, oldest first: what a device asks for on reconnect, or when it finds a gap.</summary>
public IReadOnlyList<Message> After(long afterSeq, int limit) => _messages.Skip((int)afterSeq).Take(limit).ToList();
}C#
using System.Diagnostics;
var room = new ConversationLog("room-1");
var first = room.Append(ownerEpoch: 1, "ann", "a-1", "hello");
var second = room.Append(1, "bo", "b-1", "hi ann");
var retry = room.Append(1, "ann", "a-1", "hello"); // the ack was lost, so ann sent it again
Debug.Assert(first.Seq == 1 && second.Seq == 2, "one writer hands out 1, 2, 3 ... with no gaps");
Debug.Assert(retry.Accepted && retry.Duplicate && retry.Seq == 1 && room.LastSeq == 2, "a retry returns the same position and adds nothing");
var takenOver = new ConversationLog("room-2");
takenOver.Append(ownerEpoch: 1, "ann", "a-1", "from the first owner");
takenOver.Append(2, "bo", "b-1", "from the new owner"); // ownership moved: epoch 2
var zombie = takenOver.Append(1, "ann", "a-2", "from a paused node that thinks it is still the owner");
Debug.Assert(!zombie.Accepted && takenOver.LastSeq == 2, "an older epoch is rejected, so no sequence number is ever used twice");
var tail = room.After(afterSeq: 1, limit: 10);
Debug.Assert(tail.Count == 1 && tail[0].Seq == 2, "after(1) returns what follows message 1");Networks drop, duplicate and reorder. The answer is small. The server stamps every message with its sequence; the client only shows messages in sequence, holds early ones back, ignores ones it already has, and asks for the missing range. The server need not track what each device has, because the device carries its own cursor.
C# · ChatClient
using System.Collections.Generic;
public sealed class ChatClient
{
private readonly SortedDictionary<long, Message> _early = new SortedDictionary<long, Message>(); // arrived before a gap was filled
public long LastSeq { get; private set; } // everything up to here is shown, in order
public List<Message> Shown { get; } = new List<Message>();
/// <summary>Takes one pushed message. Returns true while something is waiting behind a gap.</summary>
public bool OnPush(Message message)
{
if (message.Seq <= LastSeq) return _early.Count > 0; // a duplicate: already shown
_early[message.Seq] = message;
while (_early.TryGetValue(LastSeq + 1, out var next))
{
_early.Remove(next.Seq);
Shown.Add(next);
LastSeq = next.Seq;
}
return _early.Count > 0;
}
public void OnSync(IEnumerable<Message> missed)
{
foreach (var message in missed) OnPush(message);
}
}C# · 1,200 messages from three senders, pushed over a network that loses 10%, duplicates 10%…
// 1,200 messages from three senders, pushed over a network that loses 10%, duplicates 10% and reorders.
var network = new Random(42);
var conversation = new ConversationLog("room-3");
string[] senders = { "ann", "bo", "cy" };
var pushes = new List<Message>();
for (int i = 0; i < 1_200; i++)
{
string sender = senders[i % 3];
var stored = conversation.Append(ownerEpoch: 1, sender, clientMsgId: sender + "-" + (i / 3), body: "message " + i);
pushes.Add(conversation.Get(stored.Seq));
}
var wire = new List<Message>();
foreach (var message in pushes)
{
if (network.NextDouble() < 0.10) continue; // lost
wire.Add(message);
if (network.NextDouble() < 0.10) wire.Add(message); // delivered twice
}
for (int i = 0; i + 1 < wire.Count; i++) // a message may overtake one a few places ahead
{
int j = Math.Min(wire.Count - 1, i + network.Next(0, 5));
(wire[i], wire[j]) = (wire[j], wire[i]);
}
var phone = new ChatClient();
int syncRequests = 0, processed = 0;
foreach (var message in wire)
{
bool waiting = phone.OnPush(message);
processed++;
if (waiting && processed % 25 == 0) // ask for the missing range now and then, not on every packet
{
syncRequests++;
phone.OnSync(conversation.After(phone.LastSeq, limit: 100));
}
}
while (phone.LastSeq < conversation.LastSeq) // on the next connect the device syncs once more, as many times as needed
{
syncRequests++;
phone.OnSync(conversation.After(phone.LastSeq, limit: 100));
}
Debug.Assert(phone.Shown.Select(m => m.Seq).SequenceEqual(Enumerable.Range(1, 1_200).Select(i => (long)i)), "every message once, in order");
Debug.Assert(phone.Shown.Select(m => m.Body).SequenceEqual(conversation.After(0, 1_200).Select(m => m.Body)), "and identical to the server's log");
Debug.Assert(syncRequests > 0 && syncRequests < 100, "gap repair costs a few range requests, not one per lost message");At-least-once delivery from the server, plus idempotent handling on the client, gives the effect of exactly-once display, without a per-message acknowledgement from every recipient. Sync runs on connect, when the app returns to the foreground, after a gap that does not fill itself, and as a slow background check.
Receipts are watermarks
"Delivered" and "read" look like per-message state, but they are not stored that way. A device says "I have read everything up to sequence 4183". That is one number per member, it only moves forward, and merging two of them is max. Because max is commutative, associative and idempotent, receipts can arrive late, twice, or out of order, and every replica still converges.
C# · Status, ReadMarkers
using System.Collections.Generic;
using System.Linq;
public enum Status { Sent, Delivered, Read }
public sealed class ReadMarkers
{
private readonly Dictionary<string, long> _delivered = new Dictionary<string, long>();
private readonly Dictionary<string, long> _read = new Dictionary<string, long>();
/// <summary>A delivered watermark. Merging is max, so order and repeats do not matter.</summary>
public void Delivered(string user, long upToSeq) => _delivered[user] = Math.Max(_delivered.GetValueOrDefault(user), upToSeq);
/// <summary>A read watermark. Reading something implies it was delivered.</summary>
public void Read(string user, long upToSeq)
{
_read[user] = Math.Max(_read.GetValueOrDefault(user), upToSeq);
Delivered(user, upToSeq);
}
/// <summary>The ticks the sender sees for one message: the least advanced recipient decides.</summary>
public Status StatusOf(long seq, IEnumerable<string> recipients)
{
var members = recipients.ToList();
if (members.All(u => _read.GetValueOrDefault(u) >= seq)) return Status.Read;
if (members.All(u => _delivered.GetValueOrDefault(u) >= seq)) return Status.Delivered;
return Status.Sent;
}
}C#
var updates = new (string User, bool IsRead, long UpTo)[]
{
("bo", false, 5), ("cy", false, 10), ("bo", true, 3), ("cy", true, 10), ("bo", false, 8), ("bo", false, 2), ("cy", false, 4),
};
string[] groupMembers = { "bo", "cy" };
ReadMarkers ApplyAll(IEnumerable<(string User, bool IsRead, long UpTo)> sequence)
{
var markers = new ReadMarkers();
foreach (var update in sequence)
{
if (update.IsRead) markers.Read(update.User, update.UpTo); else markers.Delivered(update.User, update.UpTo);
}
return markers;
}
string TicksOf(ReadMarkers markers) => string.Join(",", Enumerable.Range(1, 12).Select(seq => markers.StatusOf(seq, groupMembers)));
string expectedTicks = TicksOf(ApplyAll(updates));
bool sameForEveryOrder = true;
var shuffler = new Random(3);
for (int trial = 0; trial < 200; trial++)
{
var shuffled = updates.Concat(updates.Take(3)).OrderBy(_ => shuffler.Next()).ToList(); // reordered, and three of them delivered twice
sameForEveryOrder &= TicksOf(ApplyAll(shuffled)) == expectedTicks;
}
Debug.Assert(sameForEveryOrder, "reordered and repeated receipts converge to the same ticks");
var markersNow = ApplyAll(updates);
Debug.Assert(markersNow.StatusOf(3, groupMembers) == Status.Read, "bo read up to 3 and cy up to 10");
Debug.Assert(markersNow.StatusOf(5, groupMembers) == Status.Delivered, "both received it, but bo has not read it");
Debug.Assert(markersNow.StatusOf(9, groupMembers) == Status.Sent, "bo's device has only confirmed up to 8");Why watermarks win: a 500-member group with 1,000 messages a day would need 500,000 per-message receipts a day, against 500 numbers that change when someone opens the chat. A device sends "read up to N" once when the conversation is opened, not once per message. For several devices, a user's delivered watermark is the maximum over their devices, and the read watermark is shared, so reading on a laptop clears the phone.
The gateway tier terminates TLS and the WebSocket, holds the per-connection state, and registers (user, device) → gateway in the registry with a TTL refreshed by heartbeats, so a crashed gateway's entries expire by themselves. The load balancer works at the connection level and balances by least connections, because connection lifetimes are long and uneven. Any gateway can serve any user.
Finding the recipients has two shapes.
| Model | How a message finds its recipients | Good for | Cost |
|---|---|---|---|
| Per-recipient lookup | Read each member's devices from the registry and send to each gateway | One-to-one chats and groups up to a few hundred | One registry read and one hop per recipient device |
| Per-conversation subscription | Gateways subscribe to the conversations their users are in; the owner publishes once to each subscribed gateway, which fans out locally | Large groups and channels | Subscription state (gateway × conversation) and its churn on joins and leaves |
Slack's published design is the second model: gateway servers hold the WebSockets and subscribe to channel servers, and channels are placed on channel servers with consistent hashing.
Groups by size. The message is stored once, whatever the group size, and the per-member state is the two watermarks. Small groups use per-recipient delivery. Large channels use subscriptions, send push notifications for mentions only, and replace per-message receipts with counts or nothing. This is the opposite of the news feed, where every follower gets a copy of the post ID in a personal list because each feed is different. In chat every member reads the same ordered log, so there is one log and a cursor per member.
Presence and typing indicators. Presence is derived from connections: a user is online when any of their devices has a live registry entry, and last seen is written when the last one goes. The cost is amplification: a user with 500 contacts who flips offline and online on a flaky mobile network causes 1,000 notifications. Subscribe to presence only for contacts that are on screen, wait a short grace period before announcing "offline", round last seen to the minute, and drop presence entirely in large groups. Typing indicators are ephemeral: never stored, rate limited to one every few seconds, and expired by a timer on the client.
A deploy, a load balancer failure or the loss of a zone disconnects a large share of the fleet at once, and every client retries. If the retries are synchronized, the servers face the same surge again and again, and the system stays down although every machine is healthy.
Suppose a gateway fleet can admit 5,000 new connections a second (each admission costs a TLS handshake, authentication and a registry write), and 100,000 clients lose their connection at the same instant. Three retry policies:
- Exponential backoff, no jitter. Wait 1, 2, 4 ... seconds, up to a cap of 30. All clients that failed together retry together.
- Full jitter. Wait a random time between zero and the same exponential window (the approach in Marc Brooker's AWS article on backoff and jitter).
- Server-chosen return times. The server knows its capacity, so a refusal carries a time to come back: the next second with a free admission slot.
C# · Backoff, ReconnectStorm
using System;
public enum Backoff { Exponential, FullJitter, ServerChosen }
public static class ReconnectStorm
{
/// <summary>
/// All clients lose their connection at second 0. Each second the fleet admits `admitPerSecond` attempts and refuses the rest.
/// Returns the total attempts (the wasted work lands on the servers) and the seconds until everyone is connected.
/// </summary>
public static (int Attempts, int SecondsToAllConnected) Run(Backoff policy, int clients, int admitPerSecond, int seed)
{
const int BaseSeconds = 1, CapSeconds = 30, Horizon = 4_000;
var random = new Random(seed);
var nextAttempt = new int[clients];
var failures = new int[clients];
var reserved = new int[Horizon]; // admission slots already promised, for server-chosen times
int frontier = 0, connected = 0, attempts = 0, second = 0;
for (; connected < clients && second < Horizon - 1; second++)
{
int admitted = 0;
for (int c = 0; c < clients; c++)
{
if (nextAttempt[c] != second) continue;
attempts++;
if (admitted < admitPerSecond) { admitted++; connected++; nextAttempt[c] = -1; continue; }
failures[c]++;
int window = Math.Min(CapSeconds, BaseSeconds << Math.Min(failures[c] - 1, 10));
switch (policy)
{
case Backoff.Exponential: nextAttempt[c] = second + window; break;
case Backoff.FullJitter: nextAttempt[c] = second + 1 + random.Next(window); break;
default:
frontier = Math.Max(frontier, second + 1);
while (reserved[frontier] >= admitPerSecond) frontier++;
reserved[frontier]++;
nextAttempt[c] = frontier;
break;
}
}
}
return (attempts, second);
}
}var synchronized = ReconnectStorm.Run(Backoff.Exponential, clients: 100_000, admitPerSecond: 5_000, seed: 7);
var jittered = ReconnectStorm.Run(Backoff.FullJitter, 100_000, 5_000, seed: 7);
var directed = ReconnectStorm.Run(Backoff.ServerChosen, 100_000, 5_000, seed: 7);
Debug.Assert(synchronized.Attempts == 1_050_000, "synchronized retries: twenty waves, each wasting everyone who was refused");
Debug.Assert(synchronized.SecondsToAllConnected >= 440 && synchronized.SecondsToAllConnected <= 460, "and it takes minutes (452 s), because each wave waits out a longer backoff");
Debug.Assert(jittered.Attempts > 440_000 && jittered.Attempts < 490_000, "jitter spreads the retries: about 464,000 attempts");
Debug.Assert(jittered.SecondsToAllConnected >= 40 && jittered.SecondsToAllConnected <= 50, "and the fleet finishes in about 44 s, close to the 20 s minimum");
Debug.Assert(directed.Attempts == 195_000 && directed.SecondsToAllConnected == 20, "told when to return, each client tries exactly twice and the fleet finishes at its minimum, 100,000 / 5,000");
Debug.Assert(Math.Round(200_000_000.0 / 3 / 300 / 667) == 333, "losing one of three zones: about 333 admissions a second on each surviving gateway to recover in five minutes");Without jitter, the retry traffic is 1,050,000 attempts for 100,000 clients and the fleet needs about 452 seconds. With full jitter, about 464,000 attempts and 44 seconds. With server-chosen return times, 195,000 attempts (two per client) and 20 seconds, which is the physical minimum. Always add jitter; when the server can name a return time, name it.
Sizing for the correlated failure, not the single gateway: one gateway dying sends 250,000 clients to 999 others, about 250 each, and nobody notices. Losing one of three zones sends 67 million clients to about 667 gateways. To be back in five minutes they must admit 222,000 connections a second, about 333 each, and every admission costs a handshake, authentication, a registry write and a sync. That arithmetic, not the kernel's connection limit, sets the gateway count and the headroom.
For deploys, drain gradually: tell a few percent of the fleet at a time to reconnect over a window with a random offset, and never restart a whole zone together. TLS session resumption makes reconnects cheaper. Ship the reconnect policy as configuration the server can change, so the server can slow clients down during an incident.
A partition is the unit of storage and of load. If it holds a whole conversation, a busy channel grows without bound and becomes both a huge and a hot partition. The usual fix is to partition by conversation and a time bucket. Discord's published message schema has this shape, with the primary key ((channel_id, bucket), message_id) and buckets sized so that the biggest channels stay under roughly 100 MB per partition. Time bucketing has two more benefits: "the latest page" is one partition read for any busy conversation, and retention becomes dropping whole old buckets, instead of millions of per-message deletes, which are expensive in stores that write tombstones.
The cost is on the quiet end. The newest 50 messages of a conversation that has been silent for years are found by walking buckets backwards, one query each, until enough messages are found.
C# · BucketedMessages
using System.Collections.Generic;
public sealed class BucketedMessages
{
private readonly long _bucketMs;
private readonly Dictionary<(long Conversation, long Bucket), List<long>> _partitions = new Dictionary<(long, long), List<long>>();
private int _reads;
public BucketedMessages(long bucketMs) { _bucketMs = bucketMs; }
private long BucketOf(long ms) => ms / _bucketMs;
public void Append(long conversation, long messageId, long atMs)
{
var key = (conversation, BucketOf(atMs));
if (!_partitions.TryGetValue(key, out var list)) _partitions[key] = list = new List<long>();
list.Add(messageId); // IDs rise with time, so each partition is in order
}
/// <summary>Partition queries made since the last call.</summary>
public int TakeReads() { int n = _reads; _reads = 0; return n; }
/// <summary>The newest `count` messages, walking buckets backwards from `startMs` until the conversation began.</summary>
public List<long> Latest(long conversation, int count, long startMs, long createdMs)
{
var result = new List<long>();
for (long bucket = BucketOf(startMs); bucket >= BucketOf(createdMs) && result.Count < count; bucket--)
{
_reads++; // one query to one partition, whether or not it holds anything
if (!_partitions.TryGetValue((conversation, bucket), out var list)) continue;
for (int i = list.Count - 1; i >= 0 && result.Count < count; i--) result.Add(list[i]);
}
return result;
}
}C#
const long DayMs = 86_400_000;
var history = new BucketedMessages(bucketMs: 10 * DayMs);
long today = 5 * 365 * DayMs; // the conversations are five years old
for (int i = 0; i < 30; i++) history.Append(conversation: 1, messageId: i + 1, atMs: i * DayMs / 2); // a quiet chat: 30 messages in its first 15 days
for (int i = 0; i < 1_000; i++) history.Append(conversation: 2, messageId: 10_000 + i, atMs: today - 3 * DayMs + i * 1_000); // a busy chat
var busyLatest = history.Latest(2, count: 50, startMs: today, createdMs: 0);
int busyReads = history.TakeReads();
var quietWalk = history.Latest(1, count: 50, startMs: today, createdMs: 0);
int quietWalkReads = history.TakeReads();
var quietDirect = history.Latest(1, count: 50, startMs: 29 * DayMs / 2, createdMs: 0); // start at the newest message's bucket instead
int quietDirectReads = history.TakeReads();
Debug.Assert(busyLatest.Count == 50 && busyReads == 1, "a busy chat: one partition read");
Debug.Assert(quietWalk.Count == 30 && quietWalkReads == 183, "a quiet chat: 183 queries, almost all of them empty");
Debug.Assert(quietDirect.Count == 30 && quietDirectReads == 2, "starting from the last bucket in use, two");The fix is a pointer: the conversation row records last_bucket (or the last message ID, from which the bucket follows), so the walk starts where the data is. That is why it sits in the model above.
With end-to-end encryption the server routes ciphertext and cannot read it. The design consequences are worth saying aloud, because they are the usual "now add E2EE" follow-up.
- Every device has its own keys. A message to a user with three devices is encrypted for each of the three, and the sender needs the recipient's device list. Group designs often use a per-sender group key so a message is encrypted once for the group rather than once per member.
- The server loses features that need content: search, link previews, automatic moderation and spam classification on text. Search moves onto the device. Abuse handling moves to metadata (rates, reports, account behaviour) and to reports that users choose to send.
- A new device cannot read history by asking the server. It needs a key transfer from an existing device or an encrypted backup.
- Push notifications carry little. The payload is a wake-up, or ciphertext that an extension on the phone decrypts.
- The sequence and the log are unchanged. Ordering, idempotency, gap repair and receipts are metadata, not content, so everything above still applies.
Signal's published specifications describe the Double Ratchet, which derives new keys for every message, and Sesame, its session management for multiple devices.
| Case | What goes wrong | Response |
|---|---|---|
| A gateway dies, or a deploy restarts many | Clients reconnect at once and overload the fleet | Jitter, server-chosen return times, admission limits, gradual drains |
| The ack is lost | The sender retries and the message duplicates | client_msg_id makes the append idempotent |
| A push notification is lost | The recipient does not know there is a message | Push is a hint only. Devices sync from their cursor on connect, on foreground and periodically |
| A zombie owner keeps writing | Two messages get the same sequence | Epoch fencing in the log |
| The registry entry is stale | A message goes to a gateway the device left | The gateway answers "not here"; delivery falls back to the offline path (push, then sync); entries expire by TTL |
| A huge group goes viral | One owner node and one partition saturate | Time-bucketed partitions, subscription fan-out, slow mode and rate limits, receipts reduced to counts |
| Clock skew between servers or clients | Messages appear out of order | Never order by wall clock. The sequence is the order and timestamps are for display |
| A bot floods a conversation | Fan-out amplification | Per-sender rate limits, group size caps, abuse signals on metadata |
| Region failure with asynchronous replication | The last acknowledged messages are lost | Replicate the log synchronously inside a region; accept the region-loss window explicitly, or pay for cross-region quorum |
| A malformed message crashes a parser | A crash loop on every gateway that receives it | Size and schema limits at the edge, isolation of parsing, a dead-letter path |
Interviewer follow-upL5How do you guarantee a message is neither lost nor duplicated?How to answer
Say what is achievable: at-least-once delivery with idempotent handling, which gives effectively-once results. The sender retries with a stable client_msg_id until it sees an ack, and the log turns a retry into the same sequence. The server pushes with sequences, and the client ignores anything at or below its last sequence, buffers early arrivals and syncs a missing range. The log is replicated before the ack, so an acknowledged message survives the loss of a node.
Interviewer follow-upL5WebSockets, long polling or something else?How to answer
A WebSocket for foreground clients, because it gives low latency in both directions on one connection. Long polling or server-sent events as fallbacks for networks and proxies that block upgrades. The platform push service (APNs, FCM) for backgrounded phones, as a wake-up that triggers a sync. Mobile-oriented protocols such as MQTT are a legitimate choice for constrained devices. In every case the real protocol is the sequence and the sync, so the transport can change underneath it.
Interviewer follow-upL6Two members send at the same instant. Who is first?How to answer
Whichever the conversation's owner appends first, and everyone then sees that order, because the owner assigns the sequence. The sender's own screen shows its message at once (optimistic), then settles into the position the ack reports. Timestamps are display data only. If the product needs "sent" times to look right, show the owner's receive time.
Interviewer follow-upL6A deploy restarts every gateway. How do you avoid an outage?How to answer
Drain, do not kill. Mark a few percent of the fleet as draining, tell their clients to reconnect over a window with a random offset, wait until they are gone, then restart. Keep admission control on the receiving side, so a fast reconnect cannot exceed the handshake budget, and send server-chosen return times when refusing. Never restart a whole zone together. Practise the zone-loss case, because the recovery rate is arithmetic you can check in advance.
Interviewer follow-upL6How do you show "seen by 37" in a group of 100?How to answer
Read watermarks per member. A message is seen by member M if its sequence is at or below M's read watermark, so the count is a pass over the members' numbers, not a table of per-message receipts. For large groups, compute it on demand, cache it for a few seconds, or show nothing past a size threshold.
Interviewer follow-upL7Run this active-active in two regions. What breaks?How to answer
Ordering. A single owner per conversation means one region owns it, and writers in the other region pay a round trip to the owner, which for two people in different regions is one extra latency and acceptable. Pick the home region by where most members are, move ownership with an epoch bump if the members move, and fail over with fencing. The alternative, accepting writes in both regions and merging later, needs per-sender sequences and a deterministic merge, which is how systems without a single owner work, at the cost of a harder user experience (messages that jump position). Say that you choose strong per-conversation ordering and take the latency.
Interviewer follow-upL7Add end-to-end encryption. What changes, and what does not?How to answer
Content features move to the devices (search, previews), abuse handling moves to metadata and user reports, and each device needs its own keys with a key directory as the trust anchor. A message is encrypted per recipient device, or once per group with a per-sender key. Ordering, idempotent appends, gap repair, receipts, fan-out and the reconnect behaviour are all about metadata, so none of that changes.
Interviewer follow-upL7Cut the connection fleet's cost in half. Where do you look?How to answer
Keepalives and memory per connection first: adaptive heartbeat intervals (longer on a stable network, shorter when a NAT is known to drop idle flows), compact per-connection state, and fewer idle foreground connections by letting clients disconnect after a period of inactivity and rely on push to wake them. Then the headroom: raise connections per gateway only as far as the reconnect arithmetic for the largest correlated failure allows. Name what each saving costs in latency or recovery time.
- Clarify: groups and their maximum size, what is ordered, what receipts promise, devices, offline, encryption.
- Estimate: connections as the unit of capacity, keepalives against messages, blast radius.
- Contract and model: a few frames,
client_msg_id, sequence, watermarks, bucketed partitions. - Draw it: gateways, session registry, a conversation owner with a replicated log, delivery, push.
- Go deep on ordering: one owner, idempotent append, epoch fencing, then the client's gap repair.
- Receipts and groups: watermarks, one stored copy, delivery by group size.
- Operate it: reconnect storms with jitter and server-chosen times, drains, the zone-loss arithmetic.
- Name the failure modes and follow-ups: lost acks and pushes, zombie owners, hot groups, regions, encryption.
A chat system is a replicated log per conversation, ordered by a single owner that is fenced by an epoch, with idempotent appends keyed by a client message ID. Devices hold a cursor, show messages in sequence, buffer early ones and sync the missing range, so loss, duplication and reordering are repaired on the client. Receipts are watermarks merged with max. A message is stored once, delivered per recipient for small groups and per subscribed gateway for large ones. Capacity is measured in connections, the dangerous event is the correlated reconnect, and the defences are jitter, server-chosen return times and gradual drains. Storage is partitioned by conversation and time bucket, with a pointer to the newest bucket.
Try answering out loud before you reveal each answer.
QuestionA send's ack is lost and the client retries. Why is there no duplicate, and where must the dedupe record live?Reveal answer
The client chose a client_msg_id, and the log keeps a map from sender and ID to the sequence it assigned, so a retry returns the same sequence and adds nothing. The record must be written atomically with the message, in the same durable write, and kept longer than any client will keep retrying. If it lived only in the owner's memory, a failover would forget it and the retry would duplicate the message.
QuestionTwo members send at the same instant. What decides the order everyone sees, and why not timestamps?Reveal answer
The conversation's single owner assigns consecutive sequence numbers as it appends, and every device shows messages in that order. Timestamps come from clocks that disagree, and ties and skew would give different members different orders. The sequence also lets a device notice a gap, which timestamps cannot.
QuestionA zone failure disconnects 100,000 clients at once, and they retry with exponential backoff and no jitter. What happens, and what fixes it?Reveal answer
They stay synchronized: every retry wave arrives together, the fleet admits only its capacity each time, and the rest retry together again. In the simulation that was 1,050,000 attempts and about 452 seconds for 100,000 clients admitted at 5,000 a second. Full jitter spreads the retries (about 464,000 attempts, 44 seconds), and server-chosen return times reach the minimum (195,000 attempts, 20 seconds).
- Rick Reed, Scaling to Millions of Simultaneous Connections (opens in a new tab), Erlang Factory San Francisco 2012: WhatsApp's account of reaching about two million connections on one server, mostly by removing contention.
- Discord Engineering, How Discord Stores Billions of Messages (opens in a new tab) (2017) and How Discord Stores Trillions of Messages (opens in a new tab) (2023): the partition key by channel and time bucket, hot partitions, and the move to ScyllaDB.
- Slack Engineering, Real-time Messaging (opens in a new tab): gateway servers holding WebSockets, and channel servers placed by consistent hashing.
- Martin Kleppmann, How to do distributed locking (opens in a new tab), 2016: why a lease needs a fencing token.
- Marc Brooker, Exponential Backoff And Jitter (opens in a new tab), AWS Architecture Blog: the case for jitter, with simulations.
- Signal, The Double Ratchet Algorithm (opens in a new tab) and the Sesame specification for multi-device session management, from the Signal technical documentation (opens in a new tab).