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.
Consistency & Concurrency
Section titled “Consistency & Concurrency”To maintain a strictly consistent global state across all clients, the server adheres to a Serialized Update Model for broadcasted events.
The Race Condition Problem
Section titled “The Race Condition Problem”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).
Serialized Update Queues
Section titled “Serialized Update Queues”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.
Client-Side Integration
Section titled “Client-Side Integration”The Source of Truth
Section titled “The Source of Truth”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.
Connection Lifecycle
Section titled “Connection Lifecycle”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.