WebSocket Subscriptions
Connect to BlockVectra WebSocket endpoints for eth_subscribe newHeads and logs. Learn connection methods, filter rules, reconnection backoff, and recovery.
BlockVectra provides secure WebSocket connections (wss://) for streaming real-time Ethereum event subscriptions alongside standard JSON-RPC requests.
Choose WebSocket, Webhook or polling
Use WebSocket for live newHeads and filtered logs when your application can maintain a connection. Use the Blockchain Webhook API to receive watched-wallet activity at an HTTPS endpoint, with raw-body signature verification, retries and replay of retained matches. Use HTTP polling for scheduled ERC-20 payment monitoring and historical log backfill. The stablecoin guide also shows a USDT / USDC Webhook receiver. For an architectural comparison across chain support, receiver requirements, and recovery trade-offs for developers and AI agents, see the guide to choosing Webhooks, WebSocket or RPC polling.
WebSocket support comes from ws and subscriptions in GET /v1/chains; Push support comes from the authenticated GET /v1/push/chains list. A chain without WebSocket can still use address Webhooks if listed there.
WebSocket disconnections require re-subscription and backfill; they do not emit the Push control events subscription.gap or chain.reorg. For Webhooks, a gap needs a range scan; a reorg notice needs replaced events to be marked or discarded before keeping automatically redelivered canonical events. Push replay resends retained matches, not data from before an address or chain was added or while the subscription was offline. Review billing rules and the error reference when implementing recovery.
Available chains
You can check whether WebSocket subscriptions are active on a network by reading ws (boolean) and subscriptions (array of supported types) in GET /v1/chains.
The table below reflects networks where WebSocket support is enabled:
| Chain | WebSocket Endpoint (Path Key) |
|---|---|
| Arbitrum One | wss://api.blockvectra.com/v1/arb_mainnet/{api_key} |
| Arc | wss://api.blockvectra.com/v1/arc_mainnet/{api_key} |
| Avalanche C-Chain | wss://api.blockvectra.com/v1/avax_mainnet/{api_key} |
| Base | wss://api.blockvectra.com/v1/base_mainnet/{api_key} |
| Berachain | wss://api.blockvectra.com/v1/berachain_mainnet/{api_key} |
| Boba | wss://api.blockvectra.com/v1/boba_mainnet/{api_key} |
| BNB Smart Chain | wss://api.blockvectra.com/v1/bsc_mainnet/{api_key} |
| Celo | wss://api.blockvectra.com/v1/celo_mainnet/{api_key} |
| Ethereum | wss://api.blockvectra.com/v1/eth_mainnet/{api_key} |
| Ethereum Sepolia | wss://api.blockvectra.com/v1/eth_sepolia/{api_key} |
| Fraxtal | wss://api.blockvectra.com/v1/fraxtal_mainnet/{api_key} |
| Gnosis | wss://api.blockvectra.com/v1/gnosis_mainnet/{api_key} |
| HyperEVM | wss://api.blockvectra.com/v1/hyperevm_mainnet/{api_key} |
| Ink | wss://api.blockvectra.com/v1/ink_mainnet/{api_key} |
| Katana | wss://api.blockvectra.com/v1/katana_mainnet/{api_key} |
| Linea | wss://api.blockvectra.com/v1/linea_mainnet/{api_key} |
| Metal L2 | wss://api.blockvectra.com/v1/metall2_mainnet/{api_key} |
| Mode | wss://api.blockvectra.com/v1/mode_mainnet/{api_key} |
| OP Mainnet | wss://api.blockvectra.com/v1/op_mainnet/{api_key} |
| Polygon | wss://api.blockvectra.com/v1/polygon_mainnet/{api_key} |
| Robinhood Chain | wss://api.blockvectra.com/v1/robinhood_mainnet/{api_key} |
| Robinhood Chain Testnet | wss://api.blockvectra.com/v1/robinhood_testnet/{api_key} |
| Rootstock | wss://api.blockvectra.com/v1/rootstock_mainnet/{api_key} |
| Soneium | wss://api.blockvectra.com/v1/soneium_mainnet/{api_key} |
| Sonic | wss://api.blockvectra.com/v1/sonic_mainnet/{api_key} |
| Unichain | wss://api.blockvectra.com/v1/unichain_mainnet/{api_key} |
| World Chain | wss://api.blockvectra.com/v1/world_mainnet/{api_key} |
| X Layer | wss://api.blockvectra.com/v1/xlayer_mainnet/{api_key} |
| Zora | wss://api.blockvectra.com/v1/zora_mainnet/{api_key} |
Connection and authentication
Clients establish a secure TLS WebSocket connection (wss://). The API key can be supplied in two ways:
- Path key:
wss://api.blockvectra.com/v1/{chain}/{api_key} - Header key:
wss://api.blockvectra.com/v1/{chain}with thex-api-key: {api_key}orAuthorization: Bearer {api_key}header during the HTTP Upgrade handshake.
With a path key, the path key is used and both authentication headers are ignored. Without a path key, a non-empty x-api-key takes precedence over Authorization: Bearer. Browser WebSocket APIs cannot set these headers; use the path-key URL.
Handshake admission checks
The handshake can fail with:
- Authentication: An absent API key returns HTTP 401 (
missing_api_key); an unknown, disabled, or revoked API key returns HTTP 401 (invalid_api_key); if authentication is temporarily unavailable, the response is HTTP 503 (auth_unavailable). - Account balance: An account with zero or negative prepaid balance returns HTTP 402 (
balance_exhausted); if billing state cannot be confirmed, the response is HTTP 503 (billing_unavailable). - Connection limits: Exceeding the per-key limit (20 connections) or per-account limit (50 connections) returns HTTP 429 (
ws_connection_limit). - Chain availability: Requesting an unknown or unserved chain returns HTTP 404 (
unknown_chain). - Server capacity: When the server is busy or overloaded, the handshake returns HTTP 503 (
overloaded) with aRetry-Afterheader.
Once connected, clients can send standard JSON-RPC 2.0 requests (such as eth_blockNumber or eth_call) and subscription control methods formatted as UTF-8 text frames.
Billing rules
- Establishing a connection, keeping an idle connection open, and ping/pong heartbeats are not billed.
- Successful
eth_subscribeandeth_unsubscribecalls are billed, including an unsubscribe returningfalse; failed calls are not billed. Ordinary JSON-RPC calls follow the JSON-RPC billing rules. newHeadsnotifications count once per block hash per connection, regardless of how manynewHeadssubscriptions the connection has.logsnotifications count once per subscription per block hash and phase with matching logs; blocks without matches are not billed. Multiple matching logs in the same block and phase do not multiply the charge. Separate subscriptions count separately, even when their filters overlap. Reorganization logs (removed: true) form a separate unit; a replacement block at the same height has a different hash and is a different unit.- Notifications are billed only after they are successfully flushed to the socket send buffer; queued or dropped notifications that were not flushed are not billed. Notifications queued before an
eth_unsubscribeanswer count if flushed. WebSocket messages carry no HTTP billing headers; consult account usage for metered CU.
Subscription methods
The API implements the standard Ethereum pub/sub interface: eth_subscribe and eth_unsubscribe.
newHeads
Emits a new block header object whenever a new block is appended to the chain head.
- Subscribe request:
{"jsonrpc":"2.0","id":1,"method":"eth_subscribe","params":["newHeads"]} - Subscribe response: Returns an opaque hexadecimal subscription identifier:
{"jsonrpc":"2.0","id":1,"result":"0x1"} - Push notification frame:
{"jsonrpc":"2.0","method":"eth_subscription","params":{"subscription":"0x1","result":{"number":"0x1b4","hash":"0x..."}}}
logs
Emits log events matching specified filter criteria.
-
Filter requirement: Every
logssubscription filter must specify anaddress(a contract address or array of addresses) or atopic0(the first topic position, non-null). A filter specifying neither (such as{}or{"topics":[null,"0x..."]}) is rejected with error code-32602(logs_filter_required). -
Filter limits: At most 100 addresses; at most 4 topic positions with at most 16 candidate hashes per position.
-
Filter capacity: If active log filters reach capacity, the subscription returns error code
-32022(ws_filter_capacity). -
Chain reorganizations: If a block is removed due to a chain reorg, log notifications for removed logs carry
"removed": true. -
Subscribe request:
{"jsonrpc":"2.0","id":2,"method":"eth_subscribe","params":["logs",{"address":"0x1234567890123456789012345678901234567890"}]}
eth_unsubscribe
Terminates an active subscription using its subscription identifier.
- Unsubscribe request:
{"jsonrpc":"2.0","id":3,"method":"eth_unsubscribe","params":["0x1"]} - Unsubscribe response:
{"jsonrpc":"2.0","id":3,"result":true}
Runnable examples
Connect using viem v2 via createPublicClient and the webSocket transport. Replace {chain} with the target chain identifier and {api_key} with your API key:
import { createPublicClient, webSocket } from 'viem';
const apiKey = process.env.BLOCKVECTRA_API_KEY || '{api_key}';
const url = `wss://api.blockvectra.com/v1/robinhood_mainnet/${apiKey}`;
const client = createPublicClient({
transport: webSocket(url),
});
// 1. Subscribe to new block headers (newHeads)
const unwatchBlocks = client.watchBlocks({
onBlock: (block) => {
console.log('New block header received:', block.number, block.hash);
},
onError: (error) => {
console.error('watchBlocks error:', error);
},
});
// 2. Subscribe to contract event logs (filter requires address or topic0)
const unwatchEvents = client.watchEvent({
address: '0x1234567890123456789012345678901234567890',
onLogs: (logs) => {
console.log('Matching logs received:', logs);
},
onError: (error) => {
console.error('watchEvent error:', error);
},
});Close codes and client actions
When the server terminates a WebSocket session, it sends a Close frame with a specific close code and short reason. The table below lists the close codes emitted by the server and recommended actions:
| Close code | Reason string | Description | Retryable | Client action |
|---|---|---|---|---|
| 1001 | idle | Inactive connection without subscriptions or messages for 3600 seconds (1 hour) | Yes | Reconnect as needed. |
| 1003 | binary frames are not accepted | Binary WebSocket frame received; UTF-8 text frames only | No | Do not reconnect automatically. Update client to send text frames. |
| 1009 | message too large | Inbound payload exceeded 1 MiB | No | Do not reconnect automatically. Split large requests or reduce payload size. |
| 1012 | service restart | Server restarting, or session reached maximum lifetime (24 hours) | Yes | Reconnect using randomized jitter backoff, re-establish subscriptions, and backfill missed data. |
| 1013 | chain unavailable | Chain unavailable | Yes | Reconnect using full-jitter exponential backoff, re-establish subscriptions, and backfill missed data. |
| 1013 | overloaded | Server temporarily overloaded | Yes | Reconnect using full-jitter exponential backoff, re-establish subscriptions, and backfill missed data. |
| 4402 | insufficient balance | Account balance exhausted | No | Do not reconnect automatically. Top up your balance, then reconnect. |
| 4404 | invalid api key | API key is unknown, disabled, or revoked | No | Do not reconnect automatically. Verify or rotate API key in the console before reconnecting. |
| 4408 | slow consumer | The server closes a session whose push queue passes 512 KiB and drops pending notifications; clients may not receive a close frame (browser reports 1006) | Yes | Treat unexpected disconnects (no close frame received, browser reports 1006) like 4408: reconnect with backoff, re-establish subscriptions, and backfill dropped data with eth_getLogs; subscribe to less, or read faster. |
| 4429 | push rate exceeded | Notification rate exceeded 1,000 pushes/second | Yes | Reduce subscriptions or narrow filters; reconnect with backoff, re-subscribe, and backfill. |
| 4503 | billing unavailable | Billing temporarily unavailable | Yes | Transient state; reconnect using full-jitter exponential backoff. |
Control log-query frequency on fast chains
A newHeads notification need not trigger a separate eth_getLogs call. On fast chains, fetching logs for every pushed head can make more requests than polling that naturally groups several blocks. If your application can accept a short update interval, coalesce head notifications before starting the next scan:
- Keep one scan in flight per chain and a bounded pending-head record instead of queuing one scan per notification. A pending head is a hint to check the chain, not a committed checkpoint or proof of canonical history.
- At scan start, capture a fixed block number and hash as the upper bound. Read the entire uncommitted interval in chunks within the catalog's
max_logs_block_range; do not skip intermediate blocks when several notifications are combined. Commit results and the checkpoint together. On failure, keep the previous committed checkpoint and stop that pass. - Notifications received during the scan can schedule one later pass, subject to your chosen interval and resource limits. Recheck block hashes and apply the reorganization recovery rules; a higher head number alone does not resolve a conflicting hash.
The interval trades freshness for fewer scan opportunities; it does not guarantee lower total CU. Measure actual log queries, block reads and end-to-end lag, and account for WebSocket notifications separately under the billing rules. A filtered logs subscription can deliver matching events directly, but still needs the disconnect and reorganization recovery below.
Reconnection and exponential backoff
To prevent synchronized reconnection storms when connections drop, clients must implement exponential backoff with full jitter:
- Backoff formula: Before the n-th reconnection attempt (n = 0, 1, 2, ...), wait for a duration chosen uniformly at random:
delay = random(0, min(20s, 0.5s * 2^n)) - Reset counter: Reset retry counter n to 0 only after maintaining an uninterrupted, stable connection for at least
60 seconds. - Close code 1012: Introduce randomized initial delay before first reconnect attempt to avoid synchronized reconnection spikes.
- Non-retryable codes: Do not reconnect automatically on 4402, 4404, 1003, or 1009.
Backfilling missed data after reconnection
WebSocket subscriptions do not persist across connections; notifications emitted during a disconnection are not retained on the server. Following reconnection, clients should execute a catch-up strategy:
- Backfill logs with
eth_getLogs:- Persist
last_processed_blocktogether with its block hash as the durable checkpoint for contiguous committed work. Keep it separate from the highest live block notification seen; receiving one log does not prove the rest of that block has been processed. - On reconnect, re-subscribe with the same
address/topicsfilter first, then buffer live events while catching up. Keep the buffer bounded; on overflow or catch-up failure, stop advancing the checkpoint and resume from durable state instead of silently dropping events. - After subscribing, call
eth_getBlockByNumber("latest", false)once for this catch-up pass and capture its number and hash as a fixed upper bound (catchup_to_block). Do not wait for a log notification to choose the bound, and do not move thelatesttag between chunks. - Replay the checkpoint block inclusively with
fromBlock: last_processed_blockandtoBlock: catchup_to_block, keeping the same filter. Inclusive replay covers a disconnect in the middle of that block. Split the interval into chunks that respect the network'smax_logs_block_rangefromGET /v1/chains. - Deduplicate replayed and buffered live logs by
(blockHash, transactionHash, logIndex). Advance the checkpoint only after the entire contiguous replay interval succeeds and its effects and checkpoint are durably committed; on failure, keep the previous committed checkpoint. A live log alone never advances this recovery boundary. - Compare saved block hashes against the chain for reorgs. On a mismatch, roll back to a known common ancestor and replay; deduplication alone does not perform that rollback.
- Persist
- Backfill block headers with
eth_getBlockByNumber:- Record the latest block number and hash received before disconnect.
- Re-subscribe to
newHeads. - Query
eth_getBlockByNumber("latest", false)and fetch missing intermediate blocks sequentially. VerifyparentHashchain continuity to detect reorgs.
Limits
| Limit | Value | Result when exceeded |
|---|---|---|
| Subscriptions per WebSocket connection | 100 | -32022 subscription_limit |
newHeads subscriptions per WebSocket connection | 4 | -32022 subscription_limit |
logs subscription filter requirements | Must specify an address or a topic0 (first position in topics) | -32602 logs_filter_required |
Next steps
- Browse the datasets directory to see every dataset BlockVectra indexes.
- See the free plan and pricing to check what your account includes.
- Log in to the console to create an API key.
Last updated: