Real-Time Chat System

Chat is a stateful, bidirectional, ordered event stream per conversation. The UI is the easy part; ordering, delivery, and sync are the product. A chat system that feels instant on a good network and loses messages on a bad one is not a chat system. It is a demo.

This chapter treats chat as a set of invariants and flows. It does not prescribe a specific WebSocket library or database. It describes what must be true when a client retries, a gateway dies, a user is offline for a week, or a group has 100,000 members.

Scope

In scope for v1

  • 1:1 and group conversations.
  • Send/receive messages in real time.
  • History with pagination.
  • Delivery and read receipts (can ship after v1).
  • Online presence (best effort).
  • Push notifications when offline.
  • Media attachments by reference (object storage).
  • Edit and delete with a visible tombstone.

Out of scope for v1

  • End-to-end encryption (this is a separate architecture).
  • Voice/video (WebRTC).
  • Full-text search at scale.
  • Bots, integrations, and public channels.
  • Cross-region active-active writes for the same conversation.

Actors and journeys

Actor Goal What can go wrong
Sender Send a message once and see it delivered Retry creates duplicates; optimistic UI never reconciles
Recipient Read messages in order, including after being offline Gaps, duplicates, stale unread counts
Group admin Add/remove members safely Removed member keeps receiving; new member sees old history
Operator Keep delivery working during gateway/DB failures Reconnect storms, pub/sub loss, hot groups
Support Investigate “I didn’t get the message” No per-message trace, no clear ack state

The critical journeys are:

  1. Send a message and receive the canonical acknowledgement.
  2. Reconnect and resume without gaps or duplicates.
  3. Add/remove a member without leaking history or delivery.

Invariants

  1. Per-conversation order is total and monotonic. Every message gets a seq larger than every previous message in that conversation.
  2. The server is the source of truth. The client’s optimistic message is provisional until it receives the canonical id and seq.
  3. Every send is idempotent per (conversation_id, client_id). A retry must return the existing message, not create a new one.
  4. A message is durable before it is acknowledged or fanned out. If the sender sees “sent,” a later reconnect must be able to fetch it.
  5. Delivery is at least once; the client deduplicates by message id.
  6. Read positions only move forward for a given user and conversation, except explicit reset or re-sync.
  7. Membership is checked at send and at delivery. A removed member must not receive new messages.
  8. No unbounded catch-up. Every sync has a page limit and a resync path when the gap exceeds retention.
  9. Presence is ephemeral and must never block message delivery.

Estimates

10M DAU × 50 messages/day = 500M messages/day
average: ~5,800 messages/s; peak: ~20,000/s
payload: ~200 B text + metadata → ~100 GB/day raw
per-conversation fan-out: group of 100 → up to 100 deliveries per message
connections: assume 10% concurrent → 1M WebSocket connections

Writes are modest. Connection count, fan-out, and reconnect behavior dominate. A 1M-connection fleet with a 30-second reconnect storm is a different problem from 20k writes per second.

End-to-end flows

1. Send a message

client
  → optimistic message with clientId, conversationId, body
  → WS gateway / API
  → authenticate + check membership
  → message service: BEGIN
      validate conversation state and membership
      allocate seq (per-conversation monotonic)
      insert message with unique (conversation_id, client_id)
    COMMIT
  → publish to conversation channel
  → return canonical { id, seq, createdAt } to sender
  → gateway fans out to online members
  → offline members get a push notification

Failure branches:

  • Duplicate clientId: return the existing message with the same id and seq. Do not return an error that makes the client create a new one.
  • Membership revoked mid-send: reject with 403; do not persist a message from a non-member.
  • Seq allocation conflict: retry the transaction with a new seq. If repeated, fail the send and alert; do not reuse a seq.
  • DB timeout after commit: the client retries; idempotency returns the committed message.
  • DB timeout before commit: retry is safe because no message exists.
  • Pub/sub publish fails after commit: the message is durable. Reconnect/resume must still deliver it. The real-time fan-out is best effort, not the source of truth.

2. Receive and acknowledge

gateway
  → member is connected
  → push { id, conversationId, seq, body, senderId }
  → client stores locally and displays by seq
  → client sends delivery ack { conversationId, upToSeq }
  → server updates delivery state (batched)

Rules:

  • The client buffers out-of-order messages until the gap is filled or a timeout triggers a resync.
  • Delivery acks are batched; one ack per message is a write storm.
  • Read receipts update last_read_seq, not a per-message row per member.
  • Acknowledging a later seq implies all earlier messages are delivered/read; define whether that is true for your product.

3. Reconnect and resume

client reconnects
  → authenticates
  → for each conversation: { conversationId, lastSeq }
  → server returns messages after lastSeq, limited to N
  → if the gap exceeds retention: { resyncRequired: true, snapshotCursor }
  → client replaces local state for that conversation, then resumes
  • Resume by per-conversation seq, not by wall-clock time. Clocks skew; seq does not.
  • Cap the number of conversations and messages per resume.
  • If the client has no local state (new device), use a snapshot or paginated history, not an unbounded “all messages since the beginning.”
  • A reconnect storm must be rate-limited with jitter and connection admission control.

4. Offline and push notifications

message committed
  → check online presence for each member
  → for offline members: enqueue push job (dedupe per conversation)
  → push provider accepts/rejects
  → invalid tokens are disabled
  → notification is best effort; the message remains fetchable on reconnect
  • Push is a hint, not the delivery mechanism.
  • Collapse notifications per conversation within a short window.
  • If push fails, do not retry forever; the unread state and next sync are the source of truth.

5. Membership changes

admin adds member
  → validate permission
  → insert membership with joined_at and history boundary
  → system message (optional)
  → new member can fetch history according to policy
  → publish membership event so gateways update subscriptions

admin removes member
  → revoke membership
  → stop new fan-out immediately
  → close/refresh their subscription authorization
  → keep their old messages locally according to policy

Edge decisions:

  • Does a new member see history before joined_at? Decide explicitly.
  • Does a removed member lose local history? The server can stop serving it, but cannot unsee what was already delivered.
  • Are membership changes themselves messages? If yes, they need ordering and idempotency too.

6. Edit, delete, and retention

  • Edit: append an edit record or update the body with a version; clients need a way to reconcile an edit that arrives before the original message.
  • Delete: write a tombstone, fan it out, and purge body/media asynchronously. Tombstones must survive cache and retention.
  • Retention: define per-plan retention. If a client asks for a message beyond retention, return a clear “expired” response, not a silent gap.

Data model and state

CREATE TABLE messages (
  id              uuid PRIMARY KEY,
  conversation_id uuid NOT NULL,
  sender_id       uuid NOT NULL,
  seq             bigint NOT NULL,
  client_id       text NOT NULL,
  body            text,
  kind            text NOT NULL DEFAULT 'text',
  created_at      timestamptz NOT NULL,
  edited_at       timestamptz,
  deleted_at      timestamptz,
  UNIQUE (conversation_id, seq),
  UNIQUE (conversation_id, client_id)
);
CREATE INDEX messages_conv_seq_idx ON messages (conversation_id, seq DESC);

CREATE TABLE conversation_members (
  conversation_id uuid,
  user_id         uuid,
  joined_at       timestamptz NOT NULL,
  last_read_seq   bigint NOT NULL DEFAULT 0,
  last_delivered_seq bigint NOT NULL DEFAULT 0,
  role            text NOT NULL DEFAULT 'member',
  PRIMARY KEY (conversation_id, user_id)
);

Why per-conversation seq:

  • Ordering is local, so you do not need a global clock.
  • “Messages after seq N” is a stable cursor for sync.
  • Gaps are detectable; a client can request the missing range.
  • Cross-conversation ordering is not required.

Alternative: ULID/Snowflake IDs. They work if they are monotonic per conversation; a global sortable ID is not the same as a per-conversation sequence, and it can hide gaps.

Edge cases

Case Expected behavior Notes
Client retries after ack lost Server returns the existing message Unique (conversation_id, client_id)
Two devices send at the same time Two messages with distinct seq Per-device client IDs; no global “current message”
Message arrives out of order Buffer until gap fills or timeout Do not reorder by timestamp
Gap never fills Request resync for that conversation Bound retries
User offline beyond retention resyncRequired, not an infinite gap Snapshot or history page
Message to a removed member Not delivered to them; membership check at fan-out Race with removal is possible; define a boundary
Member added mid-conversation History policy applies Decide from joined_at or full history
User blocked Server rejects send/delivery according to policy Client-side block alone is insufficient
Huge group (100k) Bounded fan-out/read-from-feed model Do not write 100k rows synchronously
Message too large Reject with a clear limit; media uses object storage Keep text and media paths separate
Media upload fails Message remains pending or fails; no dangling URL Two-phase publish
Client clock is wrong UI uses server createdAt; ordering uses seq Never sort by client time
Gateway dies with 50k connections Clients reconnect with jitter and resume by seq Capacity headroom + admission control
Pub/sub message lost Reconnect/resume recovers from DB Real-time is best effort
Duplicate fan-out Client dedupes by id Server may also dedupe per connection
Read receipt regresses Ignore or clamp to max Multi-device races
Edit arrives before original Buffer or fetch original, then apply Versioned edits
Delete races with send Define ordering; tombstone wins if committed later Read-time filtering
E2EE on multiple devices Key sync is a separate protocol Server cannot search or moderate

Failure modes and recovery

Failure Impact Detection Mitigation Recovery
WebSocket gateway crash Connections drop Connection count, 5xx Reconnect jitter, drain, capacity headroom Clients resume by seq; rebalance
Reconnect storm Gateway/DB overload Connection rate, CPU Jitter, token bucket, admission control Scale gateways; shed low-priority sync
DB primary down Sends fail; history reads fail DB health, write latency Queue writes? Prefer fail-fast; read replicas Fail over; reconcile queued sends
Redis/pub-sub down Real-time delivery misses Publish errors, delivery lag DB remains source of truth Clients resync; rebuild channels
Seq allocation conflicts Send errors Conflict counter Retry with new seq, per-conversation serialization Investigate hot conversation
Push provider down Offline users miss notifications Push error rate Queue with TTL, collapse Resend on next sync; do not loop forever
Hot group Fan-out lag Per-conversation delivery lag Worker fan-out, batching, read-time model Rate limit, split group, add capacity
Storage full Writes fail Disk usage Retention, archive, quotas Free space, replay from archive
Poison message Consumer crash loop Error rate per message Schema validation, DLQ Fix, replay, skip with audit
Clock skew Expiry/read-state errors Clock offset Server time, monotonic seq Correct clock; reconcile

Degraded-mode rules:

  1. Preserve send durability and history reads before presence, receipts, and push.
  2. Prefer “message stored, real-time delivery delayed” over “message lost.”
  3. Prefer explicit resyncRequired over silently returning a gap.
  4. Prefer rejecting new connections over accepting them and dropping messages.

Operations

Schema and partitioning

  • Partition messages by conversation or time; the read pattern is “recent history in a conversation.”
  • Keep a per-conversation hot index and archive older partitions.
  • Use online migrations: add nullable columns, backfill, dual-write/read, then remove old paths.
  • Test the migration on a copy with realistic message counts, not a toy dataset.

Retention and deletion

  • Define retention per plan and per message type.
  • Deletes create tombstones, then a background job purges body and media.
  • Exports and account deletion must include messages and attachments.
  • Legal hold overrides normal retention; make that an explicit state.

Monitoring

  • Messages accepted/s, committed/s, delivered/s.
  • p50/p95/p99 send latency and fan-out lag.
  • Reconnect rate, connection churn, auth failures.
  • Per-conversation delivery lag; top hot conversations.
  • Push acceptance/rejection, invalid token rate.
  • DB replication lag, partition size, queue depth.

Incident process

  1. Is send or receive broken? Check commit rate vs delivery rate.
  2. Is it one conversation, one region, or everyone? Check hot conversation and regional health.
  3. Is the database the bottleneck or the fan-out? Compare write latency and publish lag.
  4. Contain: shed presence/receipts, limit reconnect rate, pause non-critical fan-out.
  5. Recover: resume clients by seq, replay failed fan-out from the DB, verify with a canary conversation.
  6. Learn: add the missing invariant or alert; write a regression test.

Testing strategy

  • Ordering: concurrent sends produce unique, monotonic seq per conversation.
  • Idempotency: duplicate clientId after timeout returns one message.
  • Resume: offline client with gaps gets bounded pages or resyncRequired.
  • Duplicates: client receives the same message twice and dedupes.
  • Membership races: send vs remove, add vs history read.
  • Load: 100k+ connections, reconnect storm, hot group fan-out.
  • Chaos: kill gateway, pause pub/sub, fail primary, delay DB, fill disk.
  • Security: unauthorized conversation access, spoofed sender, oversized payloads.
  • Retention: deleted message disappears from history, cache, search, and exports.

Milestones and acceptance criteria

Milestone Build Accept when
1. Durable send Conversations, members, messages with seq + clientId Concurrent sends get unique seq; retries do not duplicate
2. Real-time delivery WS gateway + pub/sub fan-out Online members receive in order; duplicates are deduped
3. Resume Per-conversation cursor + bounded pages A client offline for a day reconnects without gaps or duplicates
4. Receipts + presence Batched delivery/read, TTL presence Receipts never block sends; presence can disappear without losing messages
5. Push + offline Push jobs, token lifecycle Offline users can fetch messages even if push fails
6. Groups at scale Fan-out workers, limits, hot-group strategy A 100k-member group does not block sends for an hour
7. Retention + delete Tombstones, purge jobs, export Deletes propagate and survive cache/restart
8. Failure drills Load + chaos Reconnect storm and gateway kill meet recovery SLO

Review questions

  • How do you guarantee per-conversation ordering without a global clock?
  • What happens if a message is delivered twice? Out of order?
  • How does a device offline for a week sync without an unbounded response?
  • Where is presence stored, and can it block delivery?
  • What happens when a gateway dies with 50k connections?
  • How do you remove a member without leaking new messages?
  • What is your retention policy, and what does “delete” actually delete?
  • Which failures fail closed, and which degrade gracefully?
  • Can you trace one message from send to delivery across gateways?

Checklist

  • Messages have stable ids and a per-conversation monotonic sequence.
  • Sends are idempotent via (conversation_id, client_id).
  • Message rows are durable before ack or fan-out.
  • Reconnect resumes from a cursor with bounded pages and a resync path.
  • Delivery/read receipts are batched and monotonic per user.
  • Presence is ephemeral, TTL-based, and non-blocking.
  • Group fan-out is bounded and has a plan for 100k members.
  • Membership is checked at send and delivery.
  • Push is best effort; history remains the source of truth.
  • Deletes/tombstones propagate through history, cache, and exports.
  • Retention, partitioning, and archival are defined.
  • Reconnect storms and gateway failures have tested runbooks.