Introducing a new way to review your PRs.

Read the announcement

solana-foundation / solana-go

Go SDK library and RPC client for the Solana Blockchain

View on GitHub

26 documents · Updated Nov 16, 2026

docs / websocket-subscriptions

WebSocket subscriptions

The WebSocket client provides a long-lived JSON-RPC connection for receiving live Solana validator events. It turns account, block, log, program, signature, slot, root, vote, and slot-update streams into typed Go notifications that callers read until they cancel the stream or close the client. This page extends the RPC client overview; request transport details are in JSON-RPC transport, and transaction status use cases are in transaction submission.

Subscription lifecycle

The subscription lifecycle starts with a WebSocket connection and ends when the caller unsubscribes or the connection closes. Each subscription sends a JSON-RPC subscribe request, waits for the validator to assign a subscription ID, and routes later notifications with that ID to the matching typed stream.

sequenceDiagram
    participant App as Application
    participant Client as WebSocket client
    participant RPC as Validator RPC

    App->>Client: Connect(endpoint)
    Client->>RPC: WebSocket handshake
    App->>Client: Subscribe(filter, options)
    Client->>RPC: subscribe request
    RPC-->>Client: subscription ID
    App->>Client: WaitSubscribed(ctx)
    loop Notifications
        RPC-->>Client: notification with subscription ID
        Client-->>App: typed Recv result
    end
    App->>Client: Unsubscribe() or Close()
    Client->>RPC: unsubscribe request when possible

Connect starts the connection and its keep-alive handling. Close stops the connection and closes all active subscriptions. A subscription's WaitSubscribed waits for server confirmation before the caller reads state that could otherwise change between the initial read and registration. Recv accepts a context, so the caller can stop waiting without closing the client; Err exposes stream errors, and Unsubscribe ends that subscription. A closed connection or a closed subscription is reported as ErrSubscriptionClosed.

Each subscription has a bounded notification stream. The client does not block its single receive loop while delivering a notification, so a caller that does not consume results fast enough can cause that subscription to close. A failed subscribe request or a decode error also closes the affected stream and reports the cause through WaitSubscribed, Recv, or Err.

The client can serve many subscriptions at the same time. If the validator assigns the same server ID to identical subscriptions, each subscription receives its own decoded notification and the server is unsubscribed only after the last local subscription closes. Notification method and server ID together identify a stream, so equal IDs from different subscription types remain separate.

References: rpc/…/client.go• L36-77 rpc/…/client.go• L88-189 rpc/…/client.go• L234-386 rpc/…/client.go• L388-550 rpc/…/subscription.go• L28-210 rpc/…/fixes_test.go• L176-231 rpc/…/shared_id_test.go• L124-287 rpc/…/wait_subscribed_test.go• L47-175

Connection options

ConnectWithOptions adds connection settings for endpoints that need request headers or different handshake limits. The ShortID option uses smaller JSON-RPC request IDs for servers that do not accept larger numeric IDs; it changes request correlation only, not subscription behavior.

OptionPurpose
HttpHeaderSends headers during the WebSocket handshake.
HandshakeTimeoutReplaces the default handshake wait when a different limit is needed.
ShortIDRestricts generated request IDs for RPC servers with narrow ID support.

References: rpc/…/client.go• L88-124 rpc/…/types.go• L29-57 rpc/…/types.go• L92-98

Subscription APIs

The APIs group notifications by the Solana object or validator event that the application needs to follow. Account and program streams report state changes, block and log streams report execution activity, signature streams report transaction status, and slot, root, vote, and slot-update streams report validator progress.

APIMain inputNotification typeTypical use
AccountSubscribeAccount public key and optional commitment or account data settingsAccountResultFollow one account's balance or data.
BlockSubscribeAll blocks or blocks that mention an account or programBlockResultFollow confirmed or finalized blocks in the validator's supported block stream.
ParsedBlockSubscribeSame block filters with parsed transaction outputParsedBlockResultFollow blocks when parsed transaction data is needed.
LogsSubscribeAll transactions, all transactions with votes, or one mentioned accountLogResultFollow transaction execution logs.
ProgramSubscribeProgram public key and optional account filtersProgramResultFollow accounts owned by a program.
SignatureSubscribeTransaction signature and optional commitmentSignatureResultWait for a transaction status.
SlotSubscribeNoneSlotResultTrack processed slots and their parent or root relation.
RootSubscribeNoneRootResultTrack the validator's newest root.
SlotsUpdatesSubscribeNoneSlotsUpdatesResultObserve validator updates during slot processing.
VoteSubscribeNoneVoteResultObserve votes received through gossip before consensus.

Every returned subscription exposes the same high-level controls: WaitSubscribed(ctx) for registration confirmation, Recv(ctx) for the next typed notification, Err() for stream errors, and Unsubscribe() for cleanup. The concrete result type determines the event payload and is documented below.

References: rpc/…/accountSubscribe.go• L48-140 rpc/…/blockSubscribe.go• L90-183 rpc/…/parsedBlockSubscribe.go• L42-116 rpc/…/logsSubscribe.go• L50-130 rpc/…/programSubscribe.go• L52-150 rpc/…/signatureSubscribe.go• L123-194 rpc/…/slotSubscribe.go• L25-68 rpc/…/rootSubscribe.go• L21-65 rpc/…/slotsUpdatesSubscribe.go• L55-102 rpc/…/voteSubscribe.go• L32-82

Account and program notifications

Account notifications describe the current value of one account. AccountResult includes the slot used for the value and an *rpc.Account, which can be nil when the account has no value. AccountSubscribeWithConfig supports commitment, data encoding, and an optional data slice; the simpler methods preserve the same stream with fewer settings.

Program notifications use the same account-state idea at program scope. ProgramResult carries a keyed account, so each event identifies the account and its data. Program configuration can add commitment, encoding, data slicing, and filters; the filters narrow the stream to matching account data.

References: rpc/…/accountSubscribe.go• L24-46 rpc/…/accountSubscribe.go• L76-140 rpc/…/programSubscribe.go• L24-50 rpc/…/programSubscribe.go• L83-150

Block notifications

Block notifications report a block that reaches the validator's selected commitment level. BlockResult carries the notification context slot and a value with the block slot, any block error, and an optional rpc.GetBlockResult. ParsedBlockResult has the same event shape but uses rpc.GetParsedBlockResult for parsed transaction data.

Both block APIs accept either an all-block filter or a filter for blocks that mention an account or program. Options control commitment, transaction detail, rewards, and the maximum supported transaction version. BlockSubscribe accepts binary transaction encodings; callers that need JSON-parsed transactions must use ParsedBlockSubscribe, which always requests parsed encoding.

These APIs are unstable and disabled unless the validator enables block subscription support. Their response format can change with the validator feature.

References: rpc/…/blockSubscribe.go• L25-89 rpc/…/blockSubscribe.go• L90-183 rpc/…/parsedBlockSubscribe.go• L24-91 rpc/…/parsedBlockSubscribe.go• L94-116

Log notifications

Log notifications connect a transaction signature with the logs produced while its instructions run. LogResult includes the context slot, the signature, a transaction error value, and the log message list; a nil error value represents a successful transaction.

LogsSubscribe selects all transactions or all transactions with vote transactions included. LogsSubscribeMentions instead selects transactions that mention one public key. Both forms can apply a commitment level.

References: rpc/…/logsSubscribe.go• L24-48 rpc/…/logsSubscribe.go• L50-130

Signature notifications

Signature notifications report the status of one transaction signature. SignatureResult includes the slot for the status and an error value that indicates whether the transaction failed. The normal stream ends after the validator sends the signature status notification, so this API is suited to waiting for one transaction rather than tracking a repeating event.

SignatureSubscribeWithOpts can request an extra early notification with EnableReceivedNotification. When enabled, the first event can set ReceivedSignature to true while its status value remains at the zero value; a later event carries the transaction status. This lets an application distinguish “the validator saw the signature” from “the transaction reached the requested commitment.”

References: rpc/…/signatureSubscribe.go• L28-106 rpc/…/signatureSubscribe.go• L108-194

Slot, root, vote, and slot update notifications

These streams describe validator progress at different stages. A slot event reports the processed slot with its parent and root. A root event reports the newest root as a single slot number. A vote event reports the vote hash, the slots covered by the vote, and an optional timestamp.

SlotsUpdatesSubscribe reports finer-grained updates for each slot. Its result identifies the parent and slot, the update type, an optional timestamp, and optional bank statistics when the validator freezes a bank. Update types include shred receipt, completion, bank creation, freeze, dead slot, optimistic confirmation, and root.

Slot and root subscriptions are useful for tracking chain progress without watching account or transaction state. Vote notifications come from gossip before consensus, so an observed vote is not guaranteed to enter the ledger. Slot-update notifications are unstable and may not be supported by every validator.

Vote subscription is unstable and disabled unless the validator enables vote subscription support. Its response format can change with the validator feature.

References: rpc/…/slotSubscribe.go• L19-68 rpc/…/rootSubscribe.go• L19-65 rpc/…/slotsUpdatesSubscribe.go• L23-102 rpc/…/voteSubscribe.go• L23-82

Notification consumption

The typed subscription wrappers keep application code focused on event handling. A caller creates the stream, waits for registration, reads one result at a time with a context, and releases the stream when it no longer needs updates.

client, err := ws.Connect(ctx, rpc.TestNet_WS)
if err != nil {
    return err
}
defer client.Close()

sub, err := client.SlotSubscribe()
if err != nil {
    return err
}
defer sub.Unsubscribe()

if err := sub.WaitSubscribed(ctx); err != nil {
    return err
}

for {
    notification, err := sub.Recv(ctx)
    if err != nil {
        return err
    }
    use(notification)
}

The same lifecycle applies to every typed wrapper. Recv returns queued notifications before the close error. After closure, each later receive returns an error that matches ErrSubscriptionClosed and preserves the underlying server, decode, or buffer error when one caused the close. Applications should treat a receive error as a stream outcome, not as a notification value.

References: rpc/…/subscription.go• L102-174 rpc/…/accountSubscribe.go• L122-140 rpc/…/slotSubscribe.go• L50-68 rpc/…/wait_subscribed_test.go• L177-215 rpc/…/shared_id_test.go• L289-339

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep each subscribe method's wire method, unsubscribe method, notification decoder, and typed result aligned. A mismatch can leave a stream registered under the wrong validator event.
  • Keep notification result shapes aligned with the validator's JSON-RPC response. This is especially important for parsed versus non-parsed block data, the two signature notification shapes, and slot-update variants.
  • When adding an option to an account, program, block, or signature subscription, check that the option is forwarded without changing the default behavior of the simpler API.
  • Treat changes to unstable block, slot-update, or vote support as validator compatibility changes. Update availability statements and expected notification types together.
  • Preserve the subscription ID correlation path when changing request IDs or response parsing. Notifications depend on the validator-assigned ID after the initial request reply.
  • Preserve shared-ID fanout and late-confirmation cleanup. Closing one local subscription must not stop another subscription that uses the same server ID.
  • Keep WaitSubscribed and close-error behavior aligned. A failed confirmation must wake waiters and make later Recv calls report an error that matches ErrSubscriptionClosed.

Important failure modes

TriggerConsequenceGuard
The WebSocket endpoint cannot complete its handshakeConnect returns an error and no client is created.Use a reachable RPC WebSocket endpoint and set HandshakeTimeout when the default limit is not suitable.
The validator returns an error for a subscribe requestWaitSubscribed and Recv report a closed stream with the RPC error instead of waiting forever.Check the error from the subscribe call and from WaitSubscribed or Recv.
The application consumes notifications too slowlyThe client closes that subscription when its bounded stream cannot accept another result.Read each stream continuously or move event work out of the receive loop.
The connection closes or stops answering keep-alive messagesAll active subscriptions close and Recv returns ErrSubscriptionClosed or a stream error.Treat closure as a reconnect or shutdown signal.
EncodingJSONParsed is sent through BlockSubscribeThe client rejects the request because its result type is for non-parsed blocks.Use ParsedBlockSubscribe for parsed block data.
A block, slot-update, or vote subscription is used on a validator without the required feature supportThe validator may reject the subscribe request because the unstable API is disabled.Confirm validator support before creating the stream.
A subscription is closed before its confirmation arrivesA late confirmation is cleaned up on the server; a shared live ID is preserved when another local subscription still uses it.Prefer WaitSubscribed when registration matters and always release unused subscriptions.

Key files

FileWhy to read it
rpc/…/client.goShows connection setup, keep-alive behavior, notification routing, shared-ID handling, and connection-wide shutdown.
rpc/…/subscription.goDefines the shared wait, receive, error, and unsubscribe contract.
rpc/…/accountSubscribe.goShows account state notifications and account-specific configuration.
rpc/…/programSubscribe.goShows program-owned account notifications and account filters.
rpc/…/blockSubscribe.goShows block filters, block options, and non-parsed block results.
rpc/…/parsedBlockSubscribe.goShows the parsed block variant and its fixed parsed encoding.
rpc/…/logsSubscribe.goShows transaction log filters and log result data.
rpc/…/signatureSubscribe.goShows transaction status notifications and the optional received marker.
rpc/…/slotSubscribe.goDefines processed-slot notifications.
rpc/…/rootSubscribe.goDefines root notifications.
rpc/…/slotsUpdatesSubscribe.goDefines detailed slot lifecycle notifications and optional bank statistics.
rpc/…/voteSubscribe.goDefines pre-consensus vote notifications and their unstable availability.
rpc/…/types.goDefines request IDs, connection options, and the validator subscription ID shape.