Isolated Multi-Tenant Workspace Chat and Channel Platform
Medium · System Design · Software Engineer · Onsite
Prompt
Architect a B2B workplace chat platform supporting 1:1 and group direct messages alongside three channel access modes—open workspace channels, hidden member-only channels, and directory-listed channels that require an invite or admin approval to join—plus workspace/channel admin roles, unread watermarks, and online status indicators. Committed messages must persist durably, stream to connected recipients with sub-second latency, allow reconnecting devices to catch up on missed activity, and remain searchable across history.
Every customer workspace operates as a strictly isolated tenant whose messages, files, caches, and search indexes may never bleed into another workspace:
- A single person's login may participate in multiple workspaces, holding an independent identity and permission set inside each workspace.
- Every conversation enforces a single server-assigned message order, whereas global ordering across unrelated conversations is unnecessary.
- Channel membership ranges from small project teams up to tens of thousands of employees.
- Unstable mobile or laptop networks will drop acknowledgments and cause clients to retry sending the same message.
- Full-text search queries and indexed documents must honor the exact same workspace and channel read permissions as timeline fetches.
Clarify your assumptions up front around peak message throughput, largest workspace headcount, retention/legal-hold policies, attachment size limits, acceptable presence lag, message edits/deletes/threads/reactions, delivery/push guarantees, and whether regulated enterprises need regional data residency or dedicated clusters.
Scope & Expectations
- Per-conversation sequencing, durability & fan-out: Show how concurrent sends receive a deterministic sequence number without duplicates on retry, fan out efficiently across both small DMs and 50,000-member channels, and catch up reconnecting devices.
- Compact read watermarks & bounded presence: Model per-conversation read progress and user availability indicators without per-reader-per-message write explosions or company-wide broadcast storms.
- Defense-in-depth tenant & channel access control: Enforce verified workspace isolation and channel membership boundaries across database shards, caches, event buses, file storage, and full-text search—including immediate revocation when someone leaves a restricted channel.
Step-by-step walkthrough
Clarify requirements and scope
In a system design interview, spend the first few minutes pinning down scale, delivery guarantees, and what "strict isolation" means. Those three choices dictate your database layout, real-time routing, and security boundaries.
Functional requirements
- Conversations: 1:1 direct messages (DMs), small group DMs, and three channel types:
- Public: visible in the organization's directory; any regular organization member can read and join.
- Private: hidden from non-members; only current members can see it exists or read its history.
- Invitation-only: listed by name and topic in the directory so people can discover it, but message history is readable only by members and joining requires an invitation or channel-admin approval.
- Messaging: send, edit, and delete text messages; upload and download file attachments.
- Real-time and offline sync: online users see new messages in near real time across all open devices; offline users catch up seamlessly when they reconnect; mobile push notifications fire for DMs and
@mentions. - Read position and presence: track how far each user has read in each conversation (powering unread badges and DM "seen" indicators) and show whether teammates are active, away, or offline.
- Search: full-text search across only the conversations the caller is currently allowed to read.
- Roles: organization owner/admin (manages users, retention policies, compliance exports), channel admin (manages one channel's members and posting rules), full member, and single- or multi-channel guest.
Non-functional requirements
- Strict tenant isolation: a tenant is one customer organization. No bug class that we can prevent mechanically may ever expose one tenant's messages, channels, files, or search hits to another tenant.
- Durability: once the server acknowledges a sent message, that message must never be lost.
- Per-conversation deterministic order: every user in a channel sees messages in the exact same server-assigned order. Ordering across different conversations is not required.
- At-least-once delivery with single display: at-least-once delivery means the network and server retry until the recipient gets the message, even if duplicates arrive; the client deduplicates so each message appears once on screen.
- Latency targets: under 500 ms p99 end-to-end delivery to online recipients in the same region; under 200 ms p99 to load a page of conversation history.
Answers to the clarifying questions (assumed for this design)
- Scale: 50,000 tenants (up to 300,000 users in the largest enterprise); 10M daily active users (DAU); 5M peak concurrent device connections; 500M messages per day with peak traffic at 3x the daily average.
- Retention and attachments: configurable retention per tenant (default: keep forever), with legal compliance holds that block deletion; file attachments up to 1 GB stored in object storage.
- Presence staleness: approximate presence is fine; up to ~60 seconds stale is acceptable.
- Edits, deletes, threads, reactions: edits and deletes are in scope; threads and reactions reuse the same per-conversation event log as additional event types.
- Dedicated infrastructure and data residency: regulated or massive enterprises may require EU-only or US-only storage or dedicated hardware. We therefore deploy the architecture in cells—self-contained regional stacks that each host either a shared pool of smaller tenants or a single dedicated enterprise tenant.
- Conversations: 1:1 direct messages (DMs), small group DMs, and three channel types:
Back-of-the-envelope numbers
Before picking databases or queues, convert the daily numbers into per-second rates so you can see where the real bottlenecks live.
Messages and storage Daily volume 500,000,000 messages / day Average write rate 500M / 86,400 s = ~5,800 messages/s Peak write rate (3x average) 3 x 5,800 = ~17,400 messages/s Average message record ~500 bytes (text + metadata; files live in object storage) Raw database growth 500M x 500 B = 250 GB/day -> 250 GB x 365 = ~91 TB/year Replicated + indexed ~273 TB/year across 3 DB replicas + ~90 TB/year for search indexes Persistent connections Peak concurrent devices 5,000,000 open sockets Capacity per gateway server ~50,000 sockets -> 100 servers minimum (~150 with 50% headroom) Real-time delivery (fan-out) Average online recipients/msg ~12 connected devices Peak socket writes 17,400 msgs/s x 12 = ~208,800 socket pushes/s Worst-case town-hall channel 50,000 members, 20,000 online devices: Naive per-user push 20,000 routing lookups + 20,000 internal RPCs for 1 message Gateway-grouped push <= 150 internal RPCs (1 per gateway), then fast in-memory writes Read watermarks (bookmark vs. per-receipt rows) Naive: 1 row per (msg, reader) 500M msgs/day x 30 avg readers = 15B rows/day (~173,600 writes/s) Pointer: 1 row per (user, conv) 10M DAU x 100 view updates/day = 1B updates/day (~11,600 writes/s) Presence Heartbeats (every 30 s) 5M sockets / 30 s = ~166,700/s (absorbed in gateway memory) Actual status transitions 10M DAU x 20 changes/day = 200M/day (~2,300 writes/s)Three architectural lessons jump straight out of this math:
- Database message inserts are modest, while live fan-out is huge. Writing 17,400 rows per second is comfortable for a sharded relational database, whereas pushing ~210,000 real-time events per second—especially inside a 50,000-person channel—requires careful two-level routing.
- Per-message read receipts are unaffordable. Storing one receipt per reader per message creates ~15x more writes than storing a single "highest sequence read" pointer per
(user, conversation). - 91 TB per year of raw message history means we must shard storage from day one and support cheap bulk retention deletes.
API design
A single human login (
account_id, such asalice@company.com) can belong to multiple organizations, holding a distinctuser_idand role inside each one. When a client opens a workspace, the auth service mints a cryptographic token bound to one specific(tenant_id, user_id, device_id). Every service extractstenant_idexclusively from that verified token—never from a URL parameter or JSON field that a client could tamper with.Clients maintain a WebSocket—a persistent, two-way TCP connection between client and server—so the server can push live events without polling.
WebSocket: wss://<cell-host>/v1/socket Header: Authorization: Bearer <signed_token(tenant_id, user_id, device_id)> Client -> Server frames send { client_msg_id, conversation_id, text, attachment_ids[], thread_root_seq? } mark_read { conversation_id, read_seq } typing { conversation_id } presence.subscribe { user_ids[] } -- capped at 500 users currently visible on screen Server -> Client frames ack { client_msg_id, conversation_id, seq, created_at } -- sent ONLY after durable DB commit event { conversation_id, seq, type: message|edit|delete|member_added|member_removed|channel_updated, payload } read.sync { conversation_id, read_seq } -- clears badges on user's other devices presence { user_id, status: active|away|offline }Standard HTTPS REST endpoints handle history pagination, reconnect catch-up, administration, search, and file uploads using the same tenant-scoped token:
GET /v1/conversations?changed_since=<cursor> -- list my conversations + latest last_seq & read_seq GET /v1/conversations/{id}/events?after_seq=41&limit=100 -- forward catch-up (or before_seq= for scrollback) POST /v1/conversations/{id}/messages -- HTTP fallback for send (uses client_msg_id) PATCH /v1/conversations/{id}/messages/{seq} -- edit a message DELETE /v1/conversations/{id}/messages/{seq} -- soft-delete (replaces body with tombstone) PUT /v1/conversations/{id}/read -- { read_seq } monotonic update POST /v1/channels -- { name, visibility: public|private|invite_only } POST /v1/channels/{id}/members -- add members (checked against channel visibility) DELETE /v1/channels/{id}/members/{user_id} -- remove member POST /v1/channels/{id}/join | /join-requests -- self-join public or request invite_only GET /v1/search?q=&in=&from=&before=&after= -- permission-filtered full-text search POST /v1/files -- returns pre-signed upload URL under t/<tenant_id>/Why these fields are shaped this way:
client_msg_idis an idempotency key—a unique token generated by the sender's device before the first network attempt and reused on every retry, so retrying after a dropped connection returns the original message instead of creating a duplicate.seqis a gap-free per-conversation counter (1, 2, 3, ...). If a phone hasseq = 41and suddenly receivesseq = 43over the socket, it immediately knows it missed42and fetchesafter_seq=41.
Data model and sharding
We store durable state in a sharded relational database (such as sharded PostgreSQL). Every table places
tenant_idas the first column of its primary key and foreign keys.We shard the core messaging tables by
(tenant_id, conversation_id). That keeps a conversation's metadata row, its authoritative member list, and all of its message events together on the exact same database shard, so checking membership, incrementinglast_seq, and inserting an event happen in one fast local transaction with no distributed two-phase commit.tenants (tenant_id) PK, cell_id, region, retention_days, legal_hold, kms_key_id users (tenant_id, user_id) PK, account_id, role: owner|admin|member|guest, status: active|deactivated -- Co-located on the same shard via shard key = (tenant_id, conversation_id): conversations (tenant_id, conversation_id) PK, kind: dm|group_dm|channel, visibility: public|private|invite_only, name, posting: everyone|admins_only, last_seq, member_count, archived memberships (tenant_id, conversation_id, user_id) PK, role: channel_admin|member, state: active|removed, joined_seq, removed_seq -- single source of truth for channel access events (tenant_id, conversation_id, seq) PK, type: message|edit|delete|member_added|member_removed|channel_updated, sender_id, client_msg_id, body_ciphertext, target_seq, current_body_ciphertext, attachment_ids, thread_root_seq, deleted, created_at, edited_at UNIQUE (tenant_id, conversation_id, sender_id, client_msg_id) -- Sharded by (tenant_id, user_id) for fast "load my sidebar" queries: user_conversations (tenant_id, user_id, conversation_id) PK, kind, muted -- derived asynchronously from membership events; NEVER used for permission checks read_state (tenant_id, user_id, conversation_id) PK, read_seq, updated_at files (tenant_id, file_id) PK, conversation_id, object_key: 't/<tenant_id>/f/<file_id>', size_bytes, malware_scan_status audit_log (tenant_id, created_at, event_id) PK, actor_id, action, target_id, metadataWhy we split
membershipsanduser_conversations:- Permission checks ask "Is user U allowed inside conversation C?"—which hits
membershipson C's shard with zero lag. - Rendering the left sidebar on app launch asks "Which conversations does user U belong to?"—without
user_conversationssharded by(tenant_id, user_id), we would have to scatter-gather across every conversation shard in the cluster.user_conversationsis an eventually consistent lookup table for listing IDs, whilemembershipsremains the strict security gatekeeper.
- Permission checks ask "Is user U allowed inside conversation C?"—which hits
High-level architecture
Desktop / Mobile / Web Clients Bearer token = (tenant_id, user_id, device_id) | v +---------------------+ Tenant Directory (cached globally): | Global Edge / L7 LB | ---> maps tenant_id -> cell_id (region, shared vs. dedicated) +----------+----------+ | ===============|====== Inside One Cell (1 Region, Isolated Stack) ======================= v +---------------------+ send / mark_read +------------------------+ | WebSocket Gateways | --------------------> | Message Service | | (~150 nodes, 50k | | (stateless: auth check,| | sockets/node) | | ACL check, DB tx) | +----------+----------+ +-----------+------------+ ^ | ^ | | | | local ACID | transaction | v | v | +----------+ | +---------------------+ +------------------------+ | | Presence | | | Connection Registry | | Sharded Message DB | | | KV Store | | | user -> gateway IDs | | key: (tenant, conv) | | | (60s TTL)| | +----------+----------+ | convs, memberships, | | +----------+ | ^ | events | | | | +-----+------------+-----+ | | | | | | +---------+-------------+ reads | | Change Data Capture | | REST API & Search Proxy <----------------+ | (reads DB commit log) | +---------+-------------+ v | | +--------------------------+ | v | Partitioned Event Bus | | +-----------------------+ | key: (tenant_id, conv_id)| | | Search Cluster | <-----------------+---+----------+---------+--+ | | (tenant-routed shards)| indexer | | | | +-----------------------+ v v v | +---------+ +-------+ +-------+ +---------------------------------------------- | Fan-out | | Push | | Audit | batched pushes per gateway | Workers | | APNs/ | | & DLP | +---------+ | FCM | +-------+ +-------+Let's trace a single message from sender to recipient:
- Alice sends
"Ship it!"over her open WebSocket. The gateway attaches her verified(tenant_id, user_id)context and forwards the RPC to the stateless Message Service. - The Message Service runs a single transaction on the shard owning
(tenant_id, conversation_id): it verifies Alice can post, deduplicates(sender_id, client_msg_id), incrementslast_seq, and inserts theeventsrow. - Once the database primary replicates that commit to a synchronous replica, the Message Service returns
ack { seq: 42 }to Alice's device. - Change data capture (CDC)—a background reader that tails the database's write-ahead commit log—picks up committed event
42and publishes it to the Event Bus partition for(tenant_id, conversation_id). - Independent consumers read the event in order: Fan-out Workers push it to online gateways, the Search Indexer makes it searchable, Push Workers alert offline phones on mentions/DMs, and the Audit Consumer archives it for compliance.
- Alice sends
Deep dive 1: per-conversation ordering and idempotent sends
Establishing one canonical sequence across separate WebSocket gateways: Gateways never negotiate order among themselves. Whether Alice connects to Gateway 7 and Bob connects to Gateway 92, both sends for
(tenant_id = T1, conversation_id = C9)land on the single primary shard holding row(T1, C9)inconversations. Locking that single row forces concurrent writes into a strict single-file line.Look closely at the exact order of SQL statements inside the transaction:
BEGIN; SET LOCAL app.tenant_id = :t; -- 1) Lock the conversation row FIRST so concurrent sends (and concurrent retries -- of the same message) line up one at a time on this conversation. SELECT visibility, posting, last_seq FROM conversations WHERE tenant_id = :t AND conversation_id = :c FOR UPDATE; -- 2) Verify the sender is still permitted to post right now (prevents a user who -- was just removed at seq N from slipping a message in at seq N + 1). SELECT role, state FROM memberships WHERE tenant_id = :t AND conversation_id = :c AND user_id = :u; -- 3) Idempotency check: if a previous attempt already committed before the ack -- was lost, return its existing seq without advancing last_seq. SELECT seq, created_at FROM events WHERE tenant_id = :t AND conversation_id = :c AND sender_id = :u AND client_msg_id = :m; -- If a row is returned -> COMMIT immediately and return that seq! -- 4) Assign the next dense sequence number (last_seq + 1) and insert the event. UPDATE conversations SET last_seq = last_seq + 1 WHERE tenant_id = :t AND conversation_id = :c RETURNING last_seq; INSERT INTO events (tenant_id, conversation_id, seq, type, sender_id, client_msg_id, body_ciphertext, created_at) VALUES (:t, :c, :new_seq, 'message', :u, :m, :ciphertext, now()); COMMIT;Why locking
conversationsin Step 1 before checkingclient_msg_idin Step 3 is critical:Timeline of a race (Alice's phone retries while her first send is still running): Attempt 1 (Gateway 7) Attempt 2 (Gateway 19, same client_msg_id = "msg-uuid-8") --------------------- --------------------------------------------------------- 1. Locks conversations row (seq=41) 2. Membership active -> OK 1. Runs SELECT ... FOR UPDATE -> WAITS on row lock 3. Checks events for "msg-uuid-8" -> none found 4. Updates last_seq = 42, inserts event seq=42, COMMITS! (Lock acquired! PostgreSQL READ COMMITTED sees committed data) 2. Membership active -> OK 3. Checks events for "msg-uuid-8" -> FINDS seq=42! 4. COMMITS and returns seq=42 (no wasted seq, no error!)- Why client timestamps are never used for ordering: laptop and phone clocks drift by seconds or minutes; server commit order gives one indisputable truth (
41, 42, 43). - Why
seqhas zero gaps:last_seqincrements in the same transaction asINSERT INTO events(if anything rolls back,last_seqrolls back too). Edits and deletes create a new event at the latestseqreferencingtarget_seqand mark deleted rows with a tombstone (a placeholder record saying "message 42 was deleted") rather than removing sequence42. - Throughput ceiling of one hot channel: holding a row lock across a synchronous same-region replica takes ~2–4 ms, capping one conversation at ~250–500 messages/s. Human typing never reaches that. For automated alert channels driven by bots, the Message Service uses group commit: routing
(tenant_id, conversation_id)via consistent hashing to one owner service instance that batches 20 queued messages into a singlelast_seq + 20transaction (~5,000+ msgs/s).
- Why client timestamps are never used for ordering: laptop and phone clocks drift by seconds or minutes; server commit order gives one indisputable truth (
Deep dive 2: real-time fan-out and offline catch-up
A messaging system faces two opposite extremes: millions of 2-person DMs and giant 50,000-person
#announcementschannels.We combine fan-out on read for durable storage with two-tier fan-out on write for live sockets: - Fan-out on read means we store each message once under
(tenant_id, conversation_id, seq), and readers fetch from that shared conversation log when opening history. Writing a separate inbox copy per recipient would turn 1 message in a 50,000-member channel into 50,000 database writes. - Fan-out on write means pushing a newly arrived message out to recipients immediately—which we do only for currently connected online devices, choosing between two paths based onmember_count:Path A: Small conversation (<= 1,000 members — covers 99%+ of DMs and team channels) Event Bus -> Fan-out Worker -> fetches member user_ids (from cache) -> looks up user_id -> gateway_ids in Connection Registry -> sends 1 batched RPC per Gateway listing target (user_id, socket_id) pairs Path B: Large channel (> 1,000 members — e.g., 50,000-person company-wide channel) At connect time: Gateway subscribes to pub/sub topic `t:<tenant_id>:c:<conv_id>` whenever >= 1 local user on that Gateway belongs to large channel C. At send time: Event Bus -> Fan-out Worker -> broadcasts 1 copy to each subscribed Gateway (<= 150 RPCs total!) -> each Gateway loops over its local in-memory subscriber setPreventing race conditions when a member is removed: Because
member_removedis written toeventsas its own sequence number (sayseq = 50) and the Event Bus is partitioned by(tenant_id, conversation_id), every consumer seesseq = 50strictly beforeseq = 51: - On Path A, seeingmember_removedatseq = 50forces the Fan-out Worker to evict its local member list and reload directly from the primary shard'smembershipstable before routingseq = 51. - On Path B, seeingseq = 50causes the Gateway to immediately drop that user's socket from the channel's local subscriber list and push achannel_removedcommand instructing the client app to wipe its local cache of that channel.Offline catch-up when a laptop wakes from sleep: 1. The client calls
GET /v1/conversations?changed_since=<last_sync_cursor>, receiving only conversations whoselast_seqor membership changed while it was asleep, along withread_seq. 2. Only for the currently open conversation (and top unread DMs), the client callsGET /v1/conversations/{id}/events?after_seq=<local_seq>&limit=50. 3. If a noisy channel advanced by > 1,000 messages while the user was on vacation, the client discards its stale local window and fetches the latest 50 messages (before_seq=latest), loading older slices on scroll.Deep dive 3: strict tenant isolation and permissions
Multi-tenant security rests on one ironclad law: propagate a cryptographically verified
tenant_idacross every storage, cache, queue, and search boundary, and configure each layer so missing context fails closed.Authority boundary Mechanical enforcement 1. Authentication Tokens are signed per (tenant_id, user_id). Services readtenant_idonly from verified auth context, never from request payloads.2. Cell routing Global edge routes tenant_id -> cell_id; a cell rejects any token whosetenant_idis not assigned to that cell.3. Database keys & RLS tenant_idleads every primary/foreign key, backed by forced row-level security (RLS) (see SQL below).4. Cache keys Cache client requires a TenantContextobject and prefixes every keyt:{tenant_id}:...; raw string keys are blocked by linter rules.5. Event bus Partition key is (tenant_id, conversation_id); every message envelope includestenant_id, and consumers assert match before processing.6. Search cluster Search proxy injects mandatory tenant_idfilter + post-checks hits againstmemberships; enterprise tenants get dedicated indexes.7. Object storage File keys live under t/<tenant_id>/f/<file_id>; downloads use short-lived pre-signed URLs minted only aftercan_readsucceeds.8. Encryption Envelope encryption—encrypting each tenant's message bodies and files with a unique per-tenant data key wrapped by KMS (or customer-managed key). Even raw disk bytes from another tenant cannot be decrypted. 9. Audit log Every admin action, compliance export, and permission change appends an immutable (tenant_id, actor_id, action)record.Mechanically preventing missing
WHERE tenant_id = ...bugs with Row-Level Security (RLS): Row-level security (RLS) is a database feature that automatically attaches a hidden security filter to everySELECT,INSERT,UPDATE, andDELETErun on a table, even if an application developer writesSELECT * FROM eventswith noWHEREclause.ALTER TABLE events ENABLE ROW LEVEL SECURITY; ALTER TABLE events FORCE ROW LEVEL SECURITY; -- enforces policy even on the table owner role CREATE POLICY tenant_isolation_policy ON events USING (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid) WITH CHECK (tenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid);Why
SET LOCALandNULLIF(..., '')::uuidboth matter: - Our data-access wrapper starts every transaction withBEGIN; SET LOCAL app.tenant_id = '<verified-uuid>';. UsingSET LOCALscopes the variable strictly to the current transaction; when the transaction commits and the connection returns to a shared connection pool, PostgreSQL resetsapp.tenant_idto''so it can never leak into the next tenant's request. - If a buggy endpoint runs a query outside the wrapper withoutSET LOCAL,NULLIF('', '')evaluates toNULL, andtenant_id = NULLmatches zero rows (failing closed instead of leaking data).Preventing stale permission caches with cache leases: Suppose an admin removes Bob from private channel
#m-and-a. If we simply delete cache keyt:T1:conv:C9:members, a concurrent reader whose request started 2 ms before the removal might finish reading the old database list (still containing Bob) 1 ms after our cache delete and write that stale list back into the cache! We prevent this with cache leases—short-lived tokens handed out by the cache on a cache miss: 1. On a cache miss, the cache generates a 5-second lease tokenL88and gives it to the reader. 2. When#m-and-aremoves Bob, the write path deletest:T1:conv:C9:members, which invalidates all outstanding lease tokens (L88). 3. When the slow reader triesset_if_lease_valid(key, old_list, lease=L88), the cache rejects the write becauseL88was invalidated. As a belt-and-suspenders backup, the CDC consumer deletes the cache key a second time when processingmember_removed, and keys carry a 60-second TTL.Read positions, presence, and permission-aware search
Read watermarks without write amplification: Instead of recording every
(message, reader)pair,read_statekeeps one monotonic pointer per(tenant_id, user_id, conversation_id):INSERT INTO read_state (tenant_id, user_id, conversation_id, read_seq, updated_at) VALUES (:t, :u, :c, :seq, now()) ON CONFLICT (tenant_id, user_id, conversation_id) DO UPDATE SET read_seq = GREATEST(read_state.read_seq, EXCLUDED.read_seq), updated_at = now();GREATEST(...)makes updates idempotent and immune to out-of-order packets from a user's phone and laptop.- A channel shows an unread indicator whenever
conversations.last_seq > read_state.read_seq. Exact numeric badges ("3") are maintained for DMs and@mentions, where counts are small and high-signal. - In a 1:1 DM, showing "Seen by Bob" under message
seq = 18simply checksread_seq(Bob) >= 18—zero extra receipt rows needed.
Scalable online presence: - Broadcasting every status change to all 300,000 colleagues in an enterprise would trigger
300,000notifications per transition (O(N^2)traffic across the company). Instead, clients callpresence.subscribefor at most 500 users currently visible in the viewport (open DM sidebar + visible channel roster). - Connected clients send a lightweight heartbeat frame every 30 s. Each Gateway aggregates its own users in memory and batch-refreshest:{tenant_id}:presence:{user_id}in the Presence KV store with a 60-second TTL (time-to-live, an automatic expiration timer). If a gateway crashes or a user loses Wi-Fi, the key expires within 60 s, comfortably meeting our ~1-minute staleness target.Permission-aware search: - The Search Indexer consumes the Event Bus and indexes
{ tenant_id, conversation_id, seq, sender_id, text, visibility, created_at }within a few seconds of send (overwriting on edit, deleting on message delete). - Clients never query the search engine directly. The Search Proxy builds a two-stage query: 1. Index filter:tenant_id = :t AND (conversation_id IN my_conversation_ids(:u) OR (visibility = 'public' AND user.role != 'guest')). We readmy_conversation_idsfromuser_conversations(fast, single user shard). 2. Authoritative post-check: Becauseuser_conversationsand the search index can lag behind a private-channel removal by a second or two, the Search Proxy extracts the distinctconversation_ids from the top page of search hits and batch-verifiescan_read(user, conv)against the authoritativemembershipstable before returning a single snippet to the client.Scaling and bottlenecks
- Rolling gateway deploys without reconnect storms: shutting down a gateway drops 50,000 WebSockets. During deploys, a draining gateway sends a
reconnect_soonframe with a random jitter window of0–180 sso clients migrate smoothly instead of hammering auth andchanged_sinceall in the same second. - Regional blip recovery: if a network outage disconnects 1M clients at once, gateways enforce token-bucket admission control on new handshakes, serve
changed_sincefrom a Redis cache of(conversation_id -> last_seq)maintained by CDC, and cap initial catch-up pages. - Tenant growth and hot shards: small tenants share database shards; if one tenant grows from 500 to 200,000 employees, new conversations hash across dozens of shards inside its cell automatically because the shard key is
(tenant_id, conversation_id)rather thantenant_idalone. - Noisy-neighbor protection: per-tenant token-bucket rate limits guard message sends, REST calls, and expensive search queries so a runaway bot at Tenant A cannot starve Tenant B.
- Rolling gateway deploys without reconnect storms: shutting down a gateway drops 50,000 WebSockets. During deploys, a draining gateway sends a
Failure handling and trade-off summary
What breaks and how the system recovers:
- Database commits, then the Message Service crashes before real-time publish: nothing is lost or stuck. We never publish directly from the HTTP/WebSocket handler; CDC reads the committed database write-ahead log and retries publishing to the Event Bus until acknowledged. Even if the bus lags, recipients self-heal as soon as the next message arrives (seeing
seq 43after41triggersafter_seq=41) or upon reconnect. - Gateway node crashes: gateways hold zero durable data. Disconnected clients reconnect to surviving gateways, resend any unacknowledged message using the same
client_msg_id, and runafter_seqcatch-up. - Shard primary crash: synchronous intra-region replication promotes the standby with zero lost
acks; writes to conversations on that shard retry withclient_msg_idafter a few seconds of failover. - Search or Presence cluster outage: messaging and history reads stay 100% up; presence degrades gracefully to "status unavailable" and search returns a retryable error while the indexer catches up from its saved bus offset.
- Continuous isolation verification: synthetic canary bots belonging to
canary-tenant-Acontinuously attempt to fetch, search, and downloadcanary-tenant-BIDs in every cell, paging engineers immediately if any boundary ever fails open.
Summary of key design choices:
- Single-row serialization per conversation gives gap-free, deterministic ordering and trivial deduplication at the cost of ~250–500 writes/s per channel (lifted via group commit for bot channels).
- Store once (fan-out on read) + gateway-grouped live push (fan-out on write) keeps disk usage independent of channel size while bounding 50,000-member broadcasts to
<= 150internal gateway RPCs. - CDC-driven event bus guarantees database state and real-time/search streams never diverge, trading ~10–30 ms of log-tailing latency for rock-solid reliability.
- Defense-in-depth isolation (tokens + cells + RLS + leases + per-tenant keys) ensures no single application bug can leak enterprise data across tenants.
- Database commits, then the Message Service crashes before real-time publish: nothing is lost or stuck. We never publish directly from the HTTP/WebSocket handler; CDC reads the committed database write-ahead log and retries publishing to the Event Bus until acknowledged. Even if the bus lags, recipients self-heal as soon as the next message arrives (seeing
Intuition & how it works
Think of an isolated multi-workspace team chat platform like a high-security office tower shared by 50,000 different companies, where each meeting room keeps a single numbered logbook chained to the table:
- Keycards locked to one company (tenant isolation): Every employee's badge is cryptographically tied to one company floor (
tenant_id). Doors, filing cabinets, caches, and search clerks check that badge automatically and refuse to open anything from another floor—even if someone guesses another room's ID number. - One numbered logbook per room (per-conversation ordering): Inside any chat room, people don't argue about whose watch was earlier. Whoever writes the next line in the room's logbook gets the next page number (
seq = 1, 2, 3, ...), and a courier photocopies that committed line to notify everyone currently listening. - One bookmark per reader (read pointers): Instead of stamping 5,000 signatures onto every page of a 5,000-person town-hall notebook, each employee simply keeps one sticky-note bookmark recording the highest page number they have read (
read_seq = 42).
A naive design falls apart in three places at enterprise scale. First, filtering tenants only with hand-written WHERE tenant_id = ? clauses means a single forgotten filter in a new endpoint or cache lookup leaks confidential messages across companies. Second, copying every message into each member's personal inbox—or writing one read-receipt row per reader—turns one post in a 50,000-person channel into 50,000 database writes. Third, publishing directly to WebSockets from the API server loses live messages whenever a server crashes right after committing to the database.
Let's trace a tiny concrete example with 4 events inside tenant T1's private channel C9 (currently at last_seq = 10, with members Alice, Bob, and Cara):
- Alice sends
"Q4 numbers look strong"(client_msg_id = "m1"): Her WebSocket drops right before she gets the acknowledgment, so her app retries with the same"m1". On shard(T1, C9), the first request locksC9, assignsseq = 11, and commits; the retry sees"m1"already stored atseq = 11and returnsack { seq: 11 }without creating a duplicate. - Database commit streams to listeners: Change data capture (CDC)—a process that tails the database's commit log—publishes event
11to the event bus partition(T1, C9). A fan-out worker pushesseq = 11to Bob's and Cara's open sockets, and the search indexer indexes"Q4 numbers look strong"under(T1, C9, 11). - Bob reads the channel on his laptop: His client sends
mark_read { conversation_id: "C9", read_seq: 11 }. The server updates Bob's single bookmark row(T1, Bob, C9) -> 11and sendsread.syncto Bob's phone so his mobile unread badge clears instantly. - Admin removes Bob from
C9(seq = 12): One transaction marks Bobremovedinmembershipsand appendsmember_removedatseq = 12. The membership cache key is invalidated (with lease protection so no slow reader refills stale data), gateways seeseq = 12before anyseq = 13and stop pushingC9to Bob, and if Bob immediately searches"Q4 numbers", the search proxy's post-check againstmembershipsblocks the hit.
Key trade-offs
- Single-row serialization per conversation vs. timestamp ordering: Locking the conversation row (or routing through a single owner node) produces a dense, gap-free sequence (
1, 2, 3, ...) so clients can detect missed messages immediately. The trade-off is a write ceiling of ~250–500 messages/s in a single channel (raised via group commit, which batches multiple queued sends into one database transaction, for bot-heavy channels). Ordering by client or server timestamps removes the row lock but suffers from clock skew—slightly mismatched clocks across machines—and cannot detect missing messages. - Fan-out on read for storage + two-tier fan-out on write for live sockets vs. per-user inboxes: Fan-out on read stores one copy of each message in the conversation log and reads it on demand, keeping disk writes
O(1)per message regardless of channel size. Live delivery still uses fan-out on write (pushing at send time), switching from per-member lookups (<= 1,000members) to gateway-level topic subscriptions (> 1,000members) so a 50,000-person channel requires at most ~150 internal network calls instead of 20,000, at the cost of maintaining subscription sets in gateway memory. - CDC / transactional outbox publishing vs. direct dual writes: Publishing events from the committed database log guarantees that every saved message is eventually broadcast and no rolled-back message ever escapes. It adds ~10–30 ms of log-tailing latency compared to pushing directly from the API server, which is faster when healthy but silently drops real-time updates and search documents if the server crashes right after database commit.
- Monotonic read pointer vs. per-message read receipts: Storing one
read_seqinteger per(tenant_id, user_id, conversation_id)eliminates multiplying message volume by channel headcount (~15B receipt rows/day vs. ~1B pointer updates/day). The trade-off is that channels cheaply track bold/unbold state (last_seq > read_seq) rather than cheap per-message "read by 4,312 people" lists, while exact unread counts are maintained separately for DMs and@mentions. - Shared database tables with row-level security vs. physical database per tenant: Hosting smaller organizations in shared tables protected by row-level security (RLS)—a database engine policy that automatically filters rows to the current session's tenant—keeps 50,000 small workspaces economical. Regulated or massive enterprises get dedicated cells (isolated regional deployments) for physical separation and data residency, trading higher infrastructure overhead for zero noisy-neighbor impact.
- Query-time search filtering + authoritative post-check vs. baking member lists into search documents: Filtering search queries by the user's conversation list and verifying returned hits against
membershipsmakes private-channel removals take effect immediately with zero reindexing. Storing all alloweduser_ids inside every message document avoids the post-check but requires rewriting millions of documents whenever someone joins or leaves a busy channel. - Viewport-scoped TTL presence vs. global exact presence: Updating presence via 30-second heartbeats with a 60-second TTL (time-to-live expiration timer) and subscribing only to the
<= 500colleagues visible on screen keeps traffic linear. Instant, org-wide presence broadcasts would create quadraticO(users^2)fan-out in 300,000-person companies for status dots users tolerate being ~30–60 seconds stale.
Common mistakes
- Reading
tenant_idfrom the request body, query string, or headers instead of extracting it solely from the cryptographically verified authentication token. - Relying on developer discipline alone for
WHERE tenant_id = ?, without forced database row-level security, tenant-scoped cache helpers, and synthetic cross-tenant canary tests. - Omitting
tenant_idfrom cache keys or search document IDs (such asconv:100:members), causing cross-tenant collisions or leaks if IDs overlap or can be guessed. - Deleting a permission cache key without preventing stale refills: a slow concurrent reader that queried the database right before a user removal can write the old member list back into the cache milliseconds after the delete unless cache leases (short-lived miss tokens invalidated on delete) are used.
- Checking
client_msg_idbefore locking the conversation row without handling concurrent retries, which lets two simultaneous retries pass the check, burn sequence numbers, or fail unexpectedly. - Generating a fresh
client_msg_idon retry, which defeats idempotency and posts duplicate messages whenever an acknowledgment packet is lost on mobile Wi-Fi. - Publishing to WebSockets before the database commits (showing "ghost" messages if the transaction rolls back) or after commit with no durable log/outbox (losing live delivery and search indexing if the server crashes).
- Treating the search index or derived
user_conversationstable as the permission authority, allowing a recently removed user to read private messages via search during replication lag. - Broadcasting presence transitions to every user in the tenant or dropping 50,000 sockets during a gateway deploy without reconnect jitter, triggering self-inflicted traffic storms.
Follow-up questions
- When senders connected to different WebSocket servers post to the same channel simultaneously, how is a single canonical message sequence established? Gateways never coordinate directly or assign sequence numbers themselves. Instead, every gateway forwards sends for conversation
(tenant_id, conversation_id)to the single database primary shard that owns that conversation row, whereSELECT ... FOR UPDATEandUPDATE conversations SET last_seq = last_seq + 1serialize concurrent arrivals into a gap-free order (N,N + 1). If a hot bot channel uses an in-memory owner service for group commit, that owner holds a lease with a fencing token—a monotonically increasing epoch number checked by the database (WHERE last_seq = :expected AND owner_epoch >= :current_epoch) so a partitioned old owner can never assign duplicate sequence numbers. - How does the system recover if a message transaction commits to storage, but the server crashes before broadcasting the live event? Because the database transaction already committed to a synchronous replica and returned
ack { seq }, we never roll the message back. Real-time publishing is decoupled from the request handler via change data capture (CDC) (or a transactional outbox table written inside the same SQL transaction), which tails the commit log and retries until the event lands on the event bus—turning a crash into a brief delay rather than a lost message. Even before that retry arrives, any subsequent message (seq + 1) lets online clients spot the missing sequence gap and pullafter_seq, while reconnecting clients catch up automatically. - When an administrator kicks a member out of a restricted channel, how do caches, live sockets, and search immediately stop serving that channel's data? A single shard transaction sets
memberships.state = 'removed'and appends amember_removedevent atseq = N. Before the API responds, the service deletes the channel's membership cache key—invalidating any active cache leases so concurrent readers cannot refill pre-removal data—while CDC repeats the delete as a backup. Becausemember_removedtravels on the same(tenant_id, conversation_id)bus partition as messages, fan-out workers and gateways processseq = Nstrictly beforeseq = N + 1, stop pushing to the user, and tell their devices to wipe local channel storage. Search requires zero reindexing because the search proxy post-checks every candidate hit'sconversation_idagainst the authoritativemembershipstable before returning results. - Where in this architecture does write-time push beat read-time pull, and vice versa? Use read-time pull (fan-out on read) for durable message history: store one row per message in the conversation's log and read ranges by
seq, because duplicating messages into 50,000 per-user inboxes wastes massive write throughput and storage for channels most members rarely open. Use write-time push (fan-out on write) only for online socket delivery and high-priority notifications (@mentionsand DMs), switching from per-member socket routing (<= 1,000members) to gateway-level pub/sub (> 1,000members) so internal network fan-out stays bounded by the number of gateway servers (~150) rather than channel membership. - If multiple workspaces share database tables, what database-level safeguards stop a developer's forgotten tenant filter from leaking rows? Enable and
FORCEPostgreSQL row-level security (RLS) on every tenant table with a policy matchingtenant_id = NULLIF(current_setting('app.tenant_id', true), '')::uuid, bindSET LOCAL app.tenant_idinside the data-access transaction wrapper using only the verified auth token, and connect with a non-superuser role that cannot bypass RLS; any query that skips the wrapper seesNULLand matches zero rows instead of leaking data. Combine RLS with composite primary/foreign keys starting withtenant_id, static linter rules banning raw SQL outside the wrapper, per-tenant envelope encryption keys, and continuous synthetic canary probes in production.
Follow-up questions
- When senders connected to different WebSocket servers post to the same channel simultaneously, how is a single canonical message sequence established?
- How does the system recover if a message transaction commits to storage, but the server crashes before broadcasting the live event?
- When an administrator kicks a member out of a restricted channel, how do caches, live sockets, and search immediately stop serving that channel's data?
- Where in this architecture does write-time push beat read-time pull, and vice versa?
- If multiple workspaces share database tables, what database-level safeguards stop a developer's forgotten tenant filter from leaking rows?
Similar questions
- Recommendation Serving and Data Platform
- Emergency 911 Call Routing Platform
- Conversational AI Metrics and Analytics Platform
- Cafe Ordering and Barista Queue Platform
- Distributed Cafe Order Management and Kitchen Dispatch System
- High-Concurrency Vehicle Rental Booking System
More Salesforce interview questions
- Architecting a Global Link-Shortening Platform Medium
- Hiring Manager Chat: Active Scope, Joining Salesforce, and Practical AI Medium
- Least Frequently Used Cache Hard Pro
- Longest Simple Path in a Tree Medium Pro
- Grid Square Area and Increasing Subsequence Length Medium Pro
- Minimum Total Peak Cost Across k Phases Medium Pro
- Hiring Manager Round: System Architecture, Greenfield Platforms, Load Surges, and Alignment Medium Pro
- Elevating Peers Through Mentorship and Sustainable Code Quality Norms Medium Pro
- Navigating Mid-Flight Course Corrections and Responsible Ownership Transitions Medium Pro
- Root-to-Leaf Path Sum Medium Pro