Logo
New RPC users get 35% off their first monthView the offer
RPC Assistant

Solana WebSocket API: How to Stream Real-Time Data from the Chain

Summary

The Solana WebSocket API lets you subscribe to real-time updates like account changes, transaction confirmations, and new slots without polling. This article explains the core subscription methods, how to connect to a WebSocket endpoint, and how to handle common failure modes in production.

Solana's WebSocket API is the backbone for real-time dApps, indexers, and trading bots. Unlike HTTP JSON-RPC, which requires polling for state changes, WebSocket subscriptions push updates the moment they happen. This article covers the essential subscription methods, how to connect to a WebSocket endpoint, and what to watch out for in production.

Quick Decision Guide: When to Use WebSocket vs HTTP

Before diving into code, decide whether you actually need WebSocket. If your app only fetches account balances on user action, HTTP polling is simpler and more reliable. If you need to react to state changes within seconds—like monitoring a wallet for incoming payments or tracking a DEX pool—WebSocket subscriptions save bandwidth and reduce latency.

Use WebSocket when:

  • You need real-time updates for account balances, token transfers, or program state.
  • You're building an order book, price ticker, or live dashboard.
  • You want to avoid polling rate limits and reduce load on your RPC provider.

Stick with HTTP when:

  • Your data needs are occasional and can tolerate a few seconds of delay.
  • You're doing one-off queries or batch reads.
  • You need archive data or historical state that WebSocket doesn't provide.

For most production apps, a hybrid approach works best: use HTTP for initial state and WebSocket for live updates. This keeps your connection count low and your data fresh.

Solana WebSocket Endpoint: What You Need to Connect

To use the Solana WebSocket API, you need a WebSocket endpoint URL. OnFinality provides a public WebSocket endpoint for Solana mainnet:

wss://solana.api.onfinality.io/public-ws

This endpoint supports the standard Solana JSON-RPC over WebSocket. For higher throughput and dedicated resources, you can provision a dedicated node through OnFinality, which gives you a private WebSocket URL with your own rate limits.

When connecting, keep these details in mind:

  • Transport: WebSocket (wss://) is required; plain ws:// is not supported on mainnet endpoints.
  • Authentication: Public endpoints may have rate limits; for production, use an API key or dedicated endpoint.
  • Network: Make sure you're connecting to the correct network (mainnet vs devnet). Devnet has a separate endpoint, such as the one listed on the Solana Devnet page.

Core Subscription Methods You Should Know

The Solana WebSocket API mirrors the HTTP JSON-RPC methods but adds subscription variants. Here are the most commonly used methods:

MethodDescriptionUse Case
accountSubscribeNotifies when an account's lamports or data changesMonitor wallet balances, token accounts
logsSubscribeStreams transaction logs matching a filterTrack program activity, debug transactions
programSubscribeAlerts when any account owned by a program changesWatch DEX pools, NFT mints
slotSubscribeSends a notification each time a new slot is confirmedTrack chain progress, sync indexers
signatureSubscribeNotifies when a transaction signature is confirmedConfirm user transactions in real-time
rootSubscribeSends a notification when a new root is setAdvanced consensus tracking

Each subscription returns a subscription ID that you use to cancel it later. You'll also need to handle the initial response and subsequent notifications.

Connecting to the Solana WebSocket API: A JavaScript Example

Here's a minimal example using the ws library in Node.js to subscribe to account updates:

const WebSocket = require('ws');

const ws = new WebSocket('wss://solana.api.onfinality.io/public-ws');

ws.on('open', function open() {
  // Subscribe to account changes for a specific public key
  const accountPubkey = 'YourBase58PublicKeyHere';
  ws.send(JSON.stringify({
    jsonrpc: '2.0',
    id: 1,
    method: 'accountSubscribe',
    params: [
      accountPubkey,
      {
        encoding: 'base64',
        commitment: 'confirmed'
      }
    ]
  }));
});

ws.on('message', function incoming(data) {
  const message = JSON.parse(data);
  if (message.method === 'accountNotification') {
    console.log('Account update:', message.params.result);
    // Handle the update, e.g., update your UI or database
  } else if (message.id === 1) {
    console.log('Subscription ID:', message.result);
    // Store the subscription ID to cancel later if needed
  }
});

ws.on('error', function error(err) {
  console.error('WebSocket error:', err);
});

Remember to replace YourBase58PublicKeyHere with a real account address. For production, you'll want to add reconnection logic and handle backpressure.

Understanding Notification Payloads

When a subscription fires, you receive a notification object with a method field like accountNotification, logsNotification, etc. The params.result contains the actual data. For accountNotification, the result includes the account's lamports, data, and owner. For logsNotification, you get logs and a signature.

Here's an example of an accountNotification payload:

{
  "jsonrpc": "2.0",
  "method": "accountNotification",
  "params": {
    "result": {
      "context": {
        "slot": 123456
      },
      "value": {
        "lamports": 1000000,
        "data": {
          "program": "",
          "parsed": null,
          "space": 0
        },
        "owner": "11111111111111111111111111111111",
        "executable": false,
        "rentEpoch": 0
      }
    },
    "subscription": 123
  }
}

Note that the data field may be base64-encoded if you requested that encoding. You'll need to decode it to read the account's state.

Handling Reconnections and Heartbeats

WebSocket connections can drop due to network issues, server restarts, or idle timeouts. In production, you must implement reconnection logic. Here's a simple pattern:

function connect() {
  const ws = new WebSocket('wss://solana.api.onfinality.io/public-ws');
  
  ws.on('open', () => {
    // Resubscribe to all active subscriptions
    activeSubscriptions.forEach(sub => ws.send(sub));
  });

  ws.on('close', () => {
    console.log('Connection closed, reconnecting in 5s...');
    setTimeout(connect, 5000);
  });

  ws.on('error', (err) => {
    console.error('Error:', err);
    ws.close();
  });

  // Send a ping every 30s to keep the connection alive
  setInterval(() => {
    if (ws.readyState === WebSocket.OPEN) {
      ws.ping();
    }
  }, 30000);
}

connect();

When reconnecting, you'll need to resubscribe to all your previous subscriptions because the server forgets them after a disconnect. Keep a list of your subscription requests and replay them on open.

Common Pitfalls and How to Avoid Them

  • Not handling backpressure: If your app can't process notifications fast enough, you'll fall behind. Use a queue or buffer to manage incoming messages.
  • Ignoring commitment levels: Subscriptions default to finalized? Actually, the default is finalized for some methods, but you often want confirmed for faster updates. Specify the commitment level explicitly to match your needs.
  • Subscribing to too many accounts: Each subscription consumes resources. Batch related accounts into a single program subscription if possible.
  • Forgetting to unsubscribe: When you no longer need updates, call accountUnsubscribe with the subscription ID to free resources.
  • Using HTTP endpoint for WebSocket: Make sure you're using the wss:// URL, not the https:// one.

Production Readiness Checklist

Before you deploy your WebSocket-based app, run through this checklist:

  • Use a dedicated WebSocket endpoint with sufficient rate limits for your workload.
  • Implement reconnection with exponential backoff.
  • Resubscribe to all active subscriptions after reconnection.
  • Monitor connection health with heartbeats or pings.
  • Set up alerting for connection drops and subscription failures.
  • Test with devnet first using the Solana Devnet endpoint.
  • Consider using a managed service like OnFinality to handle infrastructure scaling.

Choosing the Right Infrastructure for WebSocket Loads

WebSocket connections are long-lived and can be resource-intensive on the server side. If you're running your own Solana node, you'll need to manage the WebSocket server and ensure it can handle many concurrent connections. This is where a managed RPC provider can save time.

OnFinality offers both public and dedicated Solana endpoints. Public endpoints are great for development and light usage, but for production apps with high message throughput, a dedicated node gives you dedicated resources and more predictable performance. You can compare options on our RPC pricing page and see all supported networks on our networks page.

When evaluating providers, consider:

  • Connection limits: How many concurrent WebSocket connections are allowed?
  • Message throughput: Can the provider handle your subscription volume?
  • Uptime and failover: Does the provider offer redundant infrastructure?
  • Support: Is there a team to help with issues?

Key Takeaways

  • Solana's WebSocket API enables real-time subscriptions for accounts, logs, programs, slots, and signatures.
  • Use the wss:// endpoint, not https://, and specify the correct commitment level.
  • Implement reconnection logic and resubscribe after drops to maintain a reliable stream.
  • Choose a provider that can handle your WebSocket load; consider dedicated nodes for production.
  • Test on devnet before going live to avoid costly mistakes.

Frequently Asked Questions

What is the difference between Solana's HTTP and WebSocket API?

The HTTP API is request-response, so you poll for data. The WebSocket API pushes updates to you when changes occur, making it more efficient for real-time applications.

How do I get a Solana WebSocket endpoint?

You can use a public endpoint like wss://solana.api.onfinality.io/public-ws or provision a dedicated node for higher limits. For devnet, use the devnet-specific endpoint.

What commitment level should I use for WebSocket subscriptions?

It depends on your use case. confirmed is a good default for most apps because it balances speed and reliability. finalized is slower but ensures the data is irreversible. processed is fastest but may include unconfirmed data.

Can I subscribe to multiple accounts with one subscription?

No, accountSubscribe takes a single account. To monitor multiple accounts, you can either create multiple subscriptions or use programSubscribe if they are all owned by the same program.

How do I handle WebSocket disconnections?

Implement automatic reconnection with a backoff strategy, and resubscribe to all your active subscriptions after reconnecting. Keep a list of subscription requests to replay.

Does OnFinality support WebSocket for Solana?

Yes, OnFinality provides WebSocket endpoints for Solana mainnet and devnet. You can find the URLs on the respective network pages.

What are the rate limits for the public WebSocket endpoint?

Public endpoints have rate limits to ensure fair usage. For production, consider a dedicated node to get higher limits and better performance. Check our pricing page for details.

Can I use WebSocket for Solana devnet?

Yes, Solana devnet supports WebSocket subscriptions. Use the devnet endpoint from the Solana Devnet page.

What is the best way to monitor WebSocket health?

Send periodic pings and track the time between messages. Set up alerts for missed heartbeats or connection drops.

Are there any costs associated with using WebSocket subscriptions?

On public endpoints, there may be rate limits but no direct cost. Dedicated nodes have a fee based on your plan. See RPC pricing for more information.

How do I unsubscribe from a subscription?

Use the corresponding *Unsubscribe method, such as accountUnsubscribe, and pass the subscription ID you received when subscribing.

What is the maximum number of concurrent WebSocket connections?

This depends on your provider. Public endpoints may have lower limits; dedicated nodes can handle more. Contact your provider for specifics.

Can I use WebSocket for Solana with Python?

Yes, you can use libraries like websockets or solana-py to connect to WebSocket endpoints. The JSON-RPC format is the same.

What is the difference between slotSubscribe and rootSubscribe?

slotSubscribe notifies you when a new slot is confirmed, while rootSubscribe notifies when a new root is set (a slot that is finalized). Root updates are less frequent.

How do I get the subscription ID?

The server responds to your subscribe request with a JSON-RPC response containing the subscription ID in the result field.

What happens if I send a subscription request with an invalid account?

The server will return an error response. Make sure the account exists and is a valid base58 public key.

Can I subscribe to logs for a specific program?

Yes, use logsSubscribe with a filter that includes mentions for the program ID.

How do I handle large volumes of notifications?

Use a message queue to buffer notifications and process them asynchronously. Consider batching writes to your database.

Is WebSocket supported on all Solana RPC providers?

Most providers support WebSocket, but check their documentation. OnFinality supports WebSocket on both public and dedicated endpoints.

What is the best way to test WebSocket subscriptions?

Use a tool like wscat or write a simple Node.js script to subscribe to a known account and verify you receive updates.

Can I use WebSocket for Solana with ethers.js?

No, ethers.js is for EVM chains. For Solana, use @solana/web3.js which has built-in WebSocket support.

How do I set up a WebSocket connection with @solana/web3.js?

Use new Connection('wss://...') and then call methods like onAccountChange to subscribe.

What is the default commitment for WebSocket subscriptions?

The default is finalized for some methods, but you should always specify the commitment level explicitly to avoid surprises.

Are there any security considerations for WebSocket?

Use wss:// to encrypt data in transit. Avoid sending sensitive data over plain ws://.

How do I monitor the health of my WebSocket connection?

Send a ping every 30 seconds and listen for pong. If you don't receive a pong, consider the connection dead and reconnect.

Can I use WebSocket for Solana mainnet and devnet simultaneously?

Yes, you can open separate connections to each network's endpoint.

What is the best practice for managing multiple subscriptions?

Keep a map of subscription IDs to their purpose, and resubscribe on reconnect. Unsubscribe when no longer needed.

Does OnFinality provide WebSocket support for other networks?

Yes, OnFinality supports WebSocket for many networks. Check the networks page for details.

How do I get started with Solana WebSocket quickly?

Use the public endpoint and a simple script to subscribe to a test account. Then expand to your use case.

What are the common errors when using WebSocket?

Common errors include invalid JSON, unsupported method, or rate limiting. Check the error message and adjust accordingly.

Can I use WebSocket for Solana with a mobile app?

Yes, but be mindful of battery and network usage. Consider using a library that supports background connections.

How do I ensure my WebSocket connection is secure?

Always use wss:// and validate the server certificate. Avoid sending private keys over WebSocket.

What is the difference between accountSubscribe and programSubscribe?

accountSubscribe monitors a single account, while programSubscribe monitors all accounts owned by a program. Use programSubscribe for broader monitoring.

Can I filter logs by program ID?

Yes, use the mentions filter in logsSubscribe to only receive logs that mention a specific program.

How do I cancel a subscription?

Send the corresponding *Unsubscribe method with the subscription ID. For example, accountUnsubscribe with the ID.

What is the maximum message size for WebSocket?

Solana's WebSocket messages can be large, especially for account data. Ensure your client can handle large payloads.

How do I handle rate limiting on WebSocket?

If you hit rate limits, reduce the number of subscriptions or upgrade to a dedicated node with higher limits.

Can I use WebSocket for Solana with a serverless function?

Serverless functions are not ideal for long-lived WebSocket connections. Use a persistent server or a managed service.

What is the best way to learn Solana WebSocket?

Start with the official Solana documentation and experiment with the public endpoint. Then read provider-specific guides.

Does OnFinality offer WebSocket for Solana devnet?

Yes, you can find the devnet WebSocket endpoint on the Solana Devnet page.

How do I get support for WebSocket issues?

Contact your RPC provider's support team. OnFinality offers support for its services.

What is the future of Solana WebSocket?

Solana continues to improve its APIs. Stay updated with official announcements.

Can I use WebSocket for Solana with a Go application?

Yes, use libraries like gorilla/websocket to connect to the WebSocket endpoint.

How do I test WebSocket subscriptions without a real account?

You can subscribe to a known account like the system program or use a test account on devnet.

What is the best way to handle errors in WebSocket?

Log errors and implement retry logic. For persistent errors, alert your team.

Are there any costs for WebSocket subscriptions on public endpoints?

Public endpoints are free but have rate limits. For production, consider a paid plan.

How do I choose between WebSocket and HTTP for my app?

Assess your latency requirements and data volume. Use WebSocket for real-time, HTTP for occasional queries.

What is the difference between confirmed and finalized?

confirmed means the transaction is accepted by the cluster, while finalized means it's irreversible. Use confirmed for faster updates.

Can I use WebSocket for Solana with a Rust application?

Yes, use libraries like tokio-tungstenite to connect.

How do I get the current slot number via WebSocket?

Subscribe to slotSubscribe and you'll receive slot updates.

What is the best way to monitor multiple accounts?

Use programSubscribe if they share a program, or create multiple accountSubscribe calls.

How do I handle WebSocket backpressure?

Use a queue to buffer messages and process them at a controlled rate.

Can I use WebSocket for Solana with a C# application?

Yes, use libraries like ClientWebSocket in .NET.

What is the best way to ensure high availability for WebSocket connections?

Use multiple connections and failover logic. Consider a provider with redundant infrastructure.

How do I get started with OnFinality's Solana WebSocket?

Visit the Solana network page to get the endpoint and documentation.

What are the limitations of WebSocket subscriptions?

Subscriptions are ephemeral and require reconnection handling. Also, they only provide current state, not historical data.

Can I use WebSocket for Solana with a mobile app?

Yes, but be mindful of battery and network usage. Consider using a library that supports background connections.

How do I ensure my WebSocket connection is secure?

Always use wss:// and validate the server certificate. Avoid sending private keys over WebSocket.

What is the difference between accountSubscribe and programSubscribe?

accountSubscribe monitors a single account, while programSubscribe monitors all accounts owned by a program. Use programSubscribe for broader monitoring.

Can I filter logs by program ID?

Yes, use the mentions filter in logsSubscribe to only receive logs that mention a specific program.

How do I cancel a subscription?

Send the corresponding *Unsubscribe method with the subscription ID. For example, accountUnsubscribe with the ID.

What is the maximum message size for WebSocket?

Solana's WebSocket messages can be large, especially for account data. Ensure your client can handle large payloads.

How do I handle rate limiting on WebSocket?

If you hit rate limits, reduce the number of subscriptions or upgrade to a dedicated node with higher limits.

Can I use WebSocket for Solana with a serverless function?

Serverless functions are not ideal for long-lived WebSocket connections. Use a persistent server or a managed service.

What is the best way to learn Solana WebSocket?

Start with the official Solana documentation and experiment with the public endpoint. Then read provider-specific guides.

Does OnFinality offer WebSocket for Solana devnet?

Yes, you can find the devnet WebSocket endpoint on the Solana Devnet page.

How do I get support for WebSocket issues?

Contact your RPC provider's support team. OnFinality offers support for its services.

What is the future of Solana WebSocket?

Solana continues to improve its APIs. Stay updated with official announcements.

Can I use WebSocket for Solana with a Go application?

Yes, use libraries like gorilla/websocket to connect to the WebSocket endpoint.

How do I test WebSocket subscriptions without a real account?

You can subscribe to a known account like the system program or use a test account on devnet.

What is the best way to handle errors in WebSocket?

Log errors and implement retry logic. For persistent errors, alert your team.

Are there any costs for WebSocket subscriptions on public endpoints?

Public endpoints are free but have rate limits. For production, consider a paid plan.

How do I choose between WebSocket and HTTP for my app?

Assess your latency requirements and data volume. Use WebSocket for real-time, HTTP for occasional queries.

What is the difference between confirmed and finalized?

confirmed means the transaction is accepted by the cluster, while finalized means it's irreversible. Use confirmed for faster updates.

Can I use WebSocket for Solana with a Rust application?

Yes, use libraries like tokio-tungstenite to connect.

How do I get the current slot number via WebSocket?

Subscribe to slotSubscribe and you'll receive slot updates.

What is the best way to monitor multiple accounts?

Use programSubscribe if they share a program, or create multiple accountSubscribe calls.

How do I handle WebSocket backpressure?

Use a queue to buffer messages and process them at a controlled rate.

Can I use WebSocket for Solana with a C# application?

Yes, use libraries like ClientWebSocket in .NET.

What is the best way to ensure high availability for WebSocket connections?

Use multiple connections and failover logic. Consider a provider with redundant infrastructure.

How do I get started with OnFinality's Solana WebSocket?

Visit the Solana network page to get the endpoint and documentation.

What are the limitations of WebSocket subscriptions?

Subscriptions are ephemeral and require reconnection handling. Also, they only provide current state, not historical data.

RPC Knowledge Base

Related RPC details

Never Worry about Infrastructure Again

OnFinality takes away the heavy lifting of DevOps so you can build smarter and faster.

Get Started