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:

ChainWebSocket Endpoint (Path Key)
Arbitrum Onewss://api.blockvectra.com/v1/arb_mainnet/{api_key}
Arcwss://api.blockvectra.com/v1/arc_mainnet/{api_key}
Avalanche C-Chainwss://api.blockvectra.com/v1/avax_mainnet/{api_key}
Basewss://api.blockvectra.com/v1/base_mainnet/{api_key}
Berachainwss://api.blockvectra.com/v1/berachain_mainnet/{api_key}
Bobawss://api.blockvectra.com/v1/boba_mainnet/{api_key}
BNB Smart Chainwss://api.blockvectra.com/v1/bsc_mainnet/{api_key}
Celowss://api.blockvectra.com/v1/celo_mainnet/{api_key}
Ethereumwss://api.blockvectra.com/v1/eth_mainnet/{api_key}
Ethereum Sepoliawss://api.blockvectra.com/v1/eth_sepolia/{api_key}
Fraxtalwss://api.blockvectra.com/v1/fraxtal_mainnet/{api_key}
Gnosiswss://api.blockvectra.com/v1/gnosis_mainnet/{api_key}
HyperEVMwss://api.blockvectra.com/v1/hyperevm_mainnet/{api_key}
Inkwss://api.blockvectra.com/v1/ink_mainnet/{api_key}
Katanawss://api.blockvectra.com/v1/katana_mainnet/{api_key}
Lineawss://api.blockvectra.com/v1/linea_mainnet/{api_key}
Metal L2wss://api.blockvectra.com/v1/metall2_mainnet/{api_key}
Modewss://api.blockvectra.com/v1/mode_mainnet/{api_key}
OP Mainnetwss://api.blockvectra.com/v1/op_mainnet/{api_key}
Polygonwss://api.blockvectra.com/v1/polygon_mainnet/{api_key}
Robinhood Chainwss://api.blockvectra.com/v1/robinhood_mainnet/{api_key}
Robinhood Chain Testnetwss://api.blockvectra.com/v1/robinhood_testnet/{api_key}
Rootstockwss://api.blockvectra.com/v1/rootstock_mainnet/{api_key}
Soneiumwss://api.blockvectra.com/v1/soneium_mainnet/{api_key}
Sonicwss://api.blockvectra.com/v1/sonic_mainnet/{api_key}
Unichainwss://api.blockvectra.com/v1/unichain_mainnet/{api_key}
World Chainwss://api.blockvectra.com/v1/world_mainnet/{api_key}
X Layerwss://api.blockvectra.com/v1/xlayer_mainnet/{api_key}
Zorawss://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 the x-api-key: {api_key} or Authorization: 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 a Retry-After header.

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_subscribe and eth_unsubscribe calls are billed, including an unsubscribe returning false; failed calls are not billed. Ordinary JSON-RPC calls follow the JSON-RPC billing rules.
  • newHeads notifications count once per block hash per connection, regardless of how many newHeads subscriptions the connection has.
  • logs notifications 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_unsubscribe answer 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 logs subscription filter must specify an address (a contract address or array of addresses) or a topic0 (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 codeReason stringDescriptionRetryableClient action
1001idleInactive connection without subscriptions or messages for 3600 seconds (1 hour)YesReconnect as needed.
1003binary frames are not acceptedBinary WebSocket frame received; UTF-8 text frames onlyNoDo not reconnect automatically. Update client to send text frames.
1009message too largeInbound payload exceeded 1 MiBNoDo not reconnect automatically. Split large requests or reduce payload size.
1012service restartServer restarting, or session reached maximum lifetime (24 hours)YesReconnect using randomized jitter backoff, re-establish subscriptions, and backfill missed data.
1013chain unavailableChain unavailableYesReconnect using full-jitter exponential backoff, re-establish subscriptions, and backfill missed data.
1013overloadedServer temporarily overloadedYesReconnect using full-jitter exponential backoff, re-establish subscriptions, and backfill missed data.
4402insufficient balanceAccount balance exhaustedNoDo not reconnect automatically. Top up your balance, then reconnect.
4404invalid api keyAPI key is unknown, disabled, or revokedNoDo not reconnect automatically. Verify or rotate API key in the console before reconnecting.
4408slow consumerThe server closes a session whose push queue passes 512 KiB and drops pending notifications; clients may not receive a close frame (browser reports 1006)YesTreat 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.
4429push rate exceededNotification rate exceeded 1,000 pushes/secondYesReduce subscriptions or narrow filters; reconnect with backoff, re-subscribe, and backfill.
4503billing unavailableBilling temporarily unavailableYesTransient 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:

  1. Backfill logs with eth_getLogs:
    • Persist last_processed_block together 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/topics filter 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 the latest tag between chunks.
    • Replay the checkpoint block inclusively with fromBlock: last_processed_block and toBlock: 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's max_logs_block_range from GET /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.
  2. 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. Verify parentHash chain continuity to detect reorgs.

Limits

LimitValueResult when exceeded
Subscriptions per WebSocket connection100-32022 subscription_limit
newHeads subscriptions per WebSocket connection4-32022 subscription_limit
logs subscription filter requirementsMust specify an address or a topic0 (first position in topics)-32602 logs_filter_required

Next steps

Last updated:

On this page