Real-Time Direct Messaging Plus Dormant-Customer Email Campaign
System DesignModel answerLast updated
Design a WebSocket-based one-to-one messaging service with presence and history, plus a scheduled pipeline that emails customers who have been dormant for ten days.
Context
You are building shared infrastructure for a ticketing and events marketplace. Two capabilities must live on the same platform:
- An internal direct-messaging tool for staff.
- A win-back email workflow aimed at customers who have gone quiet.
Part 1: Staff messaging
- Two employees can exchange messages one-to-one, with delivery in real time.
- Clients keep a long-lived WebSocket open.
- Any client can land on any chat server, so the sender and the recipient will often be attached to different servers.
- A recipient who is online should get the message right away. If they are offline, the message must be kept and handed over later.
- Show whether a user is online, and provide a basic, paginated conversation history.
- Describe how messages travel between servers in both directions over the sockets.
Part 2: Win-back emails
Add a process that emails every customer who has not logged in for 10 days.
What to cover
Walk through the high-level architecture, the client and server APIs, storage choices, cross-server routing, how inactivity is detected, scaling, reliability, and failure handling. State your assumptions about scale and justify the main trade-offs.
Hints
Hint 1
Treat the two features as separate subsystems that only share identity and an event stream. The chat side is stateful and latency-sensitive; the email side is a scheduled, high-volume batch with idempotency concerns.
Hint 2
For routing, keep a fast registry that maps each user to the server(s) holding their socket, and give each server its own inbound channel. Persist the message before acknowledging the sender, so a lost forward can be recovered through a reconnect sync.
Hint 3
For the email job, think about how to find 'inactive for 10 days' without scanning every customer, and how to make sure a retry or a re-run of the job never sends the same person two emails for the same dormancy period.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Framing
The question combines two different patterns:
- Real-time chat: stateful sockets, where the hard part is delivering across servers.
- Dormancy emails: a scheduled batch pipeline, where the hard parts are scale and exactly-once-ish behavior.
Keep them as separate services. They share only authentication and the event bus.
Requirements and scale
Functional: one-to-one chat, real-time push to online users, offline storage with sync on reconnect, presence, paginated history, and a 10-day inactivity email.
Non-functional:
- Online delivery in roughly 200 ms.
- No loss of a message after the sender has been acknowledged.
- Ordering within a conversation.
- At-least-once delivery with client-side de-duplication.
- At most one win-back email per dormancy period per customer.
Estimates (state them aloud):
| Item | Estimate |
|---|---|
| Employees | ~20k, ~10k concurrent sockets at peak |
| Messages | ~1M/day, ~12/s average, ~200/s peak |
| Storage | ~1 KB/message, ~1 GB/day |
| Customers | ~50M, perhaps 1-3M crossing the 10-day line daily |
Chat is small: a few gateway servers handle it. Design it to scale horizontally anyway. The email workload is larger by row count.
APIs
WebSocket (wss://.../ws, JWT checked on upgrade):
- Client to server:
send {client_msg_id, to, body},ack {message_id},sync {conv_id: last_seq},heartbeat. - Server to client:
sent {client_msg_id, message_id, conv_id, seq, ts},message {...},presence {user, status, last_seen}.
REST for reads that are not time-critical:
GET /conversations?cursor=GET /conversations/{id}/messages?before_seq=&limit=50GET /presence?user_ids=
Storage
- Messages: a wide-column store (Cassandra or DynamoDB) keyed by
conv_idwithseqas the clustering key. The load is write-heavy, time-ordered and partitioned naturally by conversation. - Conversation ID: deterministic for one-to-one chats, e.g. a hash of the sorted user pair.
seq: a per-conversation counter (conditional increment). A time-based ID is acceptable if gaps are tolerable.- Inbox table:
user_conversations(user_id, last_activity, conv_id, last_read_seq, unread_count). - Idempotency: store
(sender_id, client_msg_id)with a TTL so a retried send does not create a duplicate. - Redis:
conn:{user}holds a set of{server_id, conn_id}(supports several devices, TTL ~90 s refreshed by heartbeats) andpresence:{user}. - Customer activity:
customer_activity(customer_id, last_login_at, last_emailed_for_login_at).
Architecture
Clients -WSS-> Load balancer -> Chat gateways (hold sockets)
|- Redis: connection registry, presence
|- Message service -> Cassandra
'- Inter-server bus (per-server channel)
Auth -login events-> Kafka -> Activity service -> customer_activity
Daily scheduler -> Inactivity job -> Email queue -> Workers -> Email provider
Cross-server routing
On connect: authenticate, register in conn:{user} with a TTL, and subscribe the gateway to its own channel server:{id} (once, at startup).
Send, Alice on server A, Bob on server B:
- A checks the idempotency key.
- A assigns
seqand writes the message to storage first. - A returns
sentto Alice. Durability starts here. - A looks up
conn:{bob}and finds server B. - A publishes the delivery to
server:B(or delivers locally if the same box). - B pushes it down Bob's socket.
- Bob's client acks, and delivery state is updated.
If Bob has no connection, the message is simply already stored. Optionally trigger a push notification.
Why a channel per server rather than per user? Per-user channels mean thousands of subscriptions per gateway with heavy churn. Per-server channels give one subscription per box, and the registry does the addressing.
Bus choice:
- Redis pub/sub is fire-and-forget. That is fine because the message is already durable and reconnect sync repairs gaps.
- Kafka adds replay at the cost of latency and operational weight.
- Direct gateway-to-gateway gRPC works at this scale.
Reconnect sync: the client sends its last seq per conversation. The server finds conversations with newer activity and pages the missing messages. One mechanism covers offline users, dropped bus messages, and gateway crashes.
Ordering and duplicates: seq orders messages per conversation; clients de-duplicate by message_id. The wire is at-least-once, the screen is effectively-once.
Presence
- Heartbeat every ~30 s refreshes a 90 s TTL. A clean disconnect marks the user offline immediately; a crash is handled by TTL expiry.
- Do not broadcast to everyone. Push changes only to users who have that person visible, or let clients poll for visible contacts.
- Debounce transitions by ~10 s to absorb network blips.
Dormancy emails
Capture: the auth service emits login events to Kafka; the activity service upserts last_login_at. This keeps the login path fast and decoupled.
Detect: scanning 50M rows daily is wasteful. Options:
- An indexed query on
last_login_atfor a one-day window (between now-11d and now-10d), run daily, optionally per time zone for local send times. - Or bucket customers by "due date" (
last_login + 10d) and read only today's bucket.
A login after being queued must cancel the email, so re-check last_login_at immediately before sending.
Send:
- The job writes one task per customer to a queue, with deterministic key
(customer_id, last_login_at). - Workers check suppression lists and unsubscribe status, then render and call the email provider using that key as an idempotency token.
- On success, record
last_emailed_for_login_at = last_login_at. Because the key includes the login timestamp, a re-run of the job cannot double-send, and a customer who returns and lapses again is eligible once more.
Throughput: 1-3M emails/day is ~35/s average. Spread sends over hours, respect provider rate limits, and use retries with backoff plus a dead-letter queue.
Failure handling
- Gateway crash: clients reconnect through the load balancer and sync. The registry entry expires through TTL.
- Stale registry entry: the forward fails or is dropped, and sync recovers it.
- Redis loss: presence degrades temporarily; messages stay safe in the primary store.
- Duplicate sends: idempotency keys in chat and in email.
- Job crash midway: safe to re-run because of the deterministic task key.
- Thundering reconnects: jittered backoff on clients.
Common mistakes
- Acknowledging the sender before persisting.
- Relying on pub/sub as the only delivery path.
- Broadcasting presence to everyone.
- Scanning the whole customer table daily.
- Sending the email without a pre-send recheck or idempotency key.
- Mixing the two subsystems into one service.