Workspace Chat Platform with Per-Org Isolation
System DesignModel answerLast updated
Design a chat backend for many isolated organizations, covering ordered channel history, offline catch-up, permission-aware search, presence, and read tracking.
Context
You are building the core backend for a workplace chat product. Many independent organizations (tenants) use it. Each organization has its own people, channels, and admins, and nothing one organization stores may ever be visible to another.
The product supports:
- One-to-one direct messages and group conversations.
- Three kinds of channels: public (anyone in the org can find and join), private (invite-only but discoverable to members), and invitation-only (hidden from non-members).
- Administrator roles that control channel creation, membership, and moderation.
- Durable message history that can be searched.
- Real-time delivery to people who are online, and catch-up for people who were offline.
- Online presence and per-user read positions.
A single person may belong to several organizations. Their identity is global, but their role and permissions are scoped to each organization they belong to.
Requirements
- Messages are durable once the sender receives confirmation.
- Within one conversation, every participant sees the same message order. There is no ordering requirement across different conversations.
- Channels may have anywhere from a handful of members to many thousands.
- Clients reconnect often and may resend a message if they never received an acknowledgment.
- Search results and search indexes follow the same tenant and conversation permissions as direct reads.
What to cover
Explain your choices for:
- The core data model (tenant, user, membership, conversation, message, read position, idempotency key).
- How messages get their order and how duplicate sends are prevented.
- The write path and the real-time fan-out path, including reconnect and offline catch-up.
- Where and how permissions are enforced.
- Fan-out strategy for very large channels.
- Tenant isolation, from shared storage with enforced policies up to dedicated storage for large or regulated tenants.
- Search indexing that respects permissions, and how deletions and retention apply to it.
- Presence and read-receipt design, failure handling, and observability.
Before designing, state assumptions about peak message rate, tenant size distribution, retention, attachment limits, and whether edits, deletes, threads, or legal holds are in scope.
Hints
Hint 1
Separate the durable write from the real-time push. Assign the per-conversation sequence number at write time, and only fan out after the message is committed.
Hint 2
Make sends idempotent by giving each client-generated message a unique key scoped to the conversation. A retry with the same key should return the original message rather than creating a second one.
Hint 3
Permission checks belong on every path that returns data: writes, reads, push delivery, and search hits. Consider putting the tenant ID into every key and query, and treating the search index as a copy that inherits the same access rules.
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Core data model
- Tenant (organization): ID, plan, region, isolation tier.
- User: global identity with a stable ID.
- Membership: (tenant_id, user_id) with role (member, admin) and status. Permissions live here, so the same person can be an admin in one org and a guest in another.
- Conversation: (tenant_id, conversation_id), type (DM, group, public, private, invite-only), and a monotonically increasing
last_seq. - Conversation member: (tenant_id, conversation_id, user_id) with joined_at and a last-read sequence.
- Message: (tenant_id, conversation_id, seq) as the primary key, plus sender, body reference, client_msg_id, created_at, and tombstone flags.
- Idempotency record: (tenant_id, conversation_id, sender_id, client_msg_id) mapped to the assigned seq.
Partition all conversation data by (tenant_id, conversation_id). That keeps each conversation's ordering local to one partition, and it keeps every tenant's data grouped together for isolation and for moving a tenant later.
Ordering and idempotent sends
Each conversation has a single writer at any moment, which is its partition leader. The leader performs the following steps in one transaction:
- Check the idempotency record. If the client_msg_id already exists, return the stored seq and skip everything else.
- Verify the sender is a current member with send rights.
- Increment
last_seq, insert the message at that seq, and write the idempotency record. - Commit, then acknowledge the sender with the seq.
Because the sequence is assigned by the server, every member sees the same order, and a client that resends after losing an ack gets the same result. Gaps are not allowed. If a write fails after incrementing, roll the whole transaction back so the sequence stays contiguous.
Sending throughput per conversation is limited by one leader's commit rate. For a busy channel this is usually fine, since human messaging rarely exceeds a few hundred messages per second in one room. If it ever doesn't, batch small writes within the leader.
Delivery, reconnect, and offline catch-up
Clients keep a long-lived connection to a stateless gateway. Each gateway subscribes to the conversations its connected users belong to. After commit, the leader publishes (tenant, conversation, seq, message) to a topic. Gateways push to local sockets.
Reconnection uses cursors: the client sends its last seen seq per conversation, and the server returns everything after it. Gaps are then impossible to miss, because the client can always detect a jump in seq and request the missing range.
Push is best effort. The durable history is the source of truth. A client that has been offline for days just pages history from its cursor. Offline users also get a push notification, sent through a separate queue so that slow notification providers cannot back up chat delivery.
Backpressure: if a gateway's send buffer for a socket fills up, drop that socket's realtime stream and force it to resync from its cursor instead of stalling the whole gateway.
Permissions
Authorization runs on the server for every operation:
- Writes: membership and send rights are checked inside the leader's transaction, so a membership revocation that commits before the write wins.
- Reads: history queries join through membership. A user who joins an invitation-only channel sees history only from their join point if that is the policy; that rule should be encoded explicitly.
- Fan-out: the subscription list is derived from current membership, not from what the client asks for.
- Search: the index stores tenant_id, conversation_id, and a visibility key. Queries filter by the caller's accessible conversation set. If a permission changes, the index doesn't need reindexing if the filter is computed at query time from membership.
Public channels can be visible to all members of the org. Private channels appear only to their members. Invitation-only channels are not enumerable at all, so even listing them should respect that.
Large-channel fan-out
A channel with 10,000 members receiving 10 messages per second means 100,000 deliveries per second from one message stream. Pushing that per-socket from the leader doesn't scale. Options:
- Gateway-level fan-out: the topic carries one event per message. Each gateway holds subscriptions for its local users and pushes to them. Cost scales with gateway count, not with publisher work.
- Lazy fetch for huge channels: above a threshold, don't push message bodies to everyone. Push a "new seq available" hint, and clients fetch the body when they view the channel. This cuts bandwidth dramatically.
- Rate limiting noisy senders protects the leader and the fan-out path.
Tenant isolation
Tiers, chosen per tenant:
- Shared tables, enforced everywhere: tenant_id in every key, row-level security or mandatory query scoping in the data access layer, and automated tests that try cross-tenant reads.
- Shared cluster, separate schemas or databases: stronger blast-radius containment for mid-sized tenants.
- Dedicated storage: for large or regulated tenants, or those with data residency requirements. The same code runs with a different routing table.
Routing maps tenant_id to a storage cluster, so moving a tenant between tiers is a data migration, not a code change. Caches and queues are keyed by tenant too, so one tenant's traffic spike doesn't evict another's cache entries.
Search
Index message text asynchronously from the commit log, so search lag is measured in seconds and never blocks writes. Each indexed document carries tenant_id, conversation_id, and seq. Queries always include the tenant filter and the caller's conversation set. Results are re-checked against membership before returning, since the index can lag behind a removal.
Deletion and retention: tombstones propagate as index delete events. Legal holds suspend deletion for the held conversations. Compliance exports should go through the same permission filter as search, with an audit record.
Presence and read positions
Presence uses leases: a client renews a short-lived key (for example every 30 seconds). A user is "online" if their lease is live. Presence is eventually consistent and can be stale by tens of seconds. That is acceptable for a status dot but not for delivery decisions, which should rely on connection state.
Read positions are a per-member last-read seq. Writing one row per message per member is expensive, so update the read position only when the client reports it, throttled to once every few seconds. Unread counts are computed as last_seq - last_read_seq, and read receipts are summarized rather than stored per message in large channels.
Failure and observability
- If a leader crashes, a new leader is elected from the replica set. Since the sequence lives in the committed log, the new leader continues from the last committed seq. Clients that sent during the failover retry with their client_msg_id.
- Monitor per-partition commit latency, fan-out lag, gateway buffer drops, search indexing lag, and cross-tenant policy test failures.
- Audit log admin actions, permission changes, exports, and legal-hold changes with tenant and actor IDs.
- Recovery: because history is the durable log and indexes and presence are derived, they can be rebuilt from it.
Common mistakes
- Using client timestamps for ordering, which breaks under clock skew.
- Fanning out before commit, so a rolled-back message is delivered to some users.
- Checking permissions only at connection time, not on every write and read.
- Filtering search results only in the UI instead of at query time.
- Storing one row per member per message for read receipts in large channels.
- Treating tenant isolation as a single WHERE clause that any new query can forget.