Realtime subscriptions and presence
The realtime and presence services help an application keep an active view of changes and participants. Realtime subscriptions deliver matching events through a shared WebSocket connection. Presence operations publish and manage the state that identifies active participants. The parent page, Realtime and utility services, places these services beside the SDK's other service APIs. Locale and avatars covers related utility services.
Realtime subscriptions
The Realtime service provides a long-lived event channel for application updates. A caller selects channels and optional query filters, then receives matching event envelopes through a callback instead of polling. The service shares one connection across active subscriptions and presence publication.
Channel selection
Channels define the event scope that a subscription observes. Callers can pass channel names or channel builders. The service turns each value into its wire name, removes duplicate names within one subscription, and normalizes query filters before sending them.
Presence supports broad and participant-specific channel scopes. This lets an application observe activity for all participants or narrow events to one participant's resource. src/channel.ts, src/channel.ts, src/channel.ts
References: src/channel.ts• L19-49 src/channel.ts• L77-92 src/channel.ts• L124-159 src/…/realtime.ts• L489-510 src/…/realtime.ts• L568-588
Subscription lifecycle
A subscription is a client-owned registration that maps a callback to channel names and query filters. The service opens a connection when a subscription needs one and sends the registration only after the server confirms the application-level connection.
The public subscribe call returns a RealtimeSubscription with three lifecycle operations:
unsubscriberemoves only that registration and keeps the shared connection available to other subscriptions.updatereplaces its channels or queries without replacing its callback.closeremoves the registration and also closes the connection when it was the last active subscription. Usedisconnectfor full service shutdown.
The service assigns each registration a unique ID and keeps pending registrations until the connection is ready. A short delay groups close subscription changes. Reconnects restore the active registrations. src/…/realtime.ts, src/…/realtime.ts, src/…/realtime.ts
References: src/…/realtime.ts• L12-29 src/…/realtime.ts• L175-205 src/…/realtime.ts• L391-487 src/…/realtime.ts• L568-672
Connection lifecycle
The connection carries the project and optional environment context from Client. The client also supplies the realtime endpoint and session settings used to establish and authenticate the connection. The service sends a heartbeat while the socket is open and retries unexpected closes with increasing delays. A policy-violation close does not enter the retry path. src/client.ts, src/client.ts, src/…/realtime.ts
When the connection starts or recovers, the service follows this sequence:
- The client opens the project-scoped connection.
- The server sends
connected. If needed, the client sends the current session for authentication. - The service marks the application connection ready and sends active subscription registrations and the latest queued presence state.
- The server sends events. The service routes each event to the callbacks named by its subscription IDs.
The diagram shows how one shared connection restores subscriptions and presence after a connection starts or recovers.
sequenceDiagram
participant App as Application
participant Realtime as Realtime service
participant Server as Appwrite realtime
App->>Realtime: Subscribe or publish presence
Realtime->>Server: Open project connection
Server-->>Realtime: connected
Realtime->>Server: Authenticate if needed
Realtime->>Server: Send subscriptions and latest presence
Server-->>Realtime: Event envelope
Realtime-->>App: Matching callback
Client also retains a lower-level realtime transport path for its legacy subscribe API. The service API and this client path share the same project-scoped realtime contract, but the service API provides explicit subscription objects and connection callbacks. src/client.ts, src/client.ts, src/client.ts
References: src/client.ts• L129-182 src/client.ts• L575-869 src/client.ts• L872-927 src/…/realtime.ts• L198-343 src/…/realtime.ts• L739-801
Event delivery
An event is a typed envelope rather than a bare payload. It identifies event names, matching channels, a server timestamp, the payload, and the subscription IDs that matched the event. The service uses those IDs to call only the registered callbacks for that event. Events without the required channel, event, payload, or subscription data are ignored. src/client.ts, src/…/realtime.ts, src/…/realtime.ts
Connection state is available through onOpen, onClose, and onError callbacks. These hooks let an application track the transport state while subscription callbacks handle application events. src/…/realtime.ts, src/…/realtime.ts
References: src/client.ts• L160-166 src/…/realtime.ts• L42-48 src/…/realtime.ts• L117-157 src/…/realtime.ts• L739-847
Presence records
The Presences service manages short-lived participant state. A presence record links a user to a current status and can include metadata, permissions, and an expiry time. The service lists active records, reads one record, creates or replaces state, changes selected fields, and deletes a record. These records give an application a readable active set that can recover from missed realtime events.
Presence model
A presence record is the service view of a participant's current activity. Its identity, user link, status, source, timestamps, permissions, metadata, and optional expiry describe both the participant and the lifetime of that state.
List results provide a total count and an array of records. Expired records are excluded from active results, and a direct read treats an expired record as not found. A caller can select an in-memory cache lifetime for list results. The cache is separated by project, schema version, caller permissions, and exact query. Presence writes do not invalidate it automatically. src/models.ts, src/models.ts, src/…/presences.ts, src/…/presences.ts
References: src/models.ts• L36-48 src/models.ts• L324-364 src/…/presences.ts• L11-25 src/…/presences.ts• L99-107
Presence lifecycle
Presence state follows a resource lifecycle that separates discovery from change. list finds active records with optional queries and total-count control. get reads one record by presence ID. upsert creates a record or replaces its current state. update changes only supplied fields. delete removes the record.
An application can track a participant through a session:
- Create or refresh the record with
upsert. - Read one participant with
get, or find active participants withlist. - Change status, expiry, metadata, or permissions with
updateas activity changes. - Remove the record with
deletewhen the participant leaves.
List responses can remain cached after a presence write until their selected time-to-live ends. An update can request a purge of cached list responses when a later list must show the write at once. src/…/presences.ts, src/…/presences.ts, src/…/presences.ts
References: src/…/presences.ts• L161-291 src/…/presences.ts• L293-432 src/…/presences.ts• L434-492
Realtime presence updates
Realtime.upsertPresence is the fast path for publishing current participant state over the realtime connection. It stores the latest status, presence ID, permissions, and metadata in memory, then sends that state after the connection is ready. If several calls occur before delivery, the newest state replaces older queued state.
This path complements the Presences service. Realtime presence upsert announces activity quickly, while presence operations read and manage the corresponding records. After reconnect, the latest queued presence is sent again after the server's connected signal. src/…/realtime.ts, src/…/realtime.ts, src/…/realtime.ts
The combined participant view uses both signals. Realtime events refresh the view quickly. Presence reads provide the current active set and help recover state after a missed event.
flowchart LR
Activity[Participant activity] --> Publish[Realtime presence upsert]
Publish --> Events[Realtime presence events]
Events --> View[Active participant view]
Records[Presence records] --> Reads[Presence list or single read]
Reads --> View
Activity --> Manage[Presence upsert update or delete]
Manage --> Records
References: src/…/realtime.ts• L60-78 src/…/realtime.ts• L674-737 src/…/realtime.ts• L760-801 src/…/presences.ts• L11-25 src/…/presences.ts• L161-492
Change checklist
When these files or sections are changed, remember to consider these:
- When channel names or action paths change, check channel builders and the subscription inputs that turn them into wire names.
- When event envelope fields or subscription IDs change, keep callback routing aligned with the server event contract.
- When connection readiness or reconnect behavior changes, preserve the order between
connected, authentication, registration, and presence publication. - When presence fields or expiry rules change, check the presence model, realtime presence payload, and REST presence operations together.
- When presence caching changes, check whether list results need explicit purge after updates or other writes.
- When public realtime or presence types change, update the service contract and its public exports.
- When the client realtime endpoint, project context, or session settings change, keep the service's connection URL and authentication flow aligned.
- When subscription teardown changes, keep
unsubscribe,close, anddisconnectbehavior distinct so one registration does not close a connection used by others. - When the service and legacy client realtime paths change, check that both still honor the shared event and connection contract.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| A subscription is closed instead of only unsubscribed | The last subscription can close the shared connection | Use unsubscribe for one registration and disconnect only for full shutdown |
A registration is sent before the server's connected signal | The server can reject the frame and close the connection for a policy violation | Let the service finish the application-level handshake before sending registrations |
| A connection closes while subscriptions or presence state are active | The application stops receiving updates until active state is restored | Keep active state and use the reconnect path; use a presence read to recover the view if needed |
| A presence record reaches its expiry time | List and direct-read calls no longer return it as active state | Refresh the record before expiry or treat an absent record as inactive |
| A presence update is followed by a cached list read without purge | The participant list can show stale status or metadata | Set the update purge option when the next list must reflect the write at once |
disconnect runs while the application still needs realtime state | All subscriptions and queued presence state are cleared | Call disconnect only when the feature or client is shutting down |
| An event lacks subscription IDs or the client no longer has the active registration | The event is ignored or cannot reach its callback | Preserve the subscription registration and the server event contract |
| Subscription and presence calls race while opening the socket without shared connection control | Duplicate WebSocket connections can receive overlapping state | Use the service's single connection-opening guard |
Key files
| File | Why to read it |
|---|---|
| src/…/realtime.ts | Defines channel conversion, subscription lifecycle, event delivery, connection recovery, and realtime presence publication. |
| src/client.ts | Defines client endpoint and session settings and retains the lower-level realtime transport used by the client API. |
| src/…/presences.ts | Defines listing, reading, upserting, updating, and deleting presence records. |
| src/channel.ts | Defines the channel names and resource actions that subscriptions can observe. |
| src/models.ts | Defines the presence record and presence-list result returned by the service. |
| src/index.ts | Shows the public exports for Realtime, Presences, Channel, and their key types. |