System Design · Worked case study
Designing a Reliable Chat System
Design a privacy-aware chat service whose small first version can grow into synchronized, multi-device conversations without claiming instant delivery or perfect global ordering.
Written for readers who already know the basics. If the words here are new to you, read The request lifecycle and Capacity estimation first.
Original educational architecture · Version 2026-11-12.1 · Examples use stated hypothetical assumptions, not a company's actual design.
What you will be able to explain
- Estimate message, connection, storage, and fanout load with explicit units and headroom.
- Explain durable acceptance, device synchronization, delivery acknowledgement, deduplication, and ordering boundaries.
- Evolve a monolith into regional realtime gateways and durable message workflows while preserving privacy and recoverability.
Define what chat means
Start with a bounded product: private one-to-one and groups of up to 100 members, text messages, read receipts that can be disabled, and up to five registered devices per account. A sender should see a durable accepted response quickly, and an online recipient should usually see the message within a few seconds. Offline recipients catch up when they reconnect. Do not promise exactly-once network delivery, globally ordered messages, or that a delivery receipt means a person read the content; networks retry and devices disappear. Assume 2 million monthly users, 300,000 daily users, and 60,000 concurrent connections at launch. Exclude voice/video calls, public channels, end-to-end encryption in the first release, search across message bodies, and cross-conversation ordering. Those exclusions avoid quietly turning a messaging service into a media or discovery platform. Define explicit privacy behavior: conversation membership is checked on every read and send, removed members cannot fetch later content, and retention is configurable. Product decisions about server-side plaintext must be disclosed. A later encrypted design changes moderation, search, backups, and device recovery, so it cannot be claimed as a transparent implementation detail.
- Accepted means the server durably recorded the message and assigned its conversation sequence.
- Delivered means one or more recipient devices acknowledged receipt; read is a separate user-visible signal.
- Initial target: 99.9% monthly successful send acceptance, excluding invalid requests and client connectivity.
Estimate traffic before choosing components
Use workload arithmetic to establish orders of magnitude, then measure real distributions. Suppose 300,000 daily active users each send 40 messages per day: 12 million messages daily, or about 139 messages per second averaged across 86,400 seconds. A 12× evening peak is 1,668 accepted messages per second. At 1.6 KiB average stored message payload including metadata, raw daily writes are roughly 18.3 GiB; at 3× retained indexes, replicas, and operational overhead, budget about 55 GiB/day before compression. One year at that rate is approximately 20 TiB of logical provisioned storage. If each accepted message is delivered to an average of 3.2 active/offline devices, peak delivery work is about 5,338 device notifications per second, but offline devices should be represented by durable cursors rather than queued socket events. For 60,000 open connections averaging 24 KiB of gateway memory each, the raw connection state is about 1.4 GiB; process, TLS buffers, subscriptions, and safety overhead suggest at least 3–4 GiB per 60,000 connections, distributed across multiple nodes. Add 30% capacity headroom above measured peak and retain failover capacity rather than running every node near saturation. Recompute estimates when group sizes or media attachments change.
| Quantity | Illustrative calculation | Design consequence |
|---|---|---|
| Average accepted writes | 12,000,000 / 86,400 ≈ 139/s | Partition and persist without treating average as peak |
| Peak accepted writes | 139 × 12 ≈ 1,668/s | Load test peak bursts and retry amplification |
| Connection memory | 60,000 × 24 KiB ≈ 1.4 GiB raw | Spread across gateways; budget TLS and buffers |
| One-year logical storage | 18.3 GiB/day × 365 ≈ 6.7 TiB raw payload | Replication and indexes raise physical capacity substantially |
Begin with a small monolith, then separate pressure points
A reasonable first release is one stateless application process serving HTTPS APIs and a small WebSocket endpoint, plus PostgreSQL for accounts, memberships, messages, per-device cursors, and an outbox table. This is deliberately a small monolith: one deployable keeps request validation and authorization close to transactions, and a managed database makes backup and point-in-time recovery operationally tractable. It becomes a bottleneck when long-lived sockets consume memory and file descriptors, deployments drain thousands of connections, and message persistence competes with fanout queries. The first evolution is not a fleet of tiny services: add separately scaled realtime gateway processes, keep them stateless except for live sockets, and publish committed outbox records to a durable broker. A delivery worker reads broker events, finds active device routes, and emits best-effort socket notifications; a notification is only a wake-up hint because the durable cursor remains authoritative. Later, partition message storage by conversation identifier and introduce regional gateways. Do not split membership and message writes into unrelated services until ownership and failure semantics are explicit. Each extraction adds deployments, tracing boundaries, retries, and on-call pages. This evolution uses observed connection pressure and database saturation as triggers, not fashion.
HTTPS sends, WebSocket receives, per-device cursors
Authentication, membership checks, message transaction
Conversation sequences, messages, memberships, outbox
Publishes committed events at least once
Partitioned by conversation key
Socket sessions and best-effort wake-up delivery
- Chat clients → API monolith: send / sync HTTPS
- API monolith → PostgreSQL: commit message + outbox
- PostgreSQL → Outbox relay: read unpublished rows
- Outbox relay → Durable broker: publish event
- Durable broker → Realtime gateways: consume fanout event
- Realtime gateways → Chat clients: notify connected devices
Make APIs and records support recovery
Use authenticated, versioned APIs with stable identifiers and explicit retry semantics. A send request can be POST /v1/conversations/{conversationId}/messages with a client-generated idempotency key, a device ID, and a body; the response returns messageId, conversationSequence, acceptedAt, and the sender's accepted status. Repeating the same key and payload returns the original result. Reusing the key with a different payload is a conflict, not a second message. GET /v1/conversations/{id}/sync?after={cursor}&limit=100 returns ordered visible messages, the next cursor, membership state, and a hasMore flag. The server caps page size and rejects cursors from another conversation. POST /v1/messages/{id}/ack includes device ID and acknowledged sequence; receipt visibility is separately controlled by conversation policy. Core records include Conversation(id, nextSequence, retentionPolicy), Membership(conversationId, userId, role, joinedAt, removedAt), Message(conversationId, sequence, messageId, senderId, deviceId, createdAt, body, idempotencyKey), Device(userId, deviceId, revokedAt), and DeviceCursor(conversationId, deviceId, sequence). Enforce unique(conversationId, sequence), unique(senderId, deviceId, idempotencyKey), and indexes for per-conversation sequence scans. Store payload encryption-at-rest keys and access logs separately from message content. Do not expose internal database keys or let a client choose a sequence number.
http · Illustrative example; validate before production use
POST /v1/conversations/c_81/messages
Authorization: Bearer <session>
Idempotency-Key: device-7:local-991
Content-Type: application/json
{"deviceId":"d_7","body":{"type":"text","text":"On my way"}}
200 {"messageId":"m_204","conversationSequence":918,"acceptedAt":"2026-04-04T15:20:00Z","status":"accepted"}Trace send, reconnect, and acknowledgement
On send, the API validates the session, device registration, body limits, and current membership. Within one database transaction it reserves the next sequence for that conversation, inserts the message, records the idempotency result, and inserts an outbox event. A successful commit is the acceptance point. The outbox relay can publish more than once after a crash, so workers deduplicate by messageId. Connected gateways receive a notification and deliver it to each online device session; if a connection has closed, no ephemeral queue is required. When a phone reconnects, it presents its per-conversation cursor and asks for sync. The server rechecks membership and returns a bounded sequence page, so a dropped socket notification does not lose content. The device persists messages before advancing its cursor; advancing first could skip data after a local crash. It acknowledges only after that persistence, and the server records the maximum acknowledged sequence for that device. A separate read action may update a user's read watermark if enabled. There is no global ordering between conversations, and two devices can submit concurrently; the database sequence establishes a single accepted order within one conversation. Clients should show pending local messages distinctly until the server supplies the authoritative message ID and sequence.
Client keeps local ID and retry key
Session, device, membership, payload bounds
Sequence + message + idempotency result + outbox
Broker and gateway may repeat event
Device fetches after durable local cursor
Store page before moving cursor
Record device receipt watermark
- Compose → Validate: HTTPS request
- Validate → Commit: authorized request
- Commit → Notify: outbox event
- Notify → Sync: wake-up or reconnect
- Sync → Persist locally: ordered page
- Persist locally → Acknowledge: after local commit
Be precise about ordering, duplicates, and privacy
A client timeout is ambiguous: the server may have committed even if the response was lost. Idempotency resolves this uncertainty. The unique idempotency constraint is checked in the same transaction as the message insertion, and the stored result is returned on retry. For sequence assignment, lock a conversation counter row or use a carefully designed atomic update; a global sequence generator would create a hot point and still would not represent useful cross-conversation order. Lock duration should cover only the short transaction, not network delivery. A group conversation can receive concurrent sends, but all accepted messages must receive distinct increasing positions. Broker ordering can be configured per conversation partition, yet consumers still tolerate duplicate or delayed events and treat the database sequence as authority. Device acknowledgement is monotonic: reject or ignore a lower watermark, and never let one device acknowledge another device's cursor. Membership changes need a defined boundary. A removed user must not retrieve newly requested pages; historical visibility policy should be explicit and enforced at query time rather than inferred from a stale socket subscription. Read receipts can reveal social behavior, so allow opt-out and avoid exposing device identities. If end-to-end encryption is introduced, the server can no longer inspect body content for abuse; metadata minimization, client key verification, multi-device key transfer, and account recovery become separate product and security decisions.
- Exactly-once effects are not promised across unreliable networks; idempotent command handling and deduplicated consumers provide effectively-once user-visible acceptance.
- Do not equate transport order with durable order, delivery with display, or display with human reading.
- Keep message-body authorization in the sync path even when a gateway already authorized a prior socket subscription.
Recover from worker and regional failure
If a gateway crashes, clients reconnect to any healthy gateway and resume from their durable cursor. Use jittered exponential backoff so a region outage does not become a synchronized reconnect storm; impose connection admission limits and shed nonessential presence updates first. If the broker is unavailable, the outbox grows in PostgreSQL. Alert on age and size, protect database disk headroom, and pause optional fanout rather than rejecting already committed messages. If the database is unavailable, reject new sends with a retryable service error and preserve client-generated idempotency keys; do not claim acceptance from an in-memory queue. A regional design might place each conversation in one home region while letting devices connect locally. The home region owns sequence allocation and writes; other regions route sends there and cache only bounded, non-authoritative routing hints. On home-region loss, choose between waiting for recovery and controlled promotion of a replica. Promotion requires a fencing generation and a declared recovery point: asynchronous replication can lose acknowledged writes, so the product must choose a recovery-point objective and communicate whether recently accepted messages can disappear. Never allow two regions to allocate sequence numbers concurrently. Restore drills must test database snapshots, broker offsets, encryption keys, and membership data together. Replayed outbox events are expected and safe through consumer deduplication; a full rebuild from message records must reproduce valid cursor and retention behavior.
| Failure | Safe behavior | Recovery signal |
|---|---|---|
| Socket gateway loss | Reconnect and sync from device cursor | Connection recovery and sync completion |
| Broker backlog | Retain outbox; reduce optional presence fanout | Oldest unpublished outbox age |
| Home-region loss | Fence old owner before promotion; disclose possible RPO loss | Replica lag, promotion generation, restore drill |
Protect accounts, messages, and people
Treat messages as sensitive personal data. Require short-lived access credentials, secure device enrollment, revocation on logout or account recovery, TLS in transit, and managed encryption keys at rest. Apply authorization checks to send, sync, receipt, export, and deletion endpoints; possession of a conversation ID is not authorization. Minimize logs: record actor, operation, conversation pseudonym, outcome, and latency, not message bodies or access tokens. Limit message size, send rate, group membership churn, and reconnect attempts. Abuse controls should combine per-account and per-device throttles with user reporting and block lists; IP-only blocking punishes shared networks and is easy to evade. Presence and read receipts can reveal routines, so default to least disclosure and allow disabling them. Define retention and account deletion semantics, including backups and legal holds, and show users any delay before deletion completes. If operators can read server-side plaintext, scope privileged access, use audited break-glass procedures, and make that trust boundary visible. For future end-to-end encryption, assess malicious group-member removal, key rotation, lost devices, notifications that may leak previews, and abuse reporting that users explicitly submit. Do not claim encryption against the service when the server holds usable decryption keys. Security testing should include cross-tenant cursor substitution, revoked-device sync, replayed sends, oversized payloads, and socket authorization after membership removal.
- Keep body content out of metrics, traces, crash reports, and support screenshots.
- Separate routine operations access from audited emergency access.
Measure user-visible reliability
Define indicators at the user boundary. Send acceptance availability is successful durable accepts divided by valid authenticated send attempts; exclude client-side offline queues and classify validation failures separately. A useful initial objective is 99.9% monthly availability and p99 acceptance latency below 500 ms at normal regional load. Online delivery latency measures accepted message to recipient-device acknowledgement, reported by recipient class and network state; an initial p95 under 2 seconds applies only to connected devices, while offline synchronization has a separate time-to-catch-up objective. Sync completeness checks that requested cursor ranges converge without gaps after retry. Measure active connections per gateway, rejected handshakes, reconnect rate, database lock waits, broker consumer lag, outbox age, duplicate suppression, notification-to-sync ratio, and replica lag. Avoid a single aggregate dashboard that hides a bad region or a particular client version. Use histograms and low-cardinality labels; never put user IDs or conversation IDs into metric labels. Traces can connect send, commit, outbox publish, and gateway notification with a random correlation ID, while omitting message text. Alert on error-budget burn and symptoms such as old outbox records, not only CPU. A monthly SLO is not a release target alone: define an operational response when budget is spent, such as pausing risky schema migrations and prioritizing recovery work.
| Indicator | Measurement boundary | Example objective |
|---|---|---|
| Send acceptance latency | API receipt to durable commit response | p99 < 500 ms under normal peak |
| Connected delivery | Commit timestamp to device ACK | p95 < 2 s for connected recipient |
| Catch-up completeness | Missing sequence gaps after sync retries | No persistent gaps in sampled completed syncs |
Compare cost, alternatives, and migration triggers
Use a hypothetical monthly budget, not a price promise. At 1,668 peak accepted messages/s and 55 GiB/day of physical database growth, a production database tier sized for peak writes, replicas, backups, and failover might cost roughly $18,000/month; 20 gateway instances with reserved headroom might be $8,000; broker capacity and retention $4,000; network egress, logs, and monitoring $6,000; backups and key management $2,000. Total illustrative spend is about $38,000/month before staff and taxes, with a large uncertainty range driven by provider, region, retention, and traffic. If 90% of message payloads are fetched during sync from the database, optimizing query shape may save more than adding a broker. Alternative: managed realtime messaging reduces connection operations but may constrain delivery semantics, retention, or regional routing. Alternative: keep polling instead of sockets for a small product; it is simpler but costs extra request volume and increases latency. Start migration only when load tests and production evidence show connection saturation, database lock contention, or unacceptable regional tail latency. Migrate by dual-publishing outbox records to a shadow consumer, compare sequence coverage and deduplication outcomes, then gradually route a small cohort of connections to new gateways. Rollback must preserve cursor compatibility and stop new writes cleanly. Candidate discussion should surface what the cost estimate omits: on-call labor, incident recovery, compliance, and user support.
- Trade off socket immediacy against operational complexity; durable sync remains the correctness mechanism.
- Track cost per million accepted messages and per million device-sync pages.
Prepare for deeper design questions
A strong follow-up discussion makes assumptions explicit before adding features. If asked to add end-to-end encryption, explain that the server loses body inspection and search, then cover device key verification, multi-device key transfer, backup recovery, and user-submitted abuse reports. If asked for voice calls, isolate real-time media transport and relay capacity rather than sending audio through the message log. If groups grow from 100 to 100,000 members, quantify fanout amplification, change receipt semantics, and decide whether large groups use pull-based sync. If the interviewer requires a regional write during a partition, state the conflict between accepting independent sequence allocation and preserving one conversation order; propose a fencing or consensus policy with its latency cost. Other useful probes are retention deletion across backups, delivery guarantees for offline devices, key loss after account recovery, and how to migrate without losing cursor compatibility. For each answer, distinguish a new product requirement from a hidden implementation detail, identify the invariant that changes, and name a test and SLO that would prove the new behavior. Do not promise stronger privacy, ordering, or availability merely because the architecture has more components.
Terms in plain language
- Conversation sequence
- A monotonically increasing position assigned to an accepted message within one conversation; it does not imply a total order across all conversations.
- Device cursor
- The last conversation sequence a device has reconciled, used to request changes after reconnecting.
- Delivery acknowledgement
- A device statement that a message reached that device; it is distinct from server acceptance and from human reading.
- Fencing token
- A monotonically increasing ownership generation that lets storage reject writes from a stale worker or former regional owner.
Capacity lab
Change the assumptions and inspect the math. This teaching model assumes every request creates one stored record. Real systems separate reads, writes, uploads and background work.
- Average QPS
- 231.48
- daily users × requests per user / 86,400
- Peak QPS
- 1,157.41
- average QPS × peak multiplier
- Peak payload bandwidth (MB/s)
- 1.16
- peak QPS × bytes/request / 1,000,000
- Logical retained storage (GB)
- 600
- requests/day × bytes/request × retention / 1,000,000,000
- Replicated storage (GB)
- 1,800
- logical storage × stored copies
- Serving nodes
- 1
- ceil(peak QPS / (node throughput × utilization))
Decimal MB/GB, not MiB/GiB. Indexes, protocol overhead, compression, retries, backups and failover capacity are excluded. Measure throughput on your workload; this is not a sizing guarantee or a cloud price quote.
References and boundaries
Primary documentation supports the mechanisms described. It does not certify these hypothetical architectures, prices or sizing assumptions. Review platform-specific behavior before implementation.
Defines the WebSocket transport; it does not specify the invented message persistence, authorization, or delivery semantics above.
A public synchronization API reference for cursor-like client catch-up patterns, not a verification of this design.
Documents PostgreSQL locking behavior relevant to per-conversation sequence allocation; it does not prescribe this schema.