Skip to content

About

Production ready High Availability load balancer for Ethereum/Solana nodes and RPC providers

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Repository files navigation

haprovider

Release License: MIT Project Status: Active

High Availability Provider is a load balancer for Ethereum (and EVM L2s), Solana, Tron and Bitcoin JSON-RPC nodes — put one stable endpoint in front of your own nodes and providers like Infura/QuickNode/Alchemy, and haprovider health-checks each one and fails over automatically. No more single points of failure, rate-limit outages, or serving stale data from a node that has fallen behind the chain.

flowchart LR
    C[dApp / client] -->|"JSON-RPC / WebSocket"| HA(haprovider)
    HA --> P1["http://node-1:8545"]
    HA --> P2["https://mainnet.infura.io/v3/KEY"]
    HA --> P3["https://eth.llamarpc.com"]
    HA -. "fails over on error, rate-limit (429 / -32005), or block-lag" .-> P2
Loading

Providers are tried in priority order; an unhealthy one is taken out of rotation and re-checked in the background until it recovers.

A WebSocket connection stays with the provider it was opened to. If that provider has been out of rotation for 30 seconds and another provider with a WebSocket URL is healthy, haprovider closes the connection with code 1012 (service restart) so the client reconnects to a healthy one. It does the same once the primary provider has been back for 5 minutes, to move clients back to it.

Reasons for using haprovider

  • Zero downtime - RPC providers can and will have trouble providing you uninterrupted 24/7 access. You should have at least two providers powering your access to a chain, like your own node and a service like Infura as a backup.

  • You run your own node and you don't want to disrupt your service when you take it down for maintenance/upgrades.

  • You don't want to deal with the maintenance and costs of your own nodes for storage intensive Ethereum L2 chains or a local Solana node with high hardware requirements

Table of Contents

Features

  • High Availability: Move any fallback logic from your application layer and rely on one RPC endpoint
  • Automatic Failover: Handles request failures and forwards to the next available node or node provider
  • Traffic Observability: Monitor and analyze your RPC traffic patterns
  • Request Validation: Validates requests and responses to detect errors
  • Rate Limit Handling: Detects rate limits and retries once the provider is available again
  • Request Coalescing: Collapses identical concurrent read requests into a single upstream call and fans the response back to every client
  • Response Verification: Optionally cross-checks balances, contract reads and the chain height against a second provider, so one provider can't get a wrong answer through
  • Transaction Broadcasting: Optionally sends every transaction to all providers at once and checks the hash each answers with, so one provider dropping a transaction can't hold it up
  • Connection Optimization: Upstream keepalive/http2 connection pooling
  • Health Checks: Automatic health monitoring of all configured providers

What haprovider doesn't do right now

  • Response caching

Request coalescing

When several clients send the same read request at the same time, haprovider issues a single upstream call and returns that one response to all of them. This cuts redundant load on your providers and reduces rate-limit (429) exposure under bursty traffic, for example many clients polling eth_getTransactionReceipt for the same hash.

Coalescing is automatic on the HTTP JSON-RPC path and only applies to an allowlist of read-only, idempotent methods per chain; transaction submission, filters, subscriptions and other stateful calls are always sent individually. Batch requests are never coalesced. The haprovider_coalesced_requests_total metric tracks how many requests were served from a shared upstream call.

Response verification

haprovider normally returns the first healthy provider's answer as-is. If you credit payments from what your providers report, one provider returning a wrong balance (a bug, a compromise, a man-in-the-middle) is enough to credit a payment that never happened. With verify: true on an endpoint, haprovider cross-checks the reads such decisions are made from against a second provider:

Chain Cross-checked methods
eth, tron eth_getBalance, eth_call, eth_blockNumber
solana getBalance, getAccountInfo, getMultipleAccounts, getTokenAccountBalance, getBlockHeight, getSlot
endpoints:
  eth_payments:
    chainId: "1"
    verify: true
    providers:
      - name: QuickNode
        http: https://example.quiknode.pro/${QUICKNODE_TOKEN}/
      - name: Infura
        http: https://mainnet.infura.io/v3/${INFURA_KEY}
  • Balances and contract reads must agree. The same value in a different encoding (0xa and 0x0a, letter case) agrees. For Solana only the value is compared, since the context slot almost always differs.
  • A disagreement is asked again once. Providers a block apart disagree on a value that changed in that block (e.g. a payment just arrived). After verify_retry_delay (default 1s) the same two are asked again; if they agree now, the client gets that answer. If they still disagree, a third provider settles it if the endpoint has one. Without a majority the client gets a JSON-RPC error with code -39201 ("providers disagree on the result") instead of either answer, and can retry.
  • Of two block heights, the lower is returned. Providers a block apart are both right; taking the lower one means a provider reporting a too-high height can't inflate the confirmations a client counts from it.
  • Best effort. When no other provider answers (it's down, rate limited, returns an error or a malformed result, or the endpoint has one provider), the first answer is returned unverified, so losing a provider never disrupts traffic. Watch haprovider_verified_results_total{outcome="unverified"}. haprovider also logs a warning, results not verified: <reason>, at most once a minute per endpoint (while a provider is down every checked read is one), with how many there were since the last one, which provider answered, and how many others are online.
  • Both providers are asked at the same time, so a check takes as long as the slower of the two, not both. A second opinion is waited for up to the provider's timeout. Only when the first provider fails, or two disagree, are providers asked again afterwards.
  • Coalesced requests share one check. Identical concurrent requests are answered from a single upstream call (see Request coalescing), and the check happens inside it, so they cost two upstream calls between them and all get the same checked answer.
  • Only what's needed is checked. Error answers aren't compared (they credit nothing), and in a batch only the listed methods are sent to the second provider, so a transaction is never broadcast twice.
  • Not at a block honest providers rarely agree on. Reads at the pending block (eth, tron) and account reads at processed commitment (Solana) aren't cross-checked: each node's view of them is its own.
  • HTTP only. WebSocket connections are pinned to one provider and are not cross-checked.

Cross-checked methods cost twice the upstream requests, and a disagreement adds verify_retry_delay plus one more pair of requests. Enable it on the endpoints serving the reads that credit payments; on one that also serves reads of state that changes every block (prices, anything depending on the block time), honest providers a block apart disagree often.

Transaction broadcasting

Sent to a single provider, a transaction that provider accepts but never broadcasts (a bug, an overloaded mempool, a provider dropping it on purpose) never lands, and the client waits on a hash that leads nowhere. So haprovider sends every transaction to every healthy provider of the endpoint at once:

Chain Broadcast method Hash checked against
eth eth_sendRawTransaction keccak256 of the raw transaction
solana sendTransaction its first signature (legacy and v0 transactions)
  • The first acceptance answers. A provider accepts the transaction by answering with its hash, or by saying it already has it ("already known", "already processed": once one node has a transaction, that's the usual answer from the others). The client gets the hash as soon as any provider accepts; the others still get the transaction, in the background.
  • The hash is checked. haprovider computes each transaction's hash itself. A provider answering with another one is lying or broken: its answer is never used, and it's taken out of rotation. Solana transactions in a newer format (v1) are still broadcast, but the answer is taken without checking it.
  • A rejection comes from the first provider. If no provider accepts the transaction (e.g. insufficient funds, nonce too low), the client gets the error of the first provider, in priority order, that rejected it. A rejection is about the transaction, so it never takes a provider out of rotation.
  • Only transactions are broadcast. In a batch, the rest goes the usual way. WebSocket connections are pinned to one provider and don't broadcast.
  • No private providers alongside public ones. A private or MEV-protected provider (one that keeps transactions out of the public mempool) on the same endpoint as public ones gets no protection: the public ones get the transaction too.

Each transaction costs one request per provider.

Installation

# Prebuilt binary: download from the releases page
# https://github.com/wille/haprovider/releases

# Using Go
go install github.com/wille/haprovider/cmd/haprovider@latest

# Using Docker
docker pull ghcr.io/wille/haprovider

Quick Start

  1. Create a configuration file config.yml:
endpoints:
  ethereum:
    kind: eth
    chainId: "1"
    providers:
      - name: Local node
        http: http://localhost:8145
        ws: ws://localhost:8146
      - name: backup
        http: https://eth.llamarpc.com
  1. Start the service:
$ haprovider

On startup haprovider connects to every configured provider, validates each one (chain id, block height, client version) and starts serving once at least one is healthy. Running against config.example.yml (output abbreviated):

$ haprovider --config config.example.yml
INF starting haprovider version=dev healthcheck_interval=30s
INF connecting to provider=eth/PublicNode http=https://ethereum-rpc.publicnode.com
INF connecting to provider=solana/PublicNode http=https://solana-rpc.publicnode.com
INF connecting to provider=bitcoin/PublicNode http=https://bitcoin-rpc.publicnode.com
# … one line per configured provider …
INF provider connected provider=eth/PublicNode client_version=Geth/v1.17.1-stable chain_id=1 block_height=25426434 took=137ms
INF provider connected provider=base/PublicNode client_version=reth/v2.3.0 chain_id=8453 block_height=47992129 took=140ms
INF provider connected provider=solana/PublicNode client_version=4.0.3 chain_id=mainnet block_height=407831156 took=143ms
INF provider connected provider=tron/TronGrid client_version=TRON/v4.8.1/Linux/Java1.8 chain_id=mainnet block_height=84034632 took=222ms
INF provider connected provider=bitcoin/PublicNode client_version=/Satoshi:29.3.0/ chain_id=mainnet block_height=955985 took=421ms
ERR provider failed provider=eth/dRPC error="http 500: rpc 31: Batch of more than 3 requests are not allowed on free tier …"
ERR provider failed provider=eth/Ankr error="rpc -32000: Unauthorized: You must authenticate your request with an API key …"
INF started. 14/21 providers connected version=dev addr=:8080

Or with command line options:

$ haprovider --config config.yml --log-level debug --log-json
  1. Connect your application:
import { ethers } from 'ethers';

// ethers.js v6
const provider = new ethers.JsonRpcProvider('http://localhost:8080/eth');
// or
const provider = new ethers.WebSocketProvider('ws://localhost:8080/eth');

Configuration

The configuration file supports the following options. Unknown or repeated keys are an error, so a misspelled setting stops haprovider at startup instead of being silently ignored.

# Global settings
port: 8080
log_level: info  # debug, info, warn, error
log_json: false  # Enable JSON logging

# Endpoint configurations
endpoints:
  ethereum:
    kind: eth
    chainId: "1"
    providers:
      - name: Local node
        http: http://localhost:8145
        ws: ws://localhost:8146
        timeout: 10s
      - name: Infura
        http: https://mainnet.infura.io/v3/${INFURA_KEY}
        ws: wss://mainnet.infura.io/ws/v3/${INFURA_KEY}
  solana:
    kind: solana
    chainId: mainnet
    providers:
      - name: quicknode
        http: https://solana-mainnet.quicknode.pro/${QUICKNODE_TOKEN}

Provider http and ws URLs, provider headers values, and keys expand ${ENV_VAR} references, so API keys can live in the environment (e.g. a Kubernetes Secret) instead of the config file. See Environment variables.

Configuration Options

  • port: HTTP/WS server port (default: 8080)
  • metrics_port: Prometheus port (default: none)
  • healthcheck_interval: How often each provider is health-checked (e.g. 10s, 1m) (default: 30s)
  • real_ip_header: Header carrying the real client IP when running behind a trusted proxy/load balancer, e.g. Cf-Connecting-Ip or X-Forwarded-For (optional; used for logging and the upstream X-Forwarded-For). Only enable behind a proxy you trust to set it, since clients can otherwise spoof it. ($HA_REAL_IP_HEADER)
  • log_level: Logging level (debug, info, warn, error)
  • log_json: Enable JSON logs
  • keys: Global inbound API keys accepted on every endpoint (optional). See Authentication.
  • endpoints: Map of endpoint configurations
    • kind: Chain type (eth, solana, tron, btc) (default: eth). Bitcoin (btc) endpoints only pass through blockchain-query RPCs (block/chain/mempool/txout reads plus getrawtransaction/sendrawtransaction); wallet, mining, and node-control commands are rejected. Tron does not yet support the solidity (solidity-node) API. The native TRON HTTP API passthrough (/<endpoint>/wallet/...) only forwards GET/POST requests under wallet/, walletsolidity/ and walletpbft/; other paths return 404.
    • chainId: The network the endpoint serves (required). Every provider must report it, or it's taken out of rotation:
      • eth: the decimal EIP-155 chain id, e.g. "1" for Ethereum mainnet or "8453" for Base
      • solana: mainnet, devnet, testnet, or the genesis hash of another network (e.g. a local test validator)
      • tron: mainnet, nile or shasta
      • btc: mainnet, testnet3, testnet4, signet, or the genesis block hash of another network (e.g. regtest), in lower case. A mainnet provider must also have Bitcoin's block at height 840000, which tells it apart from forks that share Bitcoin's genesis block (Bitcoin Cash, SV, Gold).
    • block_lag_tolerance: How many blocks a provider may trail, or lead, the median block height of the endpoint's providers before it's considered unhealthy (optional, per-chain default: 50 for eth and solana, 10 for tron, 0 for btc; leading is allowed at least 3 blocks). Only applies when at least 3 providers report a height: with two, nothing tells the one lagging behind from the one lying ahead, so neither is judged by the other's height. One provider reporting a wrong height can't push the others out of rotation.
    • stall_timeout: How long a provider's block height may stay unchanged while another provider reports a higher one before it's considered stalled, e.g. 90s (optional, per-chain default: 2m, or 2h for btc; 0 disables). Works with any number of providers. A chain that has halted takes no provider out.
    • max_response_size: Max upstream response size in bytes (optional, default 100MB, 0 = unlimited)
    • keys: Inbound API keys accepted for this endpoint, in addition to any global keys (optional). See Authentication.
    • public: If this endpoint is available to the public. A public endpoint will not include detailed error messages and headers (optional, default false). Note: public does not disable authentication — if keys apply to the endpoint, a valid token is still required.
    • add_xfwd_headers: Add X-Forwarded-For to upstream requests (optional, default false)
    • verify: Cross-check balances, contract reads and the chain height against a second provider (optional, default false). See Response verification.
    • verify_retry_delay: With verify, how long to wait before asking two disagreeing providers once more, e.g. 500ms (optional, default 1s; 0 asks only once)
    • providers: List of provider configurations
      • name: Provider identifier (optional, defaults to the http URL's host)
      • http: HTTP endpoint URL (required, expands ${ENV_VAR}). Redirects are never followed: a provider that answers with one is treated as failing, so configure the final URL (e.g. https://, not an http:// that redirects to it).
      • ws: WebSocket endpoint URL (optional, expands ${ENV_VAR}). Redirects on the handshake are not followed either.
      • headers: Extra headers sent to the provider (optional, values expand ${ENV_VAR})
      • timeout: Request timeout (optional, default 10s)

Environment variables

${ENV_VAR} (or $ENV_VAR) references are expanded when the config is loaded, in:

  • provider http and ws URLs
  • provider headers values
  • global and per-endpoint keys
endpoints:
  eth:
    chainId: "1"
    providers:
      - name: quicknode
        http: https://example.quiknode.pro/${QUICKNODE_TOKEN}/
        ws: wss://example.quiknode.pro/${QUICKNODE_TOKEN}/

In provider URLs, a reference to an unset or empty variable stops haprovider at startup with an error naming the provider and the variable, rather than starting with a URL that is missing its key. A literal $ in a URL must be percent-encoded as %24.

URLs are logged as scheme://host only, and an unnamed provider is named after its host, so keep API keys in the URL's path, query or userinfo, never in the hostname.

Authentication

haprovider can require callers to authenticate with a bearer token. Configure one or more keys, either globally or per endpoint:

# Accepted on every endpoint
keys:
  - ${HAPROVIDER_KEY}       # values support ${ENV_VAR} expansion

endpoints:
  eth:
    chainId: "1"
    # Additional keys accepted only on this endpoint (e.g. a per-service key)
    keys:
      - ${ETH_SERVICE_KEY}
    providers:
      - name: node
        http: http://localhost:8545

Clients pass the token in the Authorization header:

Authorization: Bearer <key>

Behavior:

  • Opt-in per endpoint. An endpoint requires authentication only if it has keys that apply to it (its own keys plus the global keys). Endpoints with no applicable keys stay open, so existing setups keep working.
  • Multiple keys are accepted, which lets you rotate keys with no downtime or hand out different keys to different services.
  • Env expansion. Key values are expanded with os.ExpandEnv, so you can keep secrets out of the config file (- ${HAPROVIDER_KEY}). Provider URLs expand too; see Environment variables.
  • Requests with a missing or invalid token get 401 Unauthorized. Authentication is enforced for HTTP JSON-RPC, the TRON HTTP API path, and WebSocket upgrades alike.
  • public: true does not bypass authentication — it only suppresses debug headers and detailed error messages. A public endpoint with keys still requires a valid token.

Command Line Options

  • --config: Path to config file (default: config.yml). Raw config YAML can be provided via $HA_CONFIG
  • --port: HTTP/WS server address (default: :8080) ($HA_PORT)
  • --metrics-port: Prometheus port (default: none) ($HA_METRICS_PORT)
  • --log-level: Logging level (debug, info, warn, error) (default: info) ($HA_LOG_LEVEL)
  • --log-json: Enable JSON logging (default: false) ($HA_LOG_JSON)
  • --real-ip-header: Header carrying the real client IP when behind a trusted proxy, e.g. Cf-Connecting-Ip ($HA_REAL_IP_HEADER)

Note

Command line arguments take precedence over configuration file settings. For example, if you specify --log-level debug on the command line, it will override the log_level setting in the config file.

Examples

Ethereum with Multiple Providers

endpoints:
  ethereum:
    kind: eth
    chainId: "1"
    providers:
      - name: Local node
        http: http://localhost:8145
        ws: ws://localhost:8146
      - name: Infura
        http: https://mainnet.infura.io/v3/${INFURA_KEY}
        ws: wss://mainnet.infura.io/ws/v3/${INFURA_KEY}
      - name: QuickNode
        http: https://mainnet.quicknode.pro/${QUICKNODE_TOKEN}
        ws: wss://mainnet.quicknode.pro/${QUICKNODE_TOKEN}

Solana Configuration

endpoints:
  solana:
    kind: solana
    chainId: mainnet
    providers:
      - name: quicknode
        http: https://solana-mainnet.quicknode.pro/${QUICKNODE_TOKEN}
      - name: fallback
        http: https://solana.rpc.helius.network

Monitoring

haprovider exposes Prometheus metrics for monitoring:

  • haprovider_requests_total: Total number of requests (labels: endpoint, provider, transport, method)
  • haprovider_failed_requests_total: Failed requests (labels: endpoint, provider, transport, method)
  • haprovider_request_duration_seconds: Request duration histogram
  • haprovider_inflight_requests: Requests currently being processed (labels: endpoint, transport)
  • haprovider_open_connections: Currently open WebSocket connections
  • haprovider_total_connections: Total WebSocket connections established
  • haprovider_provider_health: Provider health status (1=healthy, 0=unhealthy)
  • haprovider_provider_uptime_seconds: How long the provider has been continuously online, in seconds (0 if offline)
  • haprovider_provider_block_height: The block height each provider last reported in a healthcheck (labels: endpoint, provider), including one judged behind, ahead or stalled. Absent while the provider isn't reporting one (unreachable, syncing, on the wrong chain)
  • haprovider_verified_results_total: Results cross-checked against another provider on endpoints with verify: true (labels: endpoint, method, outcome). outcome is agree, agree_after_retry (they disagreed, then agreed when asked again: providers a block apart), majority (a third provider settled a disagreement), disagree (no majority; the client got an error) or unverified (no other provider answered). majority and disagree mean a provider returned a wrong answer and are worth alerting on
  • haprovider_broadcast_results_total: Each provider's answer to a transaction broadcast (labels: endpoint, provider, method, outcome). outcome is accepted, already_known, rejected (an error, e.g. insufficient funds), failed (no answer) or wrong_hash (it answered with another transaction's hash, which is worth alerting on)

The method label is the JSON-RPC method (or TRON API path) only once a provider has answered it successfully; until then, and for names no provider recognizes, it is other. This stops clients from creating unbounded time series by sending made-up method names.

Enable metrics with configuration option metrics_port: 127.0.0.1:9090

The block heights show what the block-lag check acts on. For example:

# Each provider's height, side by side
haprovider_provider_block_height

# How far each provider trails the median of its endpoint's providers, which
# block_lag_tolerance is compared with once 3 or more report (Prometheus
# averages the two middle heights where haprovider takes one of them)
quantile by (endpoint) (0.5, haprovider_provider_block_height)
  - on (endpoint) group_right haprovider_provider_block_height

# A provider that stopped advancing (what stall_timeout catches)
changes(haprovider_provider_block_height[5m]) == 0

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

About

Production ready High Availability load balancer for Ethereum/Solana nodes and RPC providers

Topics

Resources

Stars

6 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages