Skip to content

Feature: Real-time Collaboration Infrastructure

Overview

Real-time Collaboration Infrastructure provides the foundation for live, multi-user interactions in Teams. A server-sent event stream carries thread changes, a WebSocket carries CRDT synchronization (Yjs) and awareness for collaborative drafts. Together they let team members see each other's actions instantly, edit drafts simultaneously, and stay coordinated without page refreshes.

Technical Architecture: See Technical Patterns for detailed patterns on WebSocket notifications and Yjs/CRDT synchronization.

Feature Purpose

Modern team collaboration requires real-time awareness. This infrastructure ensures that when one team member assigns a thread, adds a comment, or edits a draft, all other team members see the change immediately. It transforms Teams from a static view into a living, collaborative workspace.

User Value Proposition

For All Users:

  • See teammates' actions instantly (no refresh needed)
  • Collaborate on drafts with Google Docs-like experience
  • Know who's working on what in real-time
  • Offline-capable with automatic sync when reconnected
  • Conflict-free editing (CRDT guarantees)

For Teams:

  • Coordinated work without stepping on toes
  • Live awareness prevents duplicate efforts
  • Faster decision-making with instant updates
  • Better communication through presence

For Organizations:

  • Modern, responsive user experience
  • Reduced wasted effort from conflicts
  • Improved productivity through real-time coordination
  • Scalable architecture for growing teams

Key Capabilities

1. Connection Management

Description: Long-lived connections for real-time updates, kept open without user action.

User Experience:

  • Event stream opens automatically once the app knows how to authenticate
  • Reconnects on its own after a network drop or a backend rollout
  • Catches up on what it missed once reconnected
  • Degrades to refetch-on-navigation if the stream cannot be opened at all

Acceptance Criteria:

  • Event stream opens within 2 seconds of app start
  • Reconnection with exponential backoff from 1s to 30s, plus jitter
  • Reconnects immediately when the network returns or a hidden tab is activated
  • Reconnects before its token expires, rather than after being rejected
  • Reconnects indefinitely; there is no attempt limit that requires user action

2. Thread Change Notifications

Description: Every thread change reaches every team member watching that inbox.

User Experience:

  • New comments appear automatically
  • Assignment changes update instantly
  • Status/tag changes reflect immediately
  • New mail from the background import appears in the list
  • No manual refresh required

Acceptance Criteria:

  • Updates delivered within 1 second (p95)
  • The author sees their own change like every other recipient
  • Repeated events for one thread collapse into a single reload
  • A lost event costs freshness, never correctness: the next reconnect or activation reloads
  • Only users entitled to the inbox receive its events

3. Draft Collaboration Sync

Description: Real-time synchronization of collaborative draft edits using CRDT.

User Experience:

  • Multiple users edit same draft simultaneously
  • Changes appear within 100-500ms
  • No conflicts or lost edits
  • Cursor positions visible
  • Selection highlights for each user
  • Smooth editing experience

Acceptance Criteria:

  • Yjs document syncs via custom WebSocket provider
  • Binary updates for efficiency (< 1KB typical)
  • Offline edits queued and replayed
  • Conflict-free merging guaranteed
  • Supports 10+ simultaneous editors

4. User Awareness and Presence

Description: Show who's currently active and where they're working.

User Experience:

  • See active users in draft editor
  • Cursor positions with name labels
  • User avatars in collaboration UI
  • Real-time join/leave updates
  • Presence persists during activity

Acceptance Criteria:

  • Awareness updates within 1 second
  • User info includes name, email, color
  • Presence timeout after 30 seconds inactivity
  • Maximum 50 users tracked per thread
  • Efficient awareness propagation

5. Optimistic UI Updates

Description: Update UI immediately while syncing to backend.

User Experience:

  • Actions feel instant (no waiting)
  • Success assumed initially
  • Rollback on error with notification
  • Retry logic for transient failures
  • Loading states for long operations

Acceptance Criteria:

  • UI updates before API response
  • Rollback mechanism for all actions
  • Error messages shown to user
  • Retry up to 3 times with backoff
  • Optimistic state marked visually (future)

6. Offline Resilience

Description: Keep working when the connection drops, and catch up when it returns.

User Experience:

  • Draft edits continue while the Yjs connection is down
  • The thread view catches up by itself once the connection returns
  • Coming back to a backgrounded tab shows current data
  • Conflicts in drafts resolved automatically

Acceptance Criteria:

  • Yjs merges offline draft edits conflict-free on reconnect
  • The event stream reconnects with exponential backoff (1s to 30s)
  • Every reconnect reloads the folder list, the thread list and the open thread
  • Returning to a hidden tab triggers the same reload
  • Correctness never depends on an event arriving: push only reduces latency

7. Event Propagation

Description: Tell every team member about a change, from the system of record.

User Experience:

  • Comments, assignments, status, tags and drafts appear for everyone watching
  • New mail from the background import appears without pull-to-refresh
  • Mentions and assignments reach only the person they address
  • The author sees their own change like everyone else
  • No reload needed, and nothing depends on the acting user's browser

Acceptance Criteria:

  • Events are published by the backend inside the transaction that writes the change
  • An event never describes a change that was rolled back
  • Events carry identifiers only; clients reload through the REST API
  • Events reach a user only for inboxes they can see, or when addressed to them
  • Repeated or reordered events are harmless

Technical Architecture

Transports

Two server-to-client channels, both authenticated the same way as the REST API:

  • /teams/ws — the Yjs WebSocket for collaborative drafts (binary, bidirectional)
  • /teams/api/events — the Server-Sent Events stream for thread events (text, one-directional)

Custom Yjs Provider (ADR-0008):

  • Extends WebsocketProvider from y-websocket
  • Custom sync protocol for Teams
  • Awareness protocol for presence
  • PostgreSQL persistence (yjs_documents, ADR-0028)
  • Handles reconnection and auth

Thread Event Stream (ADR-0023):

  • Path: GET /teams/api/events, one long-lived Server-Sent Events response per user
  • Same authentication as every other API call (bearer token, or the session cookie in session-forwarding mode)
  • Read with fetch() + ReadableStream rather than EventSource, because the App Suite service worker caches the request unless it carries service-worker-strategy: network-only and EventSource cannot set headers
  • Heartbeat comment every 15s keeps proxies and idle-socket timeouts from closing it
  • A rolling backend sends event: shutdown before ending the stream

Event Types:

  • thread.changed: comment, assignee, status, tags, spam/not-spam, draft created/closed/sent
  • thread.created: a new discussion thread or feedback submission
  • inbox.synced: the background mail import committed changes to an inbox
  • thread.mention: someone mentioned this user (sent to that user only)
  • thread.assigned: a thread was assigned to this user (sent to that user only)
  • Yjs sync messages (binary) and awareness updates, on the separate /teams/ws socket

Message Flow

Thread Event:

The publisher is the backend, not the acting user's browser, and PostgreSQL fans the event out to every replica. The author is among the recipients, so no client-side workaround is needed to show someone their own change.

Draft Collaboration:

CRDT Synchronization (Yjs)

Why Yjs? (ADR-0007):

  • Conflict-free replicated data type
  • Automatic merge without coordination
  • Works offline with eventual consistency
  • Small binary updates (efficient)
  • Proven technology (used in major apps)

Yjs Document Structure:

{
  mailContent: Y.XmlFragment,  // Draft body
  meta: Y.Map({
    subject: string            // Draft subject
  })
}

Sync Protocol:

  1. Client connects to WebSocket provider
  2. Server sends current document state
  3. Client applies state to local Yjs document
  4. Subsequent edits sent as binary diffs
  5. Server persists updates to PostgreSQL
  6. Server broadcasts to other clients

Awareness Protocol

Local State:

provider.awareness.setLocalStateField('user', {
  id: userId,
  context: contextId,
  name: displayName,
  email: userEmail,
  color: '#3b82f6'  // User-specific color
})

Awareness Events:

  • change: User joined, left, or updated state
  • update: Cursor/selection changed
  • Throttled to 100ms for performance

Cursor Tracking:

  • TipTap Collaboration extension
  • Syncs cursor position with Yjs
  • Displays cursors with name labels
  • Color-coded per user

API Integration

Publishing (backend): every route that changes a thread publishes inside its own transaction, so the event and the write commit or roll back together:

await db.transaction(async (tx) => {
  await tx.insert(actions).values(action)
  await publishThreadEvent(tx, {
    type: 'thread.changed',
    inboxId: inbox.id,
    threadId: thread.id,
    actor: {id: req.user.userId, context: req.user.contextId}
  })
})

Fan-out: each replica holds one dedicated LISTEN connection outside the pool. It forwards an event to the browsers it serves whose user is a member of the affected inbox, or, for thread.mention and thread.assigned, to the addressed user only.

WebSocket Backend (Fastify):

  • Custom WebSocket plugin
  • JWT verification on connect
  • Room-based routing (thread ID)
  • Yjs persistence integration
  • Graceful shutdown handling

State Management

Event Stream (ui/teams/events/teams-events.ts): a plain module, not a store. It exposes start(), stop(), a reactive connected flag, on(handler) for events and onResync(cb) for "reload what you show". It is started from main.ts once the auth mode is known.

connected is what the store checks before falling back: while it is false, posting a comment, changing a status or creating a draft reloads the timeline locally, and a syncing thread list still makes the blocking ?awaitSync=true follow-up request.

Event Handlers (ui/teams/stores/threads.ts):

function handleThreadEvent(event) {
  switch (event.type) {
    case 'thread.changed':   // coalesced per thread (250ms)
      return applyThreadChange(event)   // reload the thread, and its timeline if open
    case 'thread.created':
    case 'inbox.synced':     // debounced per inbox (500ms)
      return refreshInbox(event.inboxId) // reload the list if shown, plus folder counts
    case 'thread.mention':
      return applyMention(event)         // highlight, refetch 'Shared with me', ring the bell
    case 'thread.assigned':
      return refreshBellFromServer()
    default:
      return Promise.resolve()           // unknown types are ignored
  }
}

The bell is never built from event payloads. A mention or assignment event only says that something addressed to this user happened; the store then reloads GET notifications/unread, which is the same path used to rehydrate the bell after a reload.

Resync: on every reconnect (not the first connect) and when a hidden tab becomes visible, the store reloads the folder list, the current thread list and the open thread's timeline — the same unit pull-to-refresh runs.

Performance Optimizations

  • Coalescing: repeated events for one thread collapse into a single reload (250ms), and per-inbox list reloads are debounced (500ms)
  • Ids, not payloads: events stay small, and the client fetches only what it shows
  • Binary Protocol: Yjs uses efficient binary encoding
  • Throttled Awareness: Cursor updates throttled to 100ms
  • Exponential Backoff: event stream reconnects at 1s, 2s, 4s … up to 30s, with jitter
  • Proactive token rotation: the stream reconnects about a minute before its token expires, instead of waiting for the connection to be rejected

Security

Authentication:

  • The Yjs WebSocket takes the JWT as a query parameter, since a WebSocket cannot set headers
  • The event stream uses the normal Authorization: Bearer header, so no token reaches a URL or an access log; in session-forwarding mode it forwards the App Suite session cookie
  • Validated on connection; a 401 makes the client re-acquire its token before retrying

Authorization:

  • Room access based on inbox permissions
  • Users only receive events for inboxes they are a member of, or events addressed to them
  • Draft access validated per thread
  • No cross-inbox leakage

Rate Limiting:

  • Maximum 100 messages per second per user
  • Awareness updates throttled
  • Large documents chunked
  • Connection limits per IP (future)

UI/UX Design

Connection Indicator (Future)

┌────────────────────────────────┐
│ 🟢 Connected · 3 active users │
└────────────────────────────────┘

Offline:
┌────────────────────────────────┐
│ 🔴 Offline · Changes saved    │
│    locally                     │
└────────────────────────────────┘

Draft Collaboration UI

┌────────────────────────────────┐
│ Active: JD, JS, BJ            │
│         └─ user avatars        │
└────────────────────────────────┘

In draft:
Dear customer█John Doe,
           └─ cursor with label

Visual Feedback

  • Cursor colors: Generated from user ID hash
  • Loading states: Pulse animation
  • Error states: Red banner with retry
  • Offline state: Yellow banner
  • Connection status: Dot indicator

Dependencies

  • Yjs: CRDT library for conflict-free sync
  • y-websocket: Base WebSocket provider
  • yjs_documents: Server-side persistence, one snapshot per thread
  • y-indexeddb: Client-side persistence
  • TipTap: Editor with collaboration support
  • PostgreSQL (ADR-0006)
  • WebSocket support in Fastify

Known Limitations

  • Events are not durable: those published during a PostgreSQL failover or while a client is reconnecting are lost, and the reload on reconnect is what covers the gap
  • Two separate server-to-client channels; consolidating them is still open (ADR-0008)
  • The event stream needs a PostgreSQL endpoint that is not behind a transaction-mode connection pooler, because LISTEN is session state
  • Awareness not persisted (lost on disconnect)
  • No connection-status indicator in the UI

Future Enhancements

  1. Connection Status UI: Visual indicator of connection state
  2. Presence Panel: List of active users with status
  3. Typing Indicators: Show who's typing in comments
  4. Activity Feed: Real-time log of all actions
  5. Push Notifications: Browser notifications for events
  6. Conflict Resolution UI: Manual conflict resolution (edge cases)
  7. Bandwidth Optimization: Adaptive sync based on connection
  8. Mobile Optimization: Efficient sync for mobile networks
  9. Analytics: Track collaboration metrics
  10. Audit Log: Persistent log of all real-time events
  • Collaborative Draft Editing (primary consumer)
  • Thread Management (action notifications)
  • Assignment Workflow (assignment notifications)
  • Tags and Status (update notifications)
  • ADR-0007: Introduce Yjs to share state
    • Rationale: CRDT for conflict-free collaboration
    • Evaluated alternatives: OT, manual merge
    • Decision: Yjs for proven technology and ecosystem
  • ADR-0008: Use own WebSocket for Yjs
    • Rationale: Custom sync protocol for Teams
    • Integration with PostgreSQL persistence
    • Authentication requirements
  • ADR-0006: Database layer
    • Yjs documents stored in PostgreSQL
    • Persistence across restarts
  • ADR-0023: Server-side thread events
    • Rationale: the acting user's browser is the least reliable publisher
    • PostgreSQL LISTEN/NOTIFY for cross-replica fan-out, Server-Sent Events to the browser
    • Supersedes the Switchboard-based notification architecture and removes that dependency

Success Metrics

  • Latency: Message delivery < 1 second (p95)
  • Reliability: Sync success rate > 99.9%
  • Availability: WebSocket uptime > 99.95%
  • Conflict Rate: Zero CRDT conflicts
  • Reconnection: Average time < 5 seconds
  • Offline Sync: 100% data integrity after reconnect
  • User Experience: Perceived as "instant" (< 200ms)
  • Scalability: Support 100+ concurrent users per thread
  • Efficiency: < 10KB/minute bandwidth per user

Monitoring and Observability

Metrics to Track:

  • WebSocket connection count
  • Message delivery latency
  • Sync success/failure rate
  • Reconnection frequency
  • Offline queue size
  • Yjs document size
  • Awareness update frequency

Alerts:

  • Connection failures > 5%
  • Sync latency > 2 seconds
  • Reconnection loops detected
  • Message queue backlog > 100

Testing Strategy

  • Unit Tests: CRDT merge operations
  • Integration Tests: WebSocket message flow
  • E2E Tests: Multi-user collaboration scenarios
  • Load Tests: 100+ concurrent users
  • Chaos Tests: Network interruptions, disconnects
  • Offline Tests: Offline editing and sync