Operation
WebSocket

WebSocket

eRPC supports WebSocket connections on the same HTTP port. Clients can connect via ws:// or wss:// for persistent JSON-RPC connections and real-time subscriptions (eth_subscribe). The server side is off by default: set server.webSocket.enabled: true to accept connections.

Connecting

Connect to eRPC using the same URL path as HTTP, but with the ws:// or wss:// scheme:

ws://<your-erpc-hostname>/<project-id>/<network-architecture>/<chain-id>
// Browser / Node.js example
const ws = new WebSocket("ws://localhost:4000/main/evm/1");
 
ws.onopen = () => {
  ws.send(JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "eth_blockNumber",
    params: []
  }));
};
 
ws.onmessage = (event) => {
  console.log(JSON.parse(event.data));
  // { "jsonrpc": "2.0", "id": 1, "result": "0x1234567" }
};

WebSocket connections use the same port as HTTP once server.webSocket.enabled is true. With it off, an upgrade request is answered as ordinary HTTP. Domain aliasing rules also apply to WebSocket connections.

Regular JSON-RPC over WebSocket

All JSON-RPC methods supported over HTTP also work over WebSocket. The connection is persistent, so you can send multiple requests without reconnecting:

// Send multiple requests on the same connection
ws.send(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [] }));
ws.send(JSON.stringify({ jsonrpc: "2.0", id: 2, method: "eth_chainId", params: [] }));
ws.send(JSON.stringify({ jsonrpc: "2.0", id: 3, method: "eth_getBlockByNumber", params: ["latest", false] }));

Batch requests (JSON arrays) are also supported:

ws.send(JSON.stringify([
  { jsonrpc: "2.0", id: 1, method: "eth_blockNumber", params: [] },
  { jsonrpc: "2.0", id: 2, method: "eth_chainId", params: [] }
]));
// Response is a JSON array

All eRPC features work identically for WebSocket RPC requests: authentication, method filters, caching, upstream scoring, failsafe policies (retry, hedge, circuit breaker), rate limiting, multiplexing (request deduplication), EVM integrity checks, and metrics. Each request is bounded by server.maxTimeout, and a connection processes at most server.webSocket.maxConcurrentRequestsPerConnection messages at once — further messages wait until one finishes. A batch is one message; its requests run concurrently, as over HTTP. Credentials (secret query parameter or headers, JWT, SIWE, client IP) come from the upgrade request: an upgrade that no auth strategy accepts is refused with 401, and each request on the connection is still authenticated, with method scoping and rate limits, as over HTTP.

Subscriptions

eRPC supports eth_subscribe and eth_unsubscribe for real-time event streaming. Subscriptions require at least one upstream configured with a ws:// or wss:// endpoint.

eth_subscribe

const ws = new WebSocket("ws://localhost:4000/main/evm/1");
 
ws.onopen = () => {
  // Subscribe to new block headers
  ws.send(JSON.stringify({
    jsonrpc: "2.0",
    id: 1,
    method: "eth_subscribe",
    params: ["newHeads"]
  }));
};
 
ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  
  if (msg.id) {
    // Subscription confirmation
    console.log("Subscription ID:", msg.result);
    // "0x2a151383161618ebffddfed9de4be5db"
  }
  
  if (msg.method === "eth_subscription") {
    // New block notification
    console.log("New block:", msg.params.result.number);
  }
};

Supported subscription types (depends on upstream node capabilities):

  • newHeads — new block headers
  • logs — log entries matching a filter
  • newPendingTransactions — pending transaction hashes

Subscribing to logs with a filter

The second params entry is a filter object with optional address (string or array) and topics (array of topic hex strings or arrays for OR-matching). The filter is hashed by eRPC so multiple clients requesting the same filter share a single underlying upstream subscription.

ws.send(JSON.stringify({
  jsonrpc: "2.0",
  id: 1,
  method: "eth_subscribe",
  params: [
    "logs",
    {
      address: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC
      topics: [
        "0xddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef" // Transfer
      ]
    }
  ]
}));

eth_unsubscribe

ws.send(JSON.stringify({
  jsonrpc: "2.0",
  id: 2,
  method: "eth_unsubscribe",
  params: ["0x2a151383161618ebffddfed9de4be5db"]
}));
// Response: { "jsonrpc": "2.0", "id": 2, "result": true }

Subscription features

  • One chain for every client — all subscriptions of a network read one chain feed, kept by the network's chain tracker (see How heads reach subscribers). A client gets a block only once enough upstreams confirm it, and never a block above the network's eth_blockNumber.
  • Pending transactions from push sources — newPendingTransactions is subscribed on every admitted WebSocket upstream while a client wants it. With failover.onDefaultsExhausted on, tier:fallback upstreams feed it only while no primary source has streamed heads for 60s. A topic silent for 60s while blocks carry transactions is subscribed again, backing off up to 30 min.
  • No surprise disconnects — upstream reconnects, scoring changes and brief outages never close your connection; eRPC re-subscribes upstream behind the scenes. eRPC closes a connection only on shutdown (1001), when the client stops answering pings, or with 1013 when a logs subscription cannot continue (see below).
  • Deduplication — each block, log and pending transaction reaches a subscription once, however many upstreams report it.
  • Shared work — every subscription reads the same feed: one receipts fetch, parse and encoding per block, shared by every client.
  • Slow-client safety — a slow reader never blocks other clients or the chain tracker. A logs subscription whose next block has waited more than chainTracker.reorgWindow × the block time closes the connection with 1013, so the client knows it may have missed logs and can re-subscribe and backfill with eth_getLogs; a newHeads subscription restarts after the confirmed head, which the client sees as a jump in numbers.
  • Connection-scoped IDs — eRPC issues its own subscription IDs, so they stay the same across upstream reconnects and upstream switches. They belong to the connection that created them: eth_unsubscribe only works on that connection, and subscriptions end when it closes.
  • Rate limiting — subscribe/unsubscribe calls count against the same project and network rate limits as regular RPC.

logs subscriptions

eRPC builds logs notifications from each block's eth_getBlockReceipts, fetched once per block when the block's logsBloom may match a subscribed filter; no upstream logs subscription is made. The filter takes address and topics as geth does; fromBlock and toBlock are ignored. A filter that does not parse fails with -32602.

When a reorg drops a block with matched logs, eRPC sends those logs again with "removed": true, newest first, then the logs of the new branch. A reorg that reverts more than chainTracker.reorgWindow of the blocks a subscription was sent, or a block whose receipts no upstream serves for 60s, closes the connections of its logs subscriptions with 1013, spread over 60s.

ws.onmessage = (event) => {
  const msg = JSON.parse(event.data);
  if (msg.method === "eth_subscription" && msg.params.result.removed) {
    // This log was in a block that was reorged out.
    // Roll back any state you derived from it.
  }
};

When eth_subscribe fails

eth_subscribe returns a JSON-RPC error when:

  • the network has no subscription source for the type; for logs, no upstream serves eth_getBlockReceipts (or eth_getLogs with integrity off), or every such fetch has failed for 60s;
  • the subscription type is not supported, or a logs filter does not parse (-32602);
  • the connection already has server.webSocket.maxSubscriptionsPerConnection active subscriptions (-32005);
  • the instance already has server.webSocket.maxSubscriptions active subscriptions (-32005);
  • the request is rate limited.

A failed eth_subscribe leaves your WebSocket connection open. You can retry on the same connection.

How heads reach subscribers

wss newHeads / http poll → intake → chain tracker → confirmed head → taps → ws / gRPC

Sources. An upstream with evm.subscriptionSource: onDemand (the default for ws:// / wss:// endpoints) subscribes newHeads while a client needs every block: a newHeads or logs subscription, or a gRPC block stream. It unsubscribes 60s after the last one ends. With no such client it opens no upstream subscription, so a provider that bills subscription traffic bills none. always subscribes from network init, whether or not a WebSocket or gRPC server runs. A pushed head meets the upstream's own latest poll, so a push-fed upstream is not polled for latest as well. Other upstreams feed heads by polling eth_getBlockByNumber("latest") on the state poller's cadence, while a client subscribes or the integrity follow tap runs. A source that refuses newHeads as unsupported is polled instead and asked again on each reconnect and every 10 min.

Voters. An upstream votes while the selection policy routes to it, it is not syncing and its head is not benched. Each header passes intake first: parsing, header integrity when integrity is on, and the chain-identity check. A header that fails is dropped and counted in erpc_chain_tracker_source_heads_total.

Confirmed head. The tracker holds headers by hash and follows the branch most voters are on. It links every header to its parent, fetching missing blocks by number and by hash. The confirmed head is the highest block that servedTip.quorum of the current hash voters have reached, at or below the network's eth_blockNumber. Every transport delivers only up to it. With one push source and one polled upstream a head waits one poll round trip; with two push sources, none.

Reorgs. When the voters move to another branch, every subscription replays it:

TransportOn a reorg
ws newHeadseach head of the new branch, oldest first
ws logsthe sent logs of the dropped blocks with "removed": true, newest first; then the logs of the new branch
gRPC StreamBlocksresends from the fork point + 1: a number at or below the last one replaces it and every number above

Logs from receipts. logs notifications come from each block's eth_getBlockReceipts, fetched once when the block is pinned and its logsBloom may match a subscribed filter. Receipts that fail on every upstream for 5s fall back to eth_getLogs by blockHash. Logs reach clients one receipts round trip after the confirmed head.

The window. The tracker holds headers within chainTracker.maxBackfill of chain time below the head, and at least chainTracker.reorgWindow blocks; receipts for the last reorgWindow blocks. A reorg deeper than reorgWindow re-anchors the tracker on the majority's branch.

Wait bounds and signals per transport.

TransportSlow or stalledOut of range
ws newHeadsnext block waited more than reorgWindow × block time: restart after the confirmed headrestart after the confirmed head
ws logsnext block waited more than reorgWindow × block time, a reorg that reverts more than reorgWindow sent blocks, or 60s on one block's receipts: close 1013close 1013; closes from one event spread over 60s
ws newPendingTransactionsskips to the newest—
gRPC StreamBlocks60s of stalled read, or one Send over 10s: UNAVAILABLEOUT_OF_RANGE

Every out-of-range or lagging end counts in erpc_tap_end_total{reason,detail}.

Failure model.

FailureRecoveryBound
wss socket dropsreconnect with jittered 1–30s backoff; other voters carry; the tracker links the missed blocks30s
wss socket alive, newHeads silentits vote ages out; the socket reconnects30s past the last push
upstream lagsbenched after max(30s, 3 × cadence)90s
one upstream ahead, peers stalledsubscribers wait until the peers are benched, then get the held blocks in batches90s
upstream on a minority forkloses its vote, goes last in routingabout 60s
voters disagreethe branch with the most votes; a tie asks non-voting upstreams to settle1 settle
one block's receipts not servedother upstreams, then eth_getLogs; then logs connections close 101360s
chain makes no blocksnothing reconnects or resubscribes—

gRPC StreamBlocks

With server.grpcEnabled, the StreamService.StreamBlocks RPC (evm/stream.proto (opens in a new tab)) streams block headers from the same chain feed as ws newHeads. Auth runs once when the stream opens, as for eth_getBlockByNumber; rate limits count once at open, as for a ws subscription.

Resume. StreamBlocksRequest takes fromBlock and fromHash: the number and hash of the last header the client applied.

RequestStream starts
neither setafter the confirmed head
both set, cursor on the canonical chainat fromBlock + 1, replaying every block up to the confirmed head
both set, cursor on a dropped branchat the fork point + 1
both set, cursor older than chainTracker.maxBackfill or a hash no upstream servesends with OUT_OF_RANGE
only one setINVALID_ARGUMENT

Reorgs. Headers are ascending; after a reorg the stream resends from the fork point + 1. A header whose number is at or below the last one received replaces that number and every number above it. Each header carries hash and parentHash, so a client can check the linkage itself.

End codes.

CodeCauseClient action
UNAVAILABLE60s with no block while the confirmed head stands above the cursor, or one Send blocked for 10sreconnect with the last applied cursor
OUT_OF_RANGEthe cursor left the window, or no upstream serves itbackfill with unary calls, then reopen
INVALID_ARGUMENTonly one of fromBlock, fromHash, or a fromHash not 32 bytesfix the request

A stream at the head of a chain that makes no blocks waits without end.

WebSocket upstreams

To support subscriptions, configure at least one upstream with a ws:// or wss:// endpoint:

erpc.yaml
projects:
  - id: main
    upstreams:
      # Regular HTTP upstream (for standard RPC)
      - id: eth-mainnet-http
        endpoint: https://eth-mainnet.example.com
        evm:
          chainId: 1
 
      # WebSocket upstream (enables subscriptions)
      - id: eth-mainnet-ws
        endpoint: ws://eth-mainnet.example.com:8546
        evm:
          chainId: 1
        failsafe:
          retry:
            maxAttempts: 2
            delay: 100ms
          timeout:
            duration: 30s

WebSocket upstreams also serve regular JSON-RPC requests (not just subscriptions). eRPC's scoring system picks the best upstream regardless of transport — HTTP or WebSocket.

The WebSocket upstream client features:

  • Persistent connection with automatic reconnection — every re-dial waits a jittered exponential backoff (1s to 30s), which resets only after a connection has stayed up for a full keepalive window
  • Ping/pong keepalive (30s interval) to detect dead connections
  • Lazy connection — if the upstream is unavailable at startup, eRPC retries in the background without blocking
  • Fail-fast while reconnecting — requests sent while the connection is down fail immediately with a retryable error so they fail over to other upstreams
  • Half-open detection on timeout — when a request times out, eRPC pings the connection; with no answer within 5s of that first timeout it reconnects, however many more requests time out meanwhile, and the other requests waiting on it fail over at once instead of waiting out the keepalive window
  • Heads subscribed at network init — every subscription source subscribes newHeads as soon as its network initializes, so the head is tracked from pushed headers before any client subscribes
  • Silent subscription recovery — if a newHeads subscription pushes nothing for 15s while the same upstream's head counter stood above its last push, eRPC reconnects to that upstream
  • Unsupported newHeads is polled — if an upstream rejects eth_subscribe newHeads as unsupported, eRPC polls it for heads and asks again on each reconnect and every 10 min

eth_subscribe and eth_unsubscribe are only sent to upstreams by eRPC's own subscription handling. Over HTTP both are rejected with -32601 without reaching any upstream, since a subscription needs a client WebSocket connection to deliver to.

Server configuration

The WebSocket server is enabled and tuned via the webSocket section in server config. Only enabled is required; the other defaults work well for most deployments. WebSocket upstreams (ws:// / wss:// endpoints) work regardless of this setting.

erpc.yaml
server:
  httpPortV4: 4000
  webSocket:
    # Accept WebSocket upgrades on the HTTP port (default: false)
    enabled: true
    # Read buffer size in bytes (default: 4096)
    readBufferSize: 4096
    # Write buffer size in bytes (default: 4096)
    writeBufferSize: 4096
    # Maximum incoming message size in bytes (default: 1048576 = 1MB)
    maxMessageSize: 1048576
    # Ping interval for keepalive (default: 30s). A client that sends neither
    # a pong nor a request within twice this interval is disconnected.
    pingInterval: 30s
    # Maximum active subscriptions per WebSocket connection (default: 100)
    maxSubscriptionsPerConnection: 100
    # Maximum requests a connection runs at once (default: 250)
    maxConcurrentRequestsPerConnection: 250
    # Instance-wide caps; 0 (the default) means unlimited
    maxConnections: 0
    maxConnectionsPerIP: 0
    maxSubscriptions: 0

maxSubscriptionsPerConnection alone does not bound a client: it can open any number of connections. On a public endpoint also set the instance-wide caps:

  • maxConnections — concurrent client connections on the instance. The only connection cap that holds when client IPs are unknown or spoofed.
  • maxConnectionsPerIP — concurrent client connections from one client IP, resolved as for HTTP (see trustedIPForwarders). Together with maxSubscriptionsPerConnection it bounds one client's subscriptions.
  • maxSubscriptions — active subscriptions across all connections on the instance.

A connection over a cap is refused with 429 before the upgrade; a subscription over maxSubscriptions gets a JSON-RPC error and the connection stays open. Refusals are counted in erpc_websocket_rejected_total. The caps are per instance, so a fleet admits up to N times each.

The upgrade request must name a network (/<project-id>/<architecture>/<chain-id>, or a path that domain aliasing resolves to one); otherwise it is rejected with 400. On shutdown eRPC closes every client connection with 1001 (going away) straight away so clients reconnect to another instance; in-flight requests get up to server.waitBeforeShutdown to answer first. New connections are refused with 503 before the upgrade from then on.

Cost frames

A metering proxy in front of eRPC can read per-message cost the way it reads HTTP cost headers (server.costHeaders). Opt in per connection by sending X-ERPC-Cost-Frames: 1 on the upgrade request; it takes effect only while server.costHeaders is true. Otherwise output is plain JSON, as above.

In cost-frame mode every text message eRPC sends starts with a header block in HTTP/1.1 wire form — zero or more Name: value\r\n lines, then \r\n — followed by the unchanged JSON body, all in one WebSocket message:

X-Erpc-Billable: 1\r\n
X-Erpc-Calls: 1\r\n
X-Erpc-Methods: eth_blockNumber\r\n
X-Erpc-Network-Alias: ethereum\r\n
X-Erpc-Network-Id: evm:1\r\n
\r\n
{"jsonrpc":"2.0","id":1,"result":"0x1234567"}
  • Responses (single and batch) carry exactly the cost headers the same calls would get over HTTP (X-ERPC-Calls, X-ERPC-Billable, X-ERPC-Methods, X-ERPC-Credits, X-ERPC-Credits-Total, X-ERPC-Credits-Version, X-ERPC-Network-Id, X-ERPC-Network-Alias). A batch's X-ERPC-Calls counts every request in it, including id-less requests (JSON-RPC notifications) that get no reply entry.
  • Calls that get no reply — an id-less request, or a batch of only those — still ran, so they get a metering-only message: the header block for those calls followed by an empty body. A proxy meters it and never relays it.
  • Messages that routed no call — a batch that is not valid JSON, an empty batch — start with just \r\n.
  • Subscription notifications (eth_subscription) each carry X-ERPC-Calls: 1, X-ERPC-Billable: 1, X-ERPC-Methods: eth_subscription, X-ERPC-Subscription: <newHeads|logs|newPendingTransactions>, X-ERPC-Network-Id and X-ERPC-Network-Alias; no credits.

Header names are case-insensitive, as in HTTP. Cost frames are not valid JSON-RPC: only send the header from a proxy that strips the block before the client sees the message.

Subscription compatibility knobs

HTTP / WebSocket tip-sync considerations for strict consumers

Some RPC consumers compare the block number returned by HTTP eth_getBlockByNumber("latest") against a tip they've observed via a WebSocket newHeads subscription and flag any lag as a health-check failure. On fast-block chains (sub-second to a few seconds) the HTTP round-trip can trivially exceed the inter-block interval, so the HTTP response carries a block that was current when it was generated but older than a newHeads notification that arrived in parallel. That behaviour is inherent to HTTP-vs-push timing and is visible with or without a proxy in front.

eRPC minimises the gap in three ways:

  • Per-block cache keying for moving tags. The realtime cache entry for a latest / finalized request is keyed by the block number the tag currently resolves to, so each tip advance is a distinct key rather than pinning every call within the TTL to the same cached payload.
  • One number for latest. A latest or finalized tag is interpolated to the request's Head before forwarding, so an HTTP eth_getBlockByNumber("latest") names the block eth_blockNumber reports, whichever upstream answers.
  • No head above latest. A head reaches subscribers only at the confirmed head: servedTip.quorum hash voters have it and its number is at most the network's latest, so a newHeads client never sees a block eth_blockNumber does not; one upstream alone moves neither. Details: Block tracking.

Even so, a transient single-block lag can reach a client when the chain produces a block faster than an in-flight HTTP round-trip completes. If your consumer treats single-block HTTP-vs-WS lag as a hard failure, widen its tolerance to match the chain's block time rather than expect eRPC (or any proxy) to eliminate it.

Directives

Request directives can be set via headers or query parameters on the initial WebSocket upgrade request. They apply to every regular RPC request on that connection, batches included, subject to the same allowClientDirectives rules as HTTP:

// Pass directives via query params on the WebSocket URL
const ws = new WebSocket("ws://localhost:4000/main/evm/1?useUpstream=my-preferred-upstream");

Subscriptions (eth_subscribe) read the network-wide chain feed whatever useUpstream says. On a connection with useUpstream, a subscription delivers a block only once that upstream group's latest reaches it.