Module 6: Case Studies
Chat System
Design a WhatsApp-like chat — WebSockets, message persistence, 1:1 and group fan-out, presence, receipts, and media.
Chat is a realtime fan-out problem with strict ordering expectations inside a conversation. Interviews reward separating the socket gateway from the chat service — and persisting before you push.
What you will learn
- Clarify 1:1 vs group vs channel requirements and delivery guarantees
- Justify WebSockets and a connection-gateway tier
- Design persist-then-fan-out for online and offline users
- Explain ordering, receipts, presence, and unread counts
- Place media on object storage + CDN off the message hot path
Clarify requirements
- Lock product scope early — chat systems grow unbounded features fast.
- 1:1 messaging, group chats (size limits?), optional channels/broadcast
- Delivery: at-least-once to devices; show sent / delivered / read if needed
- Ordering within a conversation; typing indicators; presence online/last-seen
- Media: images/files/voice; size caps; virus scan async
- Scale: MAU, messages/day, p99 send-to-receive latency, multi-device support
Why not polling?
- Chat needs push. Polling burns battery and adds latency.
- Long polling is a halfway step; still chatty at scale
- WebSockets (or MQTT) give bidirectional low-latency push
- Mobile may use platform push (APNs/FCM) when the app is backgrounded
- Fallback to sync APIs for history fetch and catch-up after reconnect
- Separate realtime channel from REST for profiles/settings
Connection gateway
- Socket servers are a distinct tier. Keep them thin.
- Gateway holds WebSocket connections and heartbeats
- Session/registry service maps userId (+ deviceId) → gateway instance
- Sticky LB or registry lookup routes server-initiated pushes
- Heartbeats detect disconnects for presence updates
- Gateways should not own business logic or primary message storage
Send path (1:1)
- Persist first, then fan out — never only push in memory.
- Client → gateway → chat service: validate membership, rate-limit, assign message id/seq
- Write message to durable store (conversation-ordered)
- Lookup recipient connections; push to online gateways
- If offline: message waits in store; push notification optional
- ACK back to sender (sent); later delivered/read as devices confirm
Group chat fan-out
- Groups multiply work. Choose a fan-out strategy that matches group size.
- Small groups: write once, fan-out push to each online member
- Large groups: fan-out on write to per-user inboxes, or fan-out on read for huge audiences
- Maintain member list / roster service with cache
- Watch celebrity/mega-group fan-out cost — hybridize like news-feed designs
- Still one conversation sequence for ordering inside the group
Ordering & IDs
- Users expect messages in a conversation to appear in a stable order.
- Per-conversation monotonic sequence (or Lamport/hybrid logical clock)
- Client temp ids for optimistic UI; server id is authoritative
- Reconnect sync: fetch since last_seq
- Multi-device: each device catches up independently from history API
- Avoid global order across all chats — unnecessary and expensive
Storage choices
- Chat storage is write-heavy and retention-sensitive.
- Message table/store keyed by conversation_id + seq/timestamp
- Wide-column or sharded SQL/NoSQL by conversation_id for linear writes
- Recent messages cached; cold history in cheaper storage
- User inbox / cursor tables for unread and sync checkpoints
- Retention/deletion policies (user delete, GDPR) designed up front
Presence, typing, receipts
- Ephemeral signals should not crush the message database.
- Presence: heartbeat → Redis/ephemeral store; broadcast sparingly to contacts
- Typing: short-lived events, rate-limited, often not persisted
- Delivered/read receipts: lightweight updates; batch when possible
- Last-seen privacy settings may disable fan-out of presence
- Keep these off the critical persist path when you can
Media & push notifications
- Large files never ride inside the chat message body.
- Client uploads to object storage (pre-signed URL); message stores metadata + URL
- CDN for download; async virus scan / thumbnail jobs
- APNs/FCM for offline wake-ups with minimal payload; fetch full message on open
- Encrypt media at rest; signed URLs with expiry
- Cap sizes to protect upload and fan-out paths
Scale & failure modes
- Hot conversations and reconnect storms are the usual pain points.
- Shard conversations and connection registries
- Throttle fan-out for huge groups; prefer inbox models
- Gateway drain on deploy: migrate sockets or accept brief reconnect
- Idempotent send APIs so retries do not duplicate messages
- Backpressure when a recipient’s gateway or store is slow
Interview framing
- Use this order in a chat design round.
- Requirements: chat types, receipts, media, multi-device, scale numbers
- Draw clients → gateway → chat service → message store
- Walk 1:1 persist-then-push; extend to groups
- Add sequence numbers, sync-on-reconnect, presence/receipts
- Add media via object storage + offline push
Quick revision checklist
- Separate socket gateway from chat business service.
- Persist before fan-out.
- Discuss media via object storage + CDN.
- Ordering is per conversation, not global.
- Mention end-to-end encryption only at high level unless asked.
- Plan offline sync and push notifications.
FAQs
Why not pure HTTP polling?
Polling wastes battery/bandwidth and adds latency. Push connections scale better for chat.
Should we push before writing to the database?
No. Persist first so offline users and retries do not lose messages. Then fan out to online connections.
How do group chats scale?
Small groups can fan out pushes per member. Very large groups often use per-user inboxes or fan-out-on-read hybrids so one send does not explode into millions of writes synchronously.
How is message order guaranteed?
Assign a per-conversation monotonic sequence (or equivalent) at the chat service. Clients reconcile with server order after reconnect.
Where do images and videos go?
Object storage via pre-signed upload; the chat message stores metadata and a URL. CDN serves downloads; scanning/thumbnails run async.
How does multi-device chat work?
Each device maintains a cursor/last_seq and syncs history from the store. Online devices get pushes; others catch up on reconnect.
Learner’s Task
- Practice out loud for 10–12 minutes as if designing WhatsApp-style messaging.
- List must-have features (1:1, groups size, receipts, media) and approximate messages/day.
- Draw clients → WebSocket gateway → chat service → message DB, plus a connection registry.
- Narrate a 1:1 send: validate, persist, fan-out, ACKs; then say how an offline user catches up.
- Explain group fan-out choice and per-conversation ordering.
- Write a 4-sentence closing: gateway split, persist-then-push, media path, and one scale risk (mega-groups).