WebSocket subscriptions
WebSocket subscriptions let a Connection receive live events from a Solana RPC node. The connection keeps the HTTP request path and the WebSocket event path as separate transports, then joins them at the public listener API. This page extends Connection and RPC and relates to RPC connection operations and Kit adapters.
WebSocket transport
The WebSocket transport carries long-lived RPC PubSub streams. Connection uses the configured HTTP endpoint for request and response work and creates a separate subscription runtime for live events.
Endpoint selection
Callers can set ConnectionConfig.wsEndpoint when the RPC service exposes WebSocket traffic at a custom route or port. Without that setting, the connection derives the WebSocket endpoint from the HTTP endpoint. An explicit HTTP port is shifted by one for the node's direct WebSocket port; an endpoint without a port keeps its protocol default for reverse-proxy use.
The connection also passes subscriptions.channelConfig to the runtime. This lets the transport set channel limits and timing without changing the listener contract.
References: packages/…/connection.ts• L2877-2899 packages/…/connection.ts• L2985-3048 packages/…/makeWebsocketUrl.ts• L1-20
Socket lifecycle
The subscription runtime opens a channel when the first active subscription needs it. When the channel connects, the controller updates all logical subscriptions. When no listener remains, the runtime schedules a short idle close so a new registration can reuse the channel without keeping an unused connection open.
The runtime owns transport errors and notification streams. The controller owns the subscription intent and tells the runtime when to open or stop each stream. This split keeps socket events from changing the public listener model directly.
References: packages/…/connection.ts• L3021-3048 packages/…/runtime.ts• L326-371 packages/…/runtime.ts• L385-437 packages/…/runtime.ts• L667-675
Subscription lifecycle
The subscription lifecycle separates an application callback from the server stream that carries its events. Connection builds a normalized subscription specification, registers it with the controller, and returns a client subscription ID for later removal.
Registration and removal
Each listener receives a client subscription ID. The controller groups callbacks with the same subscription kind and equivalent normalized arguments into one logical server subscription. This can reduce duplicate RPC streams while keeping callback-level removal independent.
When a listener is removed, the client callback is detached first. The controller sends the matching server unsubscribe only when no callback still uses that logical subscription. Removal is asynchronous because the stream may need to finish its server-side shutdown.
The client also exposes awaitSubscriptionReady. It waits for a registered subscription to become established, rejects when setup fails or the subscription becomes inactive, and can stop waiting through an abort signal.
References: packages/…/connection.ts• L6531-6569 packages/…/connection.ts• L6571-6632 packages/…/controller.ts• L181-233
Subscription states
The controller tracks the shared logical subscription as it moves between client intent and server work:
| State | Meaning |
|---|---|
pending | The stream must be opened or opened again. |
subscribing | The stream is being established. |
subscribed | The server stream is active. |
unsubscribing | The server stream is being stopped. |
unsubscribed | The server stream has stopped. |
failed | The most recent setup attempt failed. |
The controller prunes a subscription with no callbacks when it is safe to do so. If a callback is removed while setup is in flight, the resulting server stream is stopped or discarded instead of being left active.
References: packages/…/controller.ts• L235-436 packages/…/registry.ts• L1-260
Notification dispatch
The runtime tags each incoming event with its subscription kind and server ID. The controller then converts the payload to the public callback shape and dispatches it to every callback still attached to that logical subscription.
The main notification mappings are:
| Subscription | Callback data |
|---|---|
| Account | Account value and RPC context. |
| Program account | Changed account address, account value, and RPC context. |
| Logs | Transaction signature, emitted logs, error, and RPC context. |
| Signature | A received event or a terminal status and RPC context. |
| Slot | Current slot, parent slot, and root slot. |
| Slot update | A block-progress event such as completion, freeze, death, or root. |
| Root | The new root slot. |
The dispatch path checks the server ID before invoking callbacks. A callback error is logged without stopping other callbacks for the same event. A terminal signature status marks the server stream as already disposed, so later client cleanup does not send a redundant unsubscribe.
References: packages/…/runtime.ts• L678-761 packages/…/controller.ts• L47-160 packages/…/connection.ts• L6865-6947
The following sequence shows how a listener becomes a server subscription and how an event returns to application code.
sequenceDiagram
participant App as Application
participant Conn as Connection
participant Controller as Subscription controller
participant RPC as RPC WebSocket
App->>Conn: Register listener
Conn->>Controller: Store normalized subscription
Controller->>RPC: Subscribe with specification
RPC-->>Controller: Notification with server ID
Controller->>Conn: Map payload to public callback data
Conn->>App: Invoke matching callbacks
App->>Conn: Remove listener
Conn->>Controller: Remove client subscription
Controller->>RPC: Unsubscribe when no callback remains
Reconnection behavior
An unexpected channel close invalidates the server IDs from the old channel but preserves the logical specifications and callbacks. The controller marks active work as pending, and the next channel connection opens only the subscriptions that still have callbacks.
The runtime uses a connection generation to separate work on an old channel from work on a new channel. A late open or close result from the old generation cannot replace current state. A normal close follows a separate path because a new listener may arrive while shutdown is in progress.
This diagram shows how client intent survives a transport loss while server identifiers do not.
sequenceDiagram
participant App as Application
participant Controller as Subscription controller
participant Old as Old WebSocket
participant New as New WebSocket
App->>Controller: Keep listener registered
Old--xController: Unexpected close
Controller->>Controller: Keep spec and callback; clear server state
Controller->>New: Reconnect and resubscribe
New-->>Controller: New server subscription ID
New-->>Controller: Notifications resume
Controller->>App: Invoke callback
References: packages/…/controller.ts• L162-179 packages/…/controller.ts• L261-370 packages/…/runtime.ts• L748-761
Listener APIs
The listener APIs expose live views of account data, program-owned accounts, transaction signatures, cluster slots, and transaction logs. Each registration returns a client subscription ID, and the matching removal method accepts that ID.
Account listeners
onAccountChange watches one account and reports its current account value with the RPC response context. The request applies the listener commitment, then the connection commitment, and then the subscription default when no commitment is supplied. The listener can select binary, parsed, or compressed account data forms supported by the RPC service.
removeAccountChangeListener removes only the callback identified by the returned client subscription ID. Equivalent account requests can share one server stream.
References: packages/…/connection.ts• L6634-6693 packages/…/subscription-specs.ts• L54-79
Program account listeners
onProgramAccountChange watches accounts owned by one program. Its callback identifies the changed account and includes the account value with its RPC context. The request can include data encoding and filters, and an account must pass all filters before the RPC node sends the event.
removeProgramAccountChangeListener removes the selected callback while preserving other callbacks that use the same normalized program subscription.
References: packages/…/connection.ts• L6695-6757 packages/…/subscription-specs.ts• L81-108
Signature listeners
onSignature reports when a transaction signature reaches the requested commitment. onSignatureWithOptions can also report receipt before processing when enableReceivedNotification is enabled. The status event is terminal, so the client removes its local listener state after delivery and does not send a second server unsubscribe.
References: packages/…/connection.ts• L6857-6961 packages/…/subscription-specs.ts• L110-128
Slot listeners
onSlotChange reports the current slot with its parent and root. onSlotUpdate reports finer progress through block production and validation. onRootChange reports only the new root slot. These listeners have no request arguments beyond the callback.
References: packages/…/connection.ts• L6788-6841 packages/…/connection.ts• L6963-6988 packages/…/runtime.ts• L605-639
Log listeners
onLogs reports the signature, emitted log lines, transaction error, and response context for matching transactions. A public key filter becomes a mentions filter for the RPC service. The listener can also use the all or allWithVotes filters.
removeOnLogsListener removes the callback associated with the returned client subscription ID.
References: packages/…/connection.ts• L6760-6786 packages/…/subscription-specs.ts• L130-143
Change checklist
When these files or sections are changed, remember to consider these:
- Keep the derived WebSocket URL and channel settings aligned with RPC deployment and reverse-proxy port rules.
- Keep each public listener's normalized subscription kind, arguments, wire method, notification shape, and removal method aligned.
- Preserve the distinction between client subscription IDs, logical subscription hashes, and server subscription IDs.
- Keep commitment, encoding, and filter defaults stable so equivalent caller inputs still share one logical stream.
- Update reconnect handling when subscription states or connection-generation checks change. Old server IDs must not receive events after a channel close.
- Keep
awaitSubscriptionReadystate observation aligned with registration, setup failure, removal, and reconnect transitions. - Keep terminal signature handling aligned with both signature listener forms. The final status must not trigger a second server removal.
Important failure modes
| Trigger | Consequence | Guard |
|---|---|---|
| The derived WebSocket endpoint does not match the RPC deployment. | The live-event channel cannot open. | Set wsEndpoint for a custom route or port. |
| Equivalent listener arguments are normalized differently. | The RPC node receives duplicate streams and callbacks split across logical subscriptions. | Apply the same commitment, encoding, and filter defaults before hashing the specification. |
| The channel closes while a subscription is opening. | A late result can attach an old server ID to the new channel. | Check the connection generation before applying setup results. |
| A callback throws during dispatch. | One callback fails, but other callbacks could be skipped. | Catch and log callback errors at the notification boundary. |
| A listener is removed while setup is in flight. | An unwanted server stream can remain active. | Recheck callback state before keeping or registering the opened stream. |
A subscription becomes inactive while awaitSubscriptionReady waits. | The caller waits for a state that cannot become ready. | Reject on failed or inactive and dispose the state observer. |
| A terminal signature event is followed by explicit server unsubscribe work. | The RPC node receives a redundant removal for an already disposed stream. | Mark terminal signature streams as auto-disposed before client cleanup. |
Key files
| File | Why to read it |
|---|---|
| packages/…/connection.ts | Defines WebSocket setup, public listener registration and removal, readiness waiting, and the account, program, signature, slot, root, and log APIs. |
| packages/…/controller.ts | Coordinates logical subscription state, server stream updates, notification mapping, removal, and reconnect recovery. |
| packages/…/runtime.ts | Owns the WebSocket channel, notification streams, channel generations, idle close, and transport failure handling. |
| packages/…/registry.ts | Stores callback ownership, logical subscription identity, client IDs, server IDs, and observed states. |
| packages/…/subscription-specs.ts | Defines how public listener arguments become normalized RPC subscription specifications. |
| packages/…/account-notifications.ts and block-notifications.ts | Define the main account and block notification conversions used before callback dispatch. |
| packages/…/makeWebsocketUrl.ts | Defines the default WebSocket endpoint derived from the HTTP endpoint. |