Solana WebSocket Unsubscribe Methods
Every subscribe method has a corresponding unsubscribe method that cancels the subscription. Call unsubscribe when you no longer need updates to free up resources.
Unsubscribe methods
| Subscribe | Unsubscribe |
|---|---|
accountSubscribe | accountUnsubscribe |
programSubscribe | programUnsubscribe |
logsSubscribe | logsUnsubscribe |
signatureSubscribe | signatureUnsubscribe |
slotSubscribe | slotUnsubscribe |
slotsUpdatesSubscribe | slotsUpdatesUnsubscribe |
rootSubscribe | rootUnsubscribe |
blockSubscribe | blockUnsubscribe |
voteSubscribe | voteUnsubscribe |
Request format
All unsubscribe methods take a single parameter: the subscription ID returned by the corresponding subscribe call.
{
"jsonrpc": "2.0",
"id": 1,
"method": "accountUnsubscribe",
"params": [42]
}
Response format
{
"jsonrpc": "2.0",
"id": 1,
"result": true
}
Returns true if the subscription was successfully cancelled, false if the subscription ID was not found.
Best practices
- Track subscription IDs. Store the subscription ID returned by each subscribe call so you can unsubscribe later.
- Unsubscribe before closing. Cancel all subscriptions before closing the WebSocket connection for a clean shutdown.
- Handle reconnection. After a reconnect (e.g., after a 1006 error), old subscription IDs are invalid. Re-subscribe to get new IDs.
const subscriptions = new Map<number, string>();
// Subscribe
const subId = await subscribe("accountSubscribe", [pubkey, config]);
subscriptions.set(subId, "accountSubscribe");
// Unsubscribe all before close
for (const [id, method] of subscriptions) {
const unsubMethod = method.replace("Subscribe", "Unsubscribe");
await send({ jsonrpc: "2.0", id: 1, method: unsubMethod, params: [id] });
}
subscriptions.clear();
FAQ
Do I need to unsubscribe before closing the WebSocket? It is good practice but not strictly required. The server cleans up subscriptions when the connection closes. However, explicit unsubscribe ensures resources are freed immediately.
What happens if I unsubscribe with an invalid ID?
The response returns false and no error is thrown. This is safe to call even if you are unsure whether the subscription is still active.
Does signatureSubscribe need to be unsubscribed?
No. signatureSubscribe automatically cancels itself after delivering the confirmation notification. You only need to unsubscribe if you want to cancel it before the transaction confirms.
Updated: