Skip to content

Real-time Event Stream

The SubscribeEvents RPC is the backbone of real-time interaction in mzchat. It provides a server-push stream of messages, presence updates, and state changes.

To maintain a strictly consistent global state across all clients, the server adheres to a Serialized Update Model for broadcasted events.

In a high-concurrency environment, transient state changes (like a user reconnecting or a rapid series of reactions) can trigger multiple asynchronous operations. Without serialization, it is possible for a “later” event to be processed and broadcasted before an “earlier” one (e.g., a “Connected” status arriving after a “Disconnected” status due to database read latency).

The server employs an internal Sequential Queue for sensitive state updates.

  • Per-User/Per-Resource: Events affecting a specific user’s presence or a specific message’s state are queued and executed one after another.
  • Ordered Broadcast: This ensures that the final event emitted to the stream always represents the most chronologically accurate state, preventing “flicker” or stale state reverts on the client.

Clients must treat the event stream as the primary source of truth for UI state updates.

  • Direct Cache Mutation: When an event arrives (e.g., MessageCreated, PresenceUpdate), clients should update their local data stores directly using the event payload.
  • Avoid Over-Invalidation: Clients should avoid invalidating and refetching entire resource lists (like history or member lists) upon receiving an event. Manual refetching introduces a race condition where the refetch request might reach the database before the event-triggering change has fully persisted, resulting in stale data.

The event stream is authorized at the point of connection.

  • Token Swap: If a client receives a new JWT (e.g., after joining a guild), it must abort the current stream and reconnect with the new credentials to ensure the stream context reflects the updated permissions.